`_
-
-
-
-Platform: any
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Environment :: Web Environment
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 2
-Classifier: Programming Language :: Python :: 2.7
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.3
-Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
-Classifier: Topic :: Software Development :: Libraries :: Python Modules
diff --git a/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/SOURCES.txt
deleted file mode 100644
index 0202fcb..0000000
--- a/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-LICENSE
-MANIFEST.in
-README.rst
-setup.cfg
-setup.py
-tests.py
-Flask_Script.egg-info/PKG-INFO
-Flask_Script.egg-info/SOURCES.txt
-Flask_Script.egg-info/dependency_links.txt
-Flask_Script.egg-info/not-zip-safe
-Flask_Script.egg-info/requires.txt
-Flask_Script.egg-info/top_level.txt
-docs/Makefile
-docs/conf.py
-docs/index.rst
-docs/make.bat
-docs/_static/flask-script.png
-docs/_static/index.html
-docs/_themes/README
-docs/_themes/flask_theme_support.py
-docs/_themes/flask/theme.conf
-docs/_themes/flask/static/flasky.css_t
-docs/_themes/flask_small/layout.html
-docs/_themes/flask_small/theme.conf
-docs/_themes/flask_small/static/flasky.css_t
-flask_script/__init__.py
-flask_script/_compat.py
-flask_script/cli.py
-flask_script/commands.py
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/installed-files.txt
deleted file mode 100644
index 2a196af..0000000
--- a/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/installed-files.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-../flask_script/__init__.py
-../flask_script/_compat.py
-../flask_script/cli.py
-../flask_script/commands.py
-../flask_script/__init__.pyc
-../flask_script/_compat.pyc
-../flask_script/cli.pyc
-../flask_script/commands.pyc
-./
-dependency_links.txt
-not-zip-safe
-PKG-INFO
-requires.txt
-SOURCES.txt
-top_level.txt
diff --git a/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/requires.txt b/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/requires.txt
deleted file mode 100644
index 2077213..0000000
--- a/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/requires.txt
+++ /dev/null
@@ -1 +0,0 @@
-Flask
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/top_level.txt
deleted file mode 100644
index efd6af0..0000000
--- a/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-flask_script
diff --git a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/PKG-INFO b/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/PKG-INFO
deleted file mode 100644
index 2c6a330..0000000
--- a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/PKG-INFO
+++ /dev/null
@@ -1,55 +0,0 @@
-Metadata-Version: 1.1
-Name: Jinja2
-Version: 2.7.2
-Summary: A small but fast and easy to use stand-alone template engine written in pure python.
-Home-page: http://jinja.pocoo.org/
-Author: Armin Ronacher
-Author-email: armin.ronacher@active-4.com
-License: BSD
-Description:
- Jinja2
- ~~~~~~
-
- Jinja2 is a template engine written in pure Python. It provides a
- `Django`_ inspired non-XML syntax but supports inline expressions and
- an optional `sandboxed`_ environment.
-
- Nutshell
- --------
-
- Here a small example of a Jinja template::
-
- {% extends 'base.html' %}
- {% block title %}Memberlist{% endblock %}
- {% block content %}
-
- {% endblock %}
-
- Philosophy
- ----------
-
- Application logic is for the controller but don't try to make the life
- for the template designer too hard by giving him too few functionality.
-
- For more informations visit the new `Jinja2 webpage`_ and `documentation`_.
-
- .. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security)
- .. _Django: http://www.djangoproject.com/
- .. _Jinja2 webpage: http://jinja.pocoo.org/
- .. _documentation: http://jinja.pocoo.org/2/documentation/
-
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Environment :: Web Environment
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 3
-Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
-Classifier: Topic :: Software Development :: Libraries :: Python Modules
-Classifier: Topic :: Text Processing :: Markup :: HTML
diff --git a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/SOURCES.txt
deleted file mode 100644
index a27a9c4..0000000
--- a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,126 +0,0 @@
-AUTHORS
-CHANGES
-LICENSE
-MANIFEST.in
-Makefile
-README.rst
-run-tests.py
-setup.cfg
-setup.py
-Jinja2.egg-info/PKG-INFO
-Jinja2.egg-info/SOURCES.txt
-Jinja2.egg-info/dependency_links.txt
-Jinja2.egg-info/entry_points.txt
-Jinja2.egg-info/not-zip-safe
-Jinja2.egg-info/requires.txt
-Jinja2.egg-info/top_level.txt
-artwork/jinjalogo.svg
-docs/Makefile
-docs/api.rst
-docs/cache_extension.py
-docs/changelog.rst
-docs/conf.py
-docs/contents.rst.inc
-docs/extensions.rst
-docs/faq.rst
-docs/index.rst
-docs/integration.rst
-docs/intro.rst
-docs/jinjaext.py
-docs/jinjastyle.sty
-docs/latexindex.rst
-docs/logo.pdf
-docs/sandbox.rst
-docs/switching.rst
-docs/templates.rst
-docs/tricks.rst
-docs/_static/.ignore
-docs/_static/jinja-small.png
-docs/_templates/sidebarintro.html
-docs/_templates/sidebarlogo.html
-docs/_themes/LICENSE
-docs/_themes/README
-docs/_themes/jinja/layout.html
-docs/_themes/jinja/relations.html
-docs/_themes/jinja/theme.conf
-docs/_themes/jinja/static/jinja.css_t
-examples/bench.py
-examples/profile.py
-examples/basic/cycle.py
-examples/basic/debugger.py
-examples/basic/inheritance.py
-examples/basic/test.py
-examples/basic/test_filter_and_linestatements.py
-examples/basic/test_loop_filter.py
-examples/basic/translate.py
-examples/basic/templates/broken.html
-examples/basic/templates/subbroken.html
-examples/rwbench/djangoext.py
-examples/rwbench/rwbench.py
-examples/rwbench/django/_form.html
-examples/rwbench/django/_input_field.html
-examples/rwbench/django/_textarea.html
-examples/rwbench/django/index.html
-examples/rwbench/django/layout.html
-examples/rwbench/genshi/helpers.html
-examples/rwbench/genshi/index.html
-examples/rwbench/genshi/layout.html
-examples/rwbench/jinja/helpers.html
-examples/rwbench/jinja/index.html
-examples/rwbench/jinja/layout.html
-examples/rwbench/mako/helpers.html
-examples/rwbench/mako/index.html
-examples/rwbench/mako/layout.html
-ext/djangojinja2.py
-ext/inlinegettext.py
-ext/jinja.el
-ext/Vim/jinja.vim
-ext/django2jinja/django2jinja.py
-ext/django2jinja/example.py
-ext/django2jinja/templates/index.html
-ext/django2jinja/templates/layout.html
-ext/django2jinja/templates/subtemplate.html
-jinja2/__init__.py
-jinja2/_compat.py
-jinja2/_stringdefs.py
-jinja2/bccache.py
-jinja2/compiler.py
-jinja2/constants.py
-jinja2/debug.py
-jinja2/defaults.py
-jinja2/environment.py
-jinja2/exceptions.py
-jinja2/ext.py
-jinja2/filters.py
-jinja2/lexer.py
-jinja2/loaders.py
-jinja2/meta.py
-jinja2/nodes.py
-jinja2/optimizer.py
-jinja2/parser.py
-jinja2/runtime.py
-jinja2/sandbox.py
-jinja2/tests.py
-jinja2/utils.py
-jinja2/visitor.py
-jinja2/testsuite/__init__.py
-jinja2/testsuite/api.py
-jinja2/testsuite/bytecode_cache.py
-jinja2/testsuite/core_tags.py
-jinja2/testsuite/debug.py
-jinja2/testsuite/doctests.py
-jinja2/testsuite/ext.py
-jinja2/testsuite/filters.py
-jinja2/testsuite/imports.py
-jinja2/testsuite/inheritance.py
-jinja2/testsuite/lexnparse.py
-jinja2/testsuite/loader.py
-jinja2/testsuite/regression.py
-jinja2/testsuite/security.py
-jinja2/testsuite/tests.py
-jinja2/testsuite/utils.py
-jinja2/testsuite/res/__init__.py
-jinja2/testsuite/res/templates/broken.html
-jinja2/testsuite/res/templates/syntaxerror.html
-jinja2/testsuite/res/templates/test.html
-jinja2/testsuite/res/templates/foo/test.html
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/entry_points.txt b/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/entry_points.txt
deleted file mode 100644
index 32e6b75..0000000
--- a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/entry_points.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-
- [babel.extractors]
- jinja2 = jinja2.ext:babel_extract[i18n]
-
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/installed-files.txt
deleted file mode 100644
index f709693..0000000
--- a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/installed-files.txt
+++ /dev/null
@@ -1,92 +0,0 @@
-../jinja2/__init__.py
-../jinja2/_compat.py
-../jinja2/_stringdefs.py
-../jinja2/bccache.py
-../jinja2/compiler.py
-../jinja2/constants.py
-../jinja2/debug.py
-../jinja2/defaults.py
-../jinja2/environment.py
-../jinja2/exceptions.py
-../jinja2/ext.py
-../jinja2/filters.py
-../jinja2/lexer.py
-../jinja2/loaders.py
-../jinja2/meta.py
-../jinja2/nodes.py
-../jinja2/optimizer.py
-../jinja2/parser.py
-../jinja2/runtime.py
-../jinja2/sandbox.py
-../jinja2/tests.py
-../jinja2/utils.py
-../jinja2/visitor.py
-../jinja2/testsuite/__init__.py
-../jinja2/testsuite/api.py
-../jinja2/testsuite/bytecode_cache.py
-../jinja2/testsuite/core_tags.py
-../jinja2/testsuite/debug.py
-../jinja2/testsuite/doctests.py
-../jinja2/testsuite/ext.py
-../jinja2/testsuite/filters.py
-../jinja2/testsuite/imports.py
-../jinja2/testsuite/inheritance.py
-../jinja2/testsuite/lexnparse.py
-../jinja2/testsuite/loader.py
-../jinja2/testsuite/regression.py
-../jinja2/testsuite/security.py
-../jinja2/testsuite/tests.py
-../jinja2/testsuite/utils.py
-../jinja2/testsuite/res/__init__.py
-../jinja2/testsuite/res/templates/broken.html
-../jinja2/testsuite/res/templates/syntaxerror.html
-../jinja2/testsuite/res/templates/test.html
-../jinja2/testsuite/res/templates/foo/test.html
-../jinja2/__init__.pyc
-../jinja2/_compat.pyc
-../jinja2/_stringdefs.pyc
-../jinja2/bccache.pyc
-../jinja2/compiler.pyc
-../jinja2/constants.pyc
-../jinja2/debug.pyc
-../jinja2/defaults.pyc
-../jinja2/environment.pyc
-../jinja2/exceptions.pyc
-../jinja2/ext.pyc
-../jinja2/filters.pyc
-../jinja2/lexer.pyc
-../jinja2/loaders.pyc
-../jinja2/meta.pyc
-../jinja2/nodes.pyc
-../jinja2/optimizer.pyc
-../jinja2/parser.pyc
-../jinja2/runtime.pyc
-../jinja2/sandbox.pyc
-../jinja2/tests.pyc
-../jinja2/utils.pyc
-../jinja2/visitor.pyc
-../jinja2/testsuite/__init__.pyc
-../jinja2/testsuite/api.pyc
-../jinja2/testsuite/bytecode_cache.pyc
-../jinja2/testsuite/core_tags.pyc
-../jinja2/testsuite/debug.pyc
-../jinja2/testsuite/doctests.pyc
-../jinja2/testsuite/ext.pyc
-../jinja2/testsuite/filters.pyc
-../jinja2/testsuite/imports.pyc
-../jinja2/testsuite/inheritance.pyc
-../jinja2/testsuite/lexnparse.pyc
-../jinja2/testsuite/loader.pyc
-../jinja2/testsuite/regression.pyc
-../jinja2/testsuite/security.pyc
-../jinja2/testsuite/tests.pyc
-../jinja2/testsuite/utils.pyc
-../jinja2/testsuite/res/__init__.pyc
-./
-dependency_links.txt
-entry_points.txt
-not-zip-safe
-PKG-INFO
-requires.txt
-SOURCES.txt
-top_level.txt
diff --git a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/requires.txt b/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/requires.txt
deleted file mode 100644
index ccd0e92..0000000
--- a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/requires.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-markupsafe
-
-[i18n]
-Babel>=0.8
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/top_level.txt
deleted file mode 100644
index 7f7afbf..0000000
--- a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-jinja2
diff --git a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/PKG-INFO b/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/PKG-INFO
deleted file mode 100644
index 91b8ec7..0000000
--- a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/PKG-INFO
+++ /dev/null
@@ -1,71 +0,0 @@
-Metadata-Version: 1.1
-Name: Mako
-Version: 0.9.1
-Summary: A super-fast templating language that borrows the best ideas from the existing templating languages.
-Home-page: http://www.makotemplates.org/
-Author: Mike Bayer
-Author-email: mike@zzzcomputing.com
-License: MIT
-Description: =========================
- Mako Templates for Python
- =========================
-
- Mako is a template library written in Python. It provides a familiar, non-XML
- syntax which compiles into Python modules for maximum performance. Mako's
- syntax and API borrows from the best ideas of many others, including Django
- templates, Cheetah, Myghty, and Genshi. Conceptually, Mako is an embedded
- Python (i.e. Python Server Page) language, which refines the familiar ideas
- of componentized layout and inheritance to produce one of the most
- straightforward and flexible models available, while also maintaining close
- ties to Python calling and scoping semantics.
-
- Nutshell
- ========
-
- ::
-
- <%inherit file="base.html"/>
- <%
- rows = [[v for v in range(0,10)] for row in range(0,10)]
- %>
-
- % for row in rows:
- ${makerow(row)}
- % endfor
-
-
- <%def name="makerow(row)">
-
- % for name in row:
- ${name} | \
- % endfor
-
- %def>
-
- Philosophy
- ===========
-
- Python is a great scripting language. Don't reinvent the wheel...your templates can handle it !
-
- Documentation
- ==============
-
- See documentation for Mako at http://www.makotemplates.org/docs/
-
- License
- ========
-
- Mako is licensed under an MIT-style license (see LICENSE).
- Other incorporated projects may be licensed under different licenses.
- All licenses allow for non-commercial and commercial use.
-
-Keywords: templates
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Environment :: Web Environment
-Classifier: Intended Audience :: Developers
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: Implementation :: CPython
-Classifier: Programming Language :: Python :: Implementation :: PyPy
-Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
diff --git a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/SOURCES.txt
deleted file mode 100644
index 6f580c3..0000000
--- a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,173 +0,0 @@
-CHANGES
-LICENSE
-MANIFEST.in
-README.rst
-distribute_setup.py
-setup.cfg
-setup.py
-Mako.egg-info/PKG-INFO
-Mako.egg-info/SOURCES.txt
-Mako.egg-info/dependency_links.txt
-Mako.egg-info/entry_points.txt
-Mako.egg-info/not-zip-safe
-Mako.egg-info/requires.txt
-Mako.egg-info/top_level.txt
-doc/caching.html
-doc/defs.html
-doc/filtering.html
-doc/genindex.html
-doc/index.html
-doc/inheritance.html
-doc/namespaces.html
-doc/runtime.html
-doc/search.html
-doc/searchindex.js
-doc/syntax.html
-doc/unicode.html
-doc/usage.html
-doc/_sources/caching.txt
-doc/_sources/defs.txt
-doc/_sources/filtering.txt
-doc/_sources/index.txt
-doc/_sources/inheritance.txt
-doc/_sources/namespaces.txt
-doc/_sources/runtime.txt
-doc/_sources/syntax.txt
-doc/_sources/unicode.txt
-doc/_sources/usage.txt
-doc/_static/basic.css
-doc/_static/comment-bright.png
-doc/_static/comment-close.png
-doc/_static/comment.png
-doc/_static/default.css
-doc/_static/docs.css
-doc/_static/doctools.js
-doc/_static/down-pressed.png
-doc/_static/down.png
-doc/_static/file.png
-doc/_static/jquery.js
-doc/_static/makoLogo.png
-doc/_static/minus.png
-doc/_static/plus.png
-doc/_static/pygments.css
-doc/_static/searchtools.js
-doc/_static/sidebar.js
-doc/_static/site.css
-doc/_static/underscore.js
-doc/_static/up-pressed.png
-doc/_static/up.png
-doc/_static/websupport.js
-doc/build/Makefile
-doc/build/caching.rst
-doc/build/conf.py
-doc/build/defs.rst
-doc/build/filtering.rst
-doc/build/index.rst
-doc/build/inheritance.rst
-doc/build/namespaces.rst
-doc/build/runtime.rst
-doc/build/syntax.rst
-doc/build/unicode.rst
-doc/build/usage.rst
-doc/build/builder/__init__.py
-doc/build/builder/builders.py
-doc/build/builder/util.py
-doc/build/static/docs.css
-doc/build/static/makoLogo.png
-doc/build/static/site.css
-doc/build/templates/base.mako
-doc/build/templates/genindex.mako
-doc/build/templates/layout.mako
-doc/build/templates/page.mako
-doc/build/templates/rtd_layout.mako
-doc/build/templates/search.mako
-examples/bench/basic.py
-examples/bench/cheetah/footer.tmpl
-examples/bench/cheetah/header.tmpl
-examples/bench/cheetah/template.tmpl
-examples/bench/django/templatetags/__init__.py
-examples/bench/django/templatetags/bench.py
-examples/bench/kid/base.kid
-examples/bench/kid/template.kid
-examples/bench/myghty/base.myt
-examples/bench/myghty/template.myt
-examples/wsgi/run_wsgi.py
-mako/__init__.py
-mako/_ast_util.py
-mako/ast.py
-mako/cache.py
-mako/codegen.py
-mako/compat.py
-mako/exceptions.py
-mako/filters.py
-mako/lexer.py
-mako/lookup.py
-mako/parsetree.py
-mako/pygen.py
-mako/pyparser.py
-mako/runtime.py
-mako/template.py
-mako/util.py
-mako/ext/__init__.py
-mako/ext/autohandler.py
-mako/ext/babelplugin.py
-mako/ext/beaker_cache.py
-mako/ext/preprocessors.py
-mako/ext/pygmentplugin.py
-mako/ext/turbogears.py
-scripts/mako-render
-test/__init__.py
-test/sample_module_namespace.py
-test/test_ast.py
-test/test_babelplugin.py
-test/test_block.py
-test/test_cache.py
-test/test_call.py
-test/test_decorators.py
-test/test_def.py
-test/test_exceptions.py
-test/test_filters.py
-test/test_inheritance.py
-test/test_lexer.py
-test/test_lookup.py
-test/test_loop.py
-test/test_lru.py
-test/test_namespace.py
-test/test_pygen.py
-test/test_runtime.py
-test/test_template.py
-test/test_tgplugin.py
-test/test_util.py
-test/util.py
-test/foo/__init__.py
-test/foo/test_ns.py
-test/templates/badbom.html
-test/templates/bom.html
-test/templates/bommagic.html
-test/templates/chs_unicode.html
-test/templates/chs_unicode_py3k.html
-test/templates/chs_utf8.html
-test/templates/crlf.html
-test/templates/gettext.mako
-test/templates/index.html
-test/templates/internationalization.html
-test/templates/modtest.html
-test/templates/read_unicode.html
-test/templates/read_unicode_py3k.html
-test/templates/runtimeerr.html
-test/templates/runtimeerr_py3k.html
-test/templates/unicode.html
-test/templates/unicode_arguments.html
-test/templates/unicode_arguments_py3k.html
-test/templates/unicode_code.html
-test/templates/unicode_code_py3k.html
-test/templates/unicode_expr.html
-test/templates/unicode_expr_py3k.html
-test/templates/unicode_runtime_error.html
-test/templates/unicode_syntax_error.html
-test/templates/foo/modtest.html.py
-test/templates/othersubdir/foo.html
-test/templates/subdir/incl.html
-test/templates/subdir/index.html
-test/templates/subdir/modtest.html
-test/templates/subdir/foo/modtest.html.py
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/entry_points.txt b/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/entry_points.txt
deleted file mode 100644
index 3717629..0000000
--- a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/entry_points.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-
- [python.templating.engines]
- mako = mako.ext.turbogears:TGPlugin
-
- [pygments.lexers]
- mako = mako.ext.pygmentplugin:MakoLexer
- html+mako = mako.ext.pygmentplugin:MakoHtmlLexer
- xml+mako = mako.ext.pygmentplugin:MakoXmlLexer
- js+mako = mako.ext.pygmentplugin:MakoJavascriptLexer
- css+mako = mako.ext.pygmentplugin:MakoCssLexer
-
- [babel.extractors]
- mako = mako.ext.babelplugin:extract
-
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/installed-files.txt
deleted file mode 100644
index ae92144..0000000
--- a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/installed-files.txt
+++ /dev/null
@@ -1,55 +0,0 @@
-../mako/__init__.py
-../mako/_ast_util.py
-../mako/ast.py
-../mako/cache.py
-../mako/codegen.py
-../mako/compat.py
-../mako/exceptions.py
-../mako/filters.py
-../mako/lexer.py
-../mako/lookup.py
-../mako/parsetree.py
-../mako/pygen.py
-../mako/pyparser.py
-../mako/runtime.py
-../mako/template.py
-../mako/util.py
-../mako/ext/__init__.py
-../mako/ext/autohandler.py
-../mako/ext/babelplugin.py
-../mako/ext/beaker_cache.py
-../mako/ext/preprocessors.py
-../mako/ext/pygmentplugin.py
-../mako/ext/turbogears.py
-../mako/__init__.pyc
-../mako/_ast_util.pyc
-../mako/ast.pyc
-../mako/cache.pyc
-../mako/codegen.pyc
-../mako/compat.pyc
-../mako/exceptions.pyc
-../mako/filters.pyc
-../mako/lexer.pyc
-../mako/lookup.pyc
-../mako/parsetree.pyc
-../mako/pygen.pyc
-../mako/pyparser.pyc
-../mako/runtime.pyc
-../mako/template.pyc
-../mako/util.pyc
-../mako/ext/__init__.pyc
-../mako/ext/autohandler.pyc
-../mako/ext/babelplugin.pyc
-../mako/ext/beaker_cache.pyc
-../mako/ext/preprocessors.pyc
-../mako/ext/pygmentplugin.pyc
-../mako/ext/turbogears.pyc
-./
-dependency_links.txt
-entry_points.txt
-not-zip-safe
-PKG-INFO
-requires.txt
-SOURCES.txt
-top_level.txt
-../../../../bin/mako-render
diff --git a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/requires.txt b/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/requires.txt
deleted file mode 100644
index 8d60d23..0000000
--- a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/requires.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-MarkupSafe>=0.9.2
-
-[beaker]
-Beaker>=1.1
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/top_level.txt
deleted file mode 100644
index 2951cdd..0000000
--- a/Darwin/lib/python2.7/site-packages/Mako-0.9.1-py2.7.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-mako
diff --git a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/PKG-INFO b/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/PKG-INFO
deleted file mode 100644
index 12aa93e..0000000
--- a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/PKG-INFO
+++ /dev/null
@@ -1,119 +0,0 @@
-Metadata-Version: 1.1
-Name: MarkupSafe
-Version: 0.23
-Summary: Implements a XML/HTML/XHTML Markup safe string for Python
-Home-page: http://github.com/mitsuhiko/markupsafe
-Author: Armin Ronacher
-Author-email: armin.ronacher@active-4.com
-License: BSD
-Description: MarkupSafe
- ==========
-
- Implements a unicode subclass that supports HTML strings:
-
- >>> from markupsafe import Markup, escape
- >>> escape("")
- Markup(u'<script>alert(document.cookie);</script>')
- >>> tmpl = Markup("%s")
- >>> tmpl % "Peter > Lustig"
- Markup(u'Peter > Lustig')
-
- If you want to make an object unicode that is not yet unicode
- but don't want to lose the taint information, you can use the
- `soft_unicode` function. (On Python 3 you can also use `soft_str` which
- is a different name for the same function).
-
- >>> from markupsafe import soft_unicode
- >>> soft_unicode(42)
- u'42'
- >>> soft_unicode(Markup('foo'))
- Markup(u'foo')
-
- HTML Representations
- --------------------
-
- Objects can customize their HTML markup equivalent by overriding
- the `__html__` function:
-
- >>> class Foo(object):
- ... def __html__(self):
- ... return 'Nice'
- ...
- >>> escape(Foo())
- Markup(u'Nice')
- >>> Markup(Foo())
- Markup(u'Nice')
-
- Silent Escapes
- --------------
-
- Since MarkupSafe 0.10 there is now also a separate escape function
- called `escape_silent` that returns an empty string for `None` for
- consistency with other systems that return empty strings for `None`
- when escaping (for instance Pylons' webhelpers).
-
- If you also want to use this for the escape method of the Markup
- object, you can create your own subclass that does that::
-
- from markupsafe import Markup, escape_silent as escape
-
- class SilentMarkup(Markup):
- __slots__ = ()
-
- @classmethod
- def escape(cls, s):
- return cls(escape(s))
-
- New-Style String Formatting
- ---------------------------
-
- Starting with MarkupSafe 0.21 new style string formats from Python 2.6 and
- 3.x are now fully supported. Previously the escape behavior of those
- functions was spotty at best. The new implementations operates under the
- following algorithm:
-
- 1. if an object has an ``__html_format__`` method it is called as
- replacement for ``__format__`` with the format specifier. It either
- has to return a string or markup object.
- 2. if an object has an ``__html__`` method it is called.
- 3. otherwise the default format system of Python kicks in and the result
- is HTML escaped.
-
- Here is how you can implement your own formatting::
-
- class User(object):
-
- def __init__(self, id, username):
- self.id = id
- self.username = username
-
- def __html_format__(self, format_spec):
- if format_spec == 'link':
- return Markup('{1}').format(
- self.id,
- self.__html__(),
- )
- elif format_spec:
- raise ValueError('Invalid format spec')
- return self.__html__()
-
- def __html__(self):
- return Markup('{0}').format(self.username)
-
- And to format that user:
-
- >>> user = User(1, 'foo')
- >>> Markup('User: {0:link}').format(user)
- Markup(u'
User: foo')
-
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Environment :: Web Environment
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 3
-Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
-Classifier: Topic :: Software Development :: Libraries :: Python Modules
-Classifier: Topic :: Text Processing :: Markup :: HTML
diff --git a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/SOURCES.txt
deleted file mode 100644
index dfeb82b..0000000
--- a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-AUTHORS
-LICENSE
-MANIFEST.in
-README.rst
-setup.cfg
-setup.py
-MarkupSafe.egg-info/PKG-INFO
-MarkupSafe.egg-info/SOURCES.txt
-MarkupSafe.egg-info/dependency_links.txt
-MarkupSafe.egg-info/not-zip-safe
-MarkupSafe.egg-info/top_level.txt
-markupsafe/__init__.py
-markupsafe/_compat.py
-markupsafe/_constants.py
-markupsafe/_native.py
-markupsafe/_speedups.c
-markupsafe/tests.py
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/installed-files.txt
deleted file mode 100644
index bff605a..0000000
--- a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/installed-files.txt
+++ /dev/null
@@ -1,18 +0,0 @@
-../markupsafe/__init__.py
-../markupsafe/_compat.py
-../markupsafe/_constants.py
-../markupsafe/_native.py
-../markupsafe/tests.py
-../markupsafe/_speedups.c
-../markupsafe/__init__.pyc
-../markupsafe/_compat.pyc
-../markupsafe/_constants.pyc
-../markupsafe/_native.pyc
-../markupsafe/tests.pyc
-../markupsafe/_speedups.so
-./
-dependency_links.txt
-not-zip-safe
-PKG-INFO
-SOURCES.txt
-top_level.txt
diff --git a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/top_level.txt
deleted file mode 100644
index 75bf729..0000000
--- a/Darwin/lib/python2.7/site-packages/MarkupSafe-0.23-py2.7.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-markupsafe
diff --git a/Darwin/lib/python2.7/site-packages/PIL/_imaging.so b/Darwin/lib/python2.7/site-packages/PIL/_imaging.so
index 13524f3..9898958 100755
Binary files a/Darwin/lib/python2.7/site-packages/PIL/_imaging.so and b/Darwin/lib/python2.7/site-packages/PIL/_imaging.so differ
diff --git a/Darwin/lib/python2.7/site-packages/PIL/_imagingft.so b/Darwin/lib/python2.7/site-packages/PIL/_imagingft.so
index d3c3581..a760e90 100755
Binary files a/Darwin/lib/python2.7/site-packages/PIL/_imagingft.so and b/Darwin/lib/python2.7/site-packages/PIL/_imagingft.so differ
diff --git a/Darwin/lib/python2.7/site-packages/PIL/_imagingmath.so b/Darwin/lib/python2.7/site-packages/PIL/_imagingmath.so
index af95808..132d2b6 100755
Binary files a/Darwin/lib/python2.7/site-packages/PIL/_imagingmath.so and b/Darwin/lib/python2.7/site-packages/PIL/_imagingmath.so differ
diff --git a/Darwin/lib/python2.7/site-packages/PIL/_imagingtk.so b/Darwin/lib/python2.7/site-packages/PIL/_imagingtk.so
index 5674345..c966a68 100755
Binary files a/Darwin/lib/python2.7/site-packages/PIL/_imagingtk.so and b/Darwin/lib/python2.7/site-packages/PIL/_imagingtk.so differ
diff --git a/Darwin/lib/python2.7/site-packages/README b/Darwin/lib/python2.7/site-packages/README
deleted file mode 100644
index 273f625..0000000
--- a/Darwin/lib/python2.7/site-packages/README
+++ /dev/null
@@ -1,2 +0,0 @@
-This directory exists so that 3rd party packages can be installed
-here. Read the source for site.py for more details.
diff --git a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/PKG-INFO b/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/PKG-INFO
deleted file mode 100644
index 9414e47..0000000
--- a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/PKG-INFO
+++ /dev/null
@@ -1,16 +0,0 @@
-Metadata-Version: 1.1
-Name: Twisted
-Version: 14.0.0
-Summary: An asynchronous networking framework written in Python
-Home-page: http://twistedmatrix.com/
-Author: Glyph Lefkowitz
-Author-email: glyph@twistedmatrix.com
-License: MIT
-Description: An extensible framework for Python programming, with special focus
- on event-based network programming and multiprotocol integration.
-
-Platform: UNKNOWN
-Classifier: Programming Language :: Python :: 2.6
-Classifier: Programming Language :: Python :: 2.7
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.3
diff --git a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/SOURCES.txt
deleted file mode 100644
index 073c9d5..0000000
--- a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,846 +0,0 @@
-README
-Twisted.egg-info/PKG-INFO
-Twisted.egg-info/SOURCES.txt
-Twisted.egg-info/dependency_links.txt
-Twisted.egg-info/not-zip-safe
-Twisted.egg-info/requires.txt
-Twisted.egg-info/top_level.txt
-bin/manhole
-bin/pyhtmlizer
-bin/tap2deb
-bin/tap2rpm
-bin/tapconvert
-bin/trial
-bin/twistd
-bin/conch/cftp
-bin/conch/ckeygen
-bin/conch/conch
-bin/conch/tkconch
-bin/lore/lore
-bin/mail/mailmail
-twisted/__init__.py
-twisted/_version.py
-twisted/copyright.py
-twisted/plugin.py
-twisted/application/__init__.py
-twisted/application/app.py
-twisted/application/internet.py
-twisted/application/reactors.py
-twisted/application/service.py
-twisted/application/strports.py
-twisted/application/test/__init__.py
-twisted/application/test/test_internet.py
-twisted/conch/__init__.py
-twisted/conch/_version.py
-twisted/conch/avatar.py
-twisted/conch/checkers.py
-twisted/conch/endpoints.py
-twisted/conch/error.py
-twisted/conch/interfaces.py
-twisted/conch/ls.py
-twisted/conch/manhole.py
-twisted/conch/manhole_ssh.py
-twisted/conch/manhole_tap.py
-twisted/conch/mixin.py
-twisted/conch/recvline.py
-twisted/conch/stdio.py
-twisted/conch/tap.py
-twisted/conch/telnet.py
-twisted/conch/ttymodes.py
-twisted/conch/unix.py
-twisted/conch/client/__init__.py
-twisted/conch/client/agent.py
-twisted/conch/client/connect.py
-twisted/conch/client/default.py
-twisted/conch/client/direct.py
-twisted/conch/client/knownhosts.py
-twisted/conch/client/options.py
-twisted/conch/insults/__init__.py
-twisted/conch/insults/client.py
-twisted/conch/insults/colors.py
-twisted/conch/insults/helper.py
-twisted/conch/insults/insults.py
-twisted/conch/insults/text.py
-twisted/conch/insults/window.py
-twisted/conch/openssh_compat/__init__.py
-twisted/conch/openssh_compat/factory.py
-twisted/conch/openssh_compat/primes.py
-twisted/conch/scripts/__init__.py
-twisted/conch/scripts/cftp.py
-twisted/conch/scripts/ckeygen.py
-twisted/conch/scripts/conch.py
-twisted/conch/scripts/tkconch.py
-twisted/conch/ssh/__init__.py
-twisted/conch/ssh/address.py
-twisted/conch/ssh/agent.py
-twisted/conch/ssh/channel.py
-twisted/conch/ssh/common.py
-twisted/conch/ssh/connection.py
-twisted/conch/ssh/factory.py
-twisted/conch/ssh/filetransfer.py
-twisted/conch/ssh/forwarding.py
-twisted/conch/ssh/keys.py
-twisted/conch/ssh/service.py
-twisted/conch/ssh/session.py
-twisted/conch/ssh/sexpy.py
-twisted/conch/ssh/transport.py
-twisted/conch/ssh/userauth.py
-twisted/conch/test/__init__.py
-twisted/conch/test/keydata.py
-twisted/conch/test/test_address.py
-twisted/conch/test/test_agent.py
-twisted/conch/test/test_cftp.py
-twisted/conch/test/test_channel.py
-twisted/conch/test/test_checkers.py
-twisted/conch/test/test_ckeygen.py
-twisted/conch/test/test_conch.py
-twisted/conch/test/test_connection.py
-twisted/conch/test/test_default.py
-twisted/conch/test/test_endpoints.py
-twisted/conch/test/test_filetransfer.py
-twisted/conch/test/test_helper.py
-twisted/conch/test/test_insults.py
-twisted/conch/test/test_keys.py
-twisted/conch/test/test_knownhosts.py
-twisted/conch/test/test_manhole.py
-twisted/conch/test/test_mixin.py
-twisted/conch/test/test_openssh_compat.py
-twisted/conch/test/test_recvline.py
-twisted/conch/test/test_scripts.py
-twisted/conch/test/test_session.py
-twisted/conch/test/test_ssh.py
-twisted/conch/test/test_tap.py
-twisted/conch/test/test_telnet.py
-twisted/conch/test/test_text.py
-twisted/conch/test/test_transport.py
-twisted/conch/test/test_userauth.py
-twisted/conch/test/test_window.py
-twisted/conch/ui/__init__.py
-twisted/conch/ui/ansi.py
-twisted/conch/ui/tkvt100.py
-twisted/cred/__init__.py
-twisted/cred/_digest.py
-twisted/cred/checkers.py
-twisted/cred/credentials.py
-twisted/cred/error.py
-twisted/cred/pamauth.py
-twisted/cred/portal.py
-twisted/cred/strcred.py
-twisted/enterprise/__init__.py
-twisted/enterprise/adbapi.py
-twisted/internet/__init__.py
-twisted/internet/_baseprocess.py
-twisted/internet/_dumbwin32proc.py
-twisted/internet/_glibbase.py
-twisted/internet/_newtls.py
-twisted/internet/_pollingfile.py
-twisted/internet/_posixserialport.py
-twisted/internet/_posixstdio.py
-twisted/internet/_signals.py
-twisted/internet/_ssl.py
-twisted/internet/_sslverify.py
-twisted/internet/_threadedselect.py
-twisted/internet/_win32serialport.py
-twisted/internet/_win32stdio.py
-twisted/internet/abstract.py
-twisted/internet/address.py
-twisted/internet/base.py
-twisted/internet/cfreactor.py
-twisted/internet/default.py
-twisted/internet/defer.py
-twisted/internet/endpoints.py
-twisted/internet/epollreactor.py
-twisted/internet/error.py
-twisted/internet/fdesc.py
-twisted/internet/gireactor.py
-twisted/internet/glib2reactor.py
-twisted/internet/gtk2reactor.py
-twisted/internet/gtk3reactor.py
-twisted/internet/gtkreactor.py
-twisted/internet/inotify.py
-twisted/internet/interfaces.py
-twisted/internet/kqreactor.py
-twisted/internet/main.py
-twisted/internet/pollreactor.py
-twisted/internet/posixbase.py
-twisted/internet/process.py
-twisted/internet/protocol.py
-twisted/internet/pyuisupport.py
-twisted/internet/qtreactor.py
-twisted/internet/reactor.py
-twisted/internet/selectreactor.py
-twisted/internet/serialport.py
-twisted/internet/ssl.py
-twisted/internet/stdio.py
-twisted/internet/task.py
-twisted/internet/tcp.py
-twisted/internet/threads.py
-twisted/internet/tksupport.py
-twisted/internet/udp.py
-twisted/internet/unix.py
-twisted/internet/utils.py
-twisted/internet/win32eventreactor.py
-twisted/internet/wxreactor.py
-twisted/internet/wxsupport.py
-twisted/internet/iocpreactor/__init__.py
-twisted/internet/iocpreactor/abstract.py
-twisted/internet/iocpreactor/const.py
-twisted/internet/iocpreactor/interfaces.py
-twisted/internet/iocpreactor/reactor.py
-twisted/internet/iocpreactor/setup.py
-twisted/internet/iocpreactor/tcp.py
-twisted/internet/iocpreactor/udp.py
-twisted/internet/iocpreactor/iocpsupport/iocpsupport.c
-twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c
-twisted/internet/test/__init__.py
-twisted/internet/test/_posixifaces.py
-twisted/internet/test/_win32ifaces.py
-twisted/internet/test/connectionmixins.py
-twisted/internet/test/fakeendpoint.py
-twisted/internet/test/modulehelpers.py
-twisted/internet/test/process_gireactornocompat.py
-twisted/internet/test/process_helper.py
-twisted/internet/test/reactormixins.py
-twisted/internet/test/test_abstract.py
-twisted/internet/test/test_address.py
-twisted/internet/test/test_base.py
-twisted/internet/test/test_baseprocess.py
-twisted/internet/test/test_core.py
-twisted/internet/test/test_default.py
-twisted/internet/test/test_endpoints.py
-twisted/internet/test/test_epollreactor.py
-twisted/internet/test/test_fdset.py
-twisted/internet/test/test_filedescriptor.py
-twisted/internet/test/test_gireactor.py
-twisted/internet/test/test_glibbase.py
-twisted/internet/test/test_gtkreactor.py
-twisted/internet/test/test_inlinecb.py
-twisted/internet/test/test_inotify.py
-twisted/internet/test/test_iocp.py
-twisted/internet/test/test_main.py
-twisted/internet/test/test_newtls.py
-twisted/internet/test/test_pollingfile.py
-twisted/internet/test/test_posixbase.py
-twisted/internet/test/test_posixprocess.py
-twisted/internet/test/test_process.py
-twisted/internet/test/test_protocol.py
-twisted/internet/test/test_qtreactor.py
-twisted/internet/test/test_serialport.py
-twisted/internet/test/test_sigchld.py
-twisted/internet/test/test_socket.py
-twisted/internet/test/test_stdio.py
-twisted/internet/test/test_tcp.py
-twisted/internet/test/test_threads.py
-twisted/internet/test/test_time.py
-twisted/internet/test/test_tls.py
-twisted/internet/test/test_udp.py
-twisted/internet/test/test_udp_internals.py
-twisted/internet/test/test_unix.py
-twisted/internet/test/test_win32events.py
-twisted/lore/__init__.py
-twisted/lore/_version.py
-twisted/lore/default.py
-twisted/lore/docbook.py
-twisted/lore/htmlbook.py
-twisted/lore/indexer.py
-twisted/lore/latex.py
-twisted/lore/lint.py
-twisted/lore/lmath.py
-twisted/lore/man2lore.py
-twisted/lore/numberer.py
-twisted/lore/process.py
-twisted/lore/slides.py
-twisted/lore/texi.py
-twisted/lore/tree.py
-twisted/lore/scripts/__init__.py
-twisted/lore/scripts/lore.py
-twisted/lore/test/__init__.py
-twisted/lore/test/test_docbook.py
-twisted/lore/test/test_latex.py
-twisted/lore/test/test_lint.py
-twisted/lore/test/test_lmath.py
-twisted/lore/test/test_lore.py
-twisted/lore/test/test_man2lore.py
-twisted/lore/test/test_scripts.py
-twisted/lore/test/test_slides.py
-twisted/lore/test/test_texi.py
-twisted/mail/__init__.py
-twisted/mail/_version.py
-twisted/mail/alias.py
-twisted/mail/bounce.py
-twisted/mail/imap4.py
-twisted/mail/mail.py
-twisted/mail/maildir.py
-twisted/mail/pb.py
-twisted/mail/pop3.py
-twisted/mail/pop3client.py
-twisted/mail/protocols.py
-twisted/mail/relay.py
-twisted/mail/relaymanager.py
-twisted/mail/smtp.py
-twisted/mail/tap.py
-twisted/mail/scripts/__init__.py
-twisted/mail/scripts/mailmail.py
-twisted/mail/test/__init__.py
-twisted/mail/test/pop3testserver.py
-twisted/mail/test/test_bounce.py
-twisted/mail/test/test_imap.py
-twisted/mail/test/test_mail.py
-twisted/mail/test/test_mailmail.py
-twisted/mail/test/test_options.py
-twisted/mail/test/test_pop3.py
-twisted/mail/test/test_pop3client.py
-twisted/mail/test/test_scripts.py
-twisted/mail/test/test_smtp.py
-twisted/manhole/__init__.py
-twisted/manhole/_inspectro.py
-twisted/manhole/explorer.py
-twisted/manhole/gladereactor.py
-twisted/manhole/service.py
-twisted/manhole/telnet.py
-twisted/manhole/test/__init__.py
-twisted/manhole/test/test_explorer.py
-twisted/manhole/ui/__init__.py
-twisted/manhole/ui/gtk2manhole.py
-twisted/manhole/ui/test/__init__.py
-twisted/manhole/ui/test/test_gtk2manhole.py
-twisted/names/__init__.py
-twisted/names/_rfc1982.py
-twisted/names/_version.py
-twisted/names/authority.py
-twisted/names/cache.py
-twisted/names/client.py
-twisted/names/common.py
-twisted/names/dns.py
-twisted/names/error.py
-twisted/names/hosts.py
-twisted/names/resolve.py
-twisted/names/root.py
-twisted/names/secondary.py
-twisted/names/server.py
-twisted/names/srvconnect.py
-twisted/names/tap.py
-twisted/names/test/__init__.py
-twisted/names/test/test_cache.py
-twisted/names/test/test_client.py
-twisted/names/test/test_common.py
-twisted/names/test/test_dns.py
-twisted/names/test/test_examples.py
-twisted/names/test/test_hosts.py
-twisted/names/test/test_names.py
-twisted/names/test/test_resolve.py
-twisted/names/test/test_rfc1982.py
-twisted/names/test/test_rootresolve.py
-twisted/names/test/test_server.py
-twisted/names/test/test_srvconnect.py
-twisted/names/test/test_tap.py
-twisted/news/__init__.py
-twisted/news/_version.py
-twisted/news/database.py
-twisted/news/news.py
-twisted/news/nntp.py
-twisted/news/tap.py
-twisted/news/test/__init__.py
-twisted/news/test/test_database.py
-twisted/news/test/test_news.py
-twisted/news/test/test_nntp.py
-twisted/pair/__init__.py
-twisted/pair/_version.py
-twisted/pair/ethernet.py
-twisted/pair/ip.py
-twisted/pair/raw.py
-twisted/pair/rawudp.py
-twisted/pair/testing.py
-twisted/pair/tuntap.py
-twisted/pair/test/__init__.py
-twisted/pair/test/test_ethernet.py
-twisted/pair/test/test_ip.py
-twisted/pair/test/test_rawudp.py
-twisted/pair/test/test_tuntap.py
-twisted/persisted/__init__.py
-twisted/persisted/aot.py
-twisted/persisted/crefutil.py
-twisted/persisted/dirdbm.py
-twisted/persisted/sob.py
-twisted/persisted/styles.py
-twisted/persisted/test/__init__.py
-twisted/persisted/test/test_styles.py
-twisted/plugins/__init__.py
-twisted/plugins/cred_anonymous.py
-twisted/plugins/cred_file.py
-twisted/plugins/cred_memory.py
-twisted/plugins/cred_sshkeys.py
-twisted/plugins/cred_unix.py
-twisted/plugins/twisted_conch.py
-twisted/plugins/twisted_core.py
-twisted/plugins/twisted_ftp.py
-twisted/plugins/twisted_inet.py
-twisted/plugins/twisted_lore.py
-twisted/plugins/twisted_mail.py
-twisted/plugins/twisted_manhole.py
-twisted/plugins/twisted_names.py
-twisted/plugins/twisted_news.py
-twisted/plugins/twisted_portforward.py
-twisted/plugins/twisted_qtstub.py
-twisted/plugins/twisted_reactors.py
-twisted/plugins/twisted_runner.py
-twisted/plugins/twisted_socks.py
-twisted/plugins/twisted_telnet.py
-twisted/plugins/twisted_trial.py
-twisted/plugins/twisted_web.py
-twisted/plugins/twisted_words.py
-twisted/positioning/__init__.py
-twisted/positioning/_sentence.py
-twisted/positioning/base.py
-twisted/positioning/ipositioning.py
-twisted/positioning/nmea.py
-twisted/positioning/test/__init__.py
-twisted/positioning/test/receiver.py
-twisted/positioning/test/test_base.py
-twisted/positioning/test/test_nmea.py
-twisted/positioning/test/test_sentence.py
-twisted/protocols/__init__.py
-twisted/protocols/amp.py
-twisted/protocols/basic.py
-twisted/protocols/dict.py
-twisted/protocols/finger.py
-twisted/protocols/ftp.py
-twisted/protocols/htb.py
-twisted/protocols/ident.py
-twisted/protocols/loopback.py
-twisted/protocols/memcache.py
-twisted/protocols/pcp.py
-twisted/protocols/policies.py
-twisted/protocols/portforward.py
-twisted/protocols/postfix.py
-twisted/protocols/shoutcast.py
-twisted/protocols/sip.py
-twisted/protocols/socks.py
-twisted/protocols/stateful.py
-twisted/protocols/telnet.py
-twisted/protocols/tls.py
-twisted/protocols/wire.py
-twisted/protocols/gps/__init__.py
-twisted/protocols/gps/nmea.py
-twisted/protocols/gps/rockwell.py
-twisted/protocols/mice/__init__.py
-twisted/protocols/mice/mouseman.py
-twisted/protocols/test/__init__.py
-twisted/protocols/test/test_basic.py
-twisted/protocols/test/test_tls.py
-twisted/python/__init__.py
-twisted/python/_inotify.py
-twisted/python/_release.py
-twisted/python/_shellcomp.py
-twisted/python/_textattributes.py
-twisted/python/compat.py
-twisted/python/components.py
-twisted/python/constants.py
-twisted/python/context.py
-twisted/python/deprecate.py
-twisted/python/dist.py
-twisted/python/dist3.py
-twisted/python/failure.py
-twisted/python/fakepwd.py
-twisted/python/filepath.py
-twisted/python/finalize.py
-twisted/python/formmethod.py
-twisted/python/hashlib.py
-twisted/python/hook.py
-twisted/python/htmlizer.py
-twisted/python/lockfile.py
-twisted/python/log.py
-twisted/python/logfile.py
-twisted/python/modules.py
-twisted/python/monkey.py
-twisted/python/procutils.py
-twisted/python/randbytes.py
-twisted/python/rebuild.py
-twisted/python/reflect.py
-twisted/python/release.py
-twisted/python/roots.py
-twisted/python/runtime.py
-twisted/python/sendmsg.c
-twisted/python/shortcut.py
-twisted/python/syslog.py
-twisted/python/systemd.py
-twisted/python/text.py
-twisted/python/threadable.py
-twisted/python/threadpool.py
-twisted/python/urlpath.py
-twisted/python/usage.py
-twisted/python/util.py
-twisted/python/versions.py
-twisted/python/win32.py
-twisted/python/zippath.py
-twisted/python/zipstream.py
-twisted/python/test/__init__.py
-twisted/python/test/deprecatedattributes.py
-twisted/python/test/modules_helpers.py
-twisted/python/test/pullpipe.py
-twisted/python/test/test_components.py
-twisted/python/test/test_constants.py
-twisted/python/test/test_deprecate.py
-twisted/python/test/test_dist.py
-twisted/python/test/test_dist3.py
-twisted/python/test/test_fakepwd.py
-twisted/python/test/test_hashlib.py
-twisted/python/test/test_htmlizer.py
-twisted/python/test/test_inotify.py
-twisted/python/test/test_release.py
-twisted/python/test/test_runtime.py
-twisted/python/test/test_sendmsg.py
-twisted/python/test/test_shellcomp.py
-twisted/python/test/test_syslog.py
-twisted/python/test/test_systemd.py
-twisted/python/test/test_textattributes.py
-twisted/python/test/test_urlpath.py
-twisted/python/test/test_util.py
-twisted/python/test/test_versions.py
-twisted/python/test/test_win32.py
-twisted/python/test/test_zippath.py
-twisted/python/test/test_zipstream.py
-twisted/runner/__init__.py
-twisted/runner/_version.py
-twisted/runner/inetd.py
-twisted/runner/inetdconf.py
-twisted/runner/inetdtap.py
-twisted/runner/portmap.c
-twisted/runner/procmon.py
-twisted/runner/procmontap.py
-twisted/runner/test/__init__.py
-twisted/runner/test/test_procmon.py
-twisted/runner/test/test_procmontap.py
-twisted/scripts/__init__.py
-twisted/scripts/_twistd_unix.py
-twisted/scripts/_twistw.py
-twisted/scripts/htmlizer.py
-twisted/scripts/manhole.py
-twisted/scripts/tap2deb.py
-twisted/scripts/tap2rpm.py
-twisted/scripts/tapconvert.py
-twisted/scripts/tkunzip.py
-twisted/scripts/trial.py
-twisted/scripts/twistd.py
-twisted/scripts/test/__init__.py
-twisted/scripts/test/test_scripts.py
-twisted/scripts/test/test_tap2deb.py
-twisted/scripts/test/test_tap2rpm.py
-twisted/spread/__init__.py
-twisted/spread/banana.py
-twisted/spread/flavors.py
-twisted/spread/interfaces.py
-twisted/spread/jelly.py
-twisted/spread/pb.py
-twisted/spread/publish.py
-twisted/spread/util.py
-twisted/spread/ui/__init__.py
-twisted/spread/ui/gtk2util.py
-twisted/spread/ui/tktree.py
-twisted/spread/ui/tkutil.py
-twisted/tap/__init__.py
-twisted/tap/ftp.py
-twisted/tap/manhole.py
-twisted/tap/portforward.py
-twisted/tap/socks.py
-twisted/tap/telnet.py
-twisted/test/__init__.py
-twisted/test/_preamble.py
-twisted/test/crash_test_dummy.py
-twisted/test/iosim.py
-twisted/test/mock_win32process.py
-twisted/test/myrebuilder1.py
-twisted/test/myrebuilder2.py
-twisted/test/plugin_basic.py
-twisted/test/plugin_extra1.py
-twisted/test/plugin_extra2.py
-twisted/test/process_cmdline.py
-twisted/test/process_echoer.py
-twisted/test/process_fds.py
-twisted/test/process_linger.py
-twisted/test/process_reader.py
-twisted/test/process_signal.py
-twisted/test/process_stdinreader.py
-twisted/test/process_tester.py
-twisted/test/process_tty.py
-twisted/test/process_twisted.py
-twisted/test/proto_helpers.py
-twisted/test/raiser.c
-twisted/test/reflect_helper_IE.py
-twisted/test/reflect_helper_VE.py
-twisted/test/reflect_helper_ZDE.py
-twisted/test/ssl_helpers.py
-twisted/test/stdio_test_consumer.py
-twisted/test/stdio_test_halfclose.py
-twisted/test/stdio_test_hostpeer.py
-twisted/test/stdio_test_lastwrite.py
-twisted/test/stdio_test_loseconn.py
-twisted/test/stdio_test_producer.py
-twisted/test/stdio_test_write.py
-twisted/test/stdio_test_writeseq.py
-twisted/test/test_abstract.py
-twisted/test/test_adbapi.py
-twisted/test/test_amp.py
-twisted/test/test_application.py
-twisted/test/test_banana.py
-twisted/test/test_compat.py
-twisted/test/test_context.py
-twisted/test/test_cooperator.py
-twisted/test/test_defer.py
-twisted/test/test_defgen.py
-twisted/test/test_dict.py
-twisted/test/test_digestauth.py
-twisted/test/test_dirdbm.py
-twisted/test/test_doc.py
-twisted/test/test_error.py
-twisted/test/test_explorer.py
-twisted/test/test_factories.py
-twisted/test/test_failure.py
-twisted/test/test_fdesc.py
-twisted/test/test_finger.py
-twisted/test/test_formmethod.py
-twisted/test/test_ftp.py
-twisted/test/test_ftp_options.py
-twisted/test/test_hook.py
-twisted/test/test_htb.py
-twisted/test/test_ident.py
-twisted/test/test_internet.py
-twisted/test/test_iosim.py
-twisted/test/test_iutils.py
-twisted/test/test_jelly.py
-twisted/test/test_lockfile.py
-twisted/test/test_log.py
-twisted/test/test_logfile.py
-twisted/test/test_loopback.py
-twisted/test/test_manhole.py
-twisted/test/test_memcache.py
-twisted/test/test_modules.py
-twisted/test/test_monkey.py
-twisted/test/test_newcred.py
-twisted/test/test_nmea.py
-twisted/test/test_paths.py
-twisted/test/test_pb.py
-twisted/test/test_pbfailure.py
-twisted/test/test_pcp.py
-twisted/test/test_persisted.py
-twisted/test/test_plugin.py
-twisted/test/test_policies.py
-twisted/test/test_postfix.py
-twisted/test/test_process.py
-twisted/test/test_protocols.py
-twisted/test/test_randbytes.py
-twisted/test/test_rebuild.py
-twisted/test/test_reflect.py
-twisted/test/test_roots.py
-twisted/test/test_setup.py
-twisted/test/test_shortcut.py
-twisted/test/test_sip.py
-twisted/test/test_sob.py
-twisted/test/test_socks.py
-twisted/test/test_ssl.py
-twisted/test/test_sslverify.py
-twisted/test/test_stateful.py
-twisted/test/test_stdio.py
-twisted/test/test_strcred.py
-twisted/test/test_strerror.py
-twisted/test/test_stringtransport.py
-twisted/test/test_strports.py
-twisted/test/test_task.py
-twisted/test/test_tcp.py
-twisted/test/test_tcp_internals.py
-twisted/test/test_text.py
-twisted/test/test_threadable.py
-twisted/test/test_threadpool.py
-twisted/test/test_threads.py
-twisted/test/test_tpfile.py
-twisted/test/test_twistd.py
-twisted/test/test_twisted.py
-twisted/test/test_udp.py
-twisted/test/test_unix.py
-twisted/test/test_usage.py
-twisted/test/testutils.py
-twisted/trial/__init__.py
-twisted/trial/_asyncrunner.py
-twisted/trial/_asynctest.py
-twisted/trial/_synctest.py
-twisted/trial/itrial.py
-twisted/trial/reporter.py
-twisted/trial/runner.py
-twisted/trial/unittest.py
-twisted/trial/util.py
-twisted/trial/_dist/__init__.py
-twisted/trial/_dist/distreporter.py
-twisted/trial/_dist/disttrial.py
-twisted/trial/_dist/managercommands.py
-twisted/trial/_dist/options.py
-twisted/trial/_dist/worker.py
-twisted/trial/_dist/workercommands.py
-twisted/trial/_dist/workerreporter.py
-twisted/trial/_dist/workertrial.py
-twisted/trial/_dist/test/__init__.py
-twisted/trial/_dist/test/test_distreporter.py
-twisted/trial/_dist/test/test_disttrial.py
-twisted/trial/_dist/test/test_options.py
-twisted/trial/_dist/test/test_worker.py
-twisted/trial/_dist/test/test_workerreporter.py
-twisted/trial/_dist/test/test_workertrial.py
-twisted/trial/test/__init__.py
-twisted/trial/test/detests.py
-twisted/trial/test/erroneous.py
-twisted/trial/test/mockcustomsuite.py
-twisted/trial/test/mockcustomsuite2.py
-twisted/trial/test/mockcustomsuite3.py
-twisted/trial/test/mockdoctest.py
-twisted/trial/test/moduleself.py
-twisted/trial/test/moduletest.py
-twisted/trial/test/novars.py
-twisted/trial/test/ordertests.py
-twisted/trial/test/packages.py
-twisted/trial/test/sample.py
-twisted/trial/test/scripttest.py
-twisted/trial/test/skipping.py
-twisted/trial/test/suppression.py
-twisted/trial/test/test_assertions.py
-twisted/trial/test/test_asyncassertions.py
-twisted/trial/test/test_deferred.py
-twisted/trial/test/test_doctest.py
-twisted/trial/test/test_keyboard.py
-twisted/trial/test/test_loader.py
-twisted/trial/test/test_log.py
-twisted/trial/test/test_output.py
-twisted/trial/test/test_plugins.py
-twisted/trial/test/test_pyunitcompat.py
-twisted/trial/test/test_reporter.py
-twisted/trial/test/test_runner.py
-twisted/trial/test/test_script.py
-twisted/trial/test/test_suppression.py
-twisted/trial/test/test_testcase.py
-twisted/trial/test/test_tests.py
-twisted/trial/test/test_util.py
-twisted/trial/test/test_warning.py
-twisted/trial/test/weird.py
-twisted/web/__init__.py
-twisted/web/_element.py
-twisted/web/_flatten.py
-twisted/web/_newclient.py
-twisted/web/_responses.py
-twisted/web/_stan.py
-twisted/web/_version.py
-twisted/web/client.py
-twisted/web/demo.py
-twisted/web/distrib.py
-twisted/web/domhelpers.py
-twisted/web/error.py
-twisted/web/guard.py
-twisted/web/html.py
-twisted/web/http.py
-twisted/web/http_headers.py
-twisted/web/iweb.py
-twisted/web/microdom.py
-twisted/web/proxy.py
-twisted/web/resource.py
-twisted/web/rewrite.py
-twisted/web/script.py
-twisted/web/server.py
-twisted/web/soap.py
-twisted/web/static.py
-twisted/web/sux.py
-twisted/web/tap.py
-twisted/web/template.py
-twisted/web/twcgi.py
-twisted/web/util.py
-twisted/web/vhost.py
-twisted/web/wsgi.py
-twisted/web/xmlrpc.py
-twisted/web/_auth/__init__.py
-twisted/web/_auth/basic.py
-twisted/web/_auth/digest.py
-twisted/web/_auth/wrapper.py
-twisted/web/test/__init__.py
-twisted/web/test/_util.py
-twisted/web/test/requesthelper.py
-twisted/web/test/test_agent.py
-twisted/web/test/test_cgi.py
-twisted/web/test/test_distrib.py
-twisted/web/test/test_domhelpers.py
-twisted/web/test/test_error.py
-twisted/web/test/test_flatten.py
-twisted/web/test/test_http.py
-twisted/web/test/test_http_headers.py
-twisted/web/test/test_httpauth.py
-twisted/web/test/test_newclient.py
-twisted/web/test/test_proxy.py
-twisted/web/test/test_resource.py
-twisted/web/test/test_script.py
-twisted/web/test/test_soap.py
-twisted/web/test/test_stan.py
-twisted/web/test/test_static.py
-twisted/web/test/test_tap.py
-twisted/web/test/test_template.py
-twisted/web/test/test_util.py
-twisted/web/test/test_vhost.py
-twisted/web/test/test_web.py
-twisted/web/test/test_webclient.py
-twisted/web/test/test_wsgi.py
-twisted/web/test/test_xml.py
-twisted/web/test/test_xmlrpc.py
-twisted/words/__init__.py
-twisted/words/_version.py
-twisted/words/ewords.py
-twisted/words/iwords.py
-twisted/words/service.py
-twisted/words/tap.py
-twisted/words/xmpproutertap.py
-twisted/words/im/__init__.py
-twisted/words/im/baseaccount.py
-twisted/words/im/basechat.py
-twisted/words/im/basesupport.py
-twisted/words/im/interfaces.py
-twisted/words/im/ircsupport.py
-twisted/words/im/locals.py
-twisted/words/im/pbsupport.py
-twisted/words/protocols/__init__.py
-twisted/words/protocols/irc.py
-twisted/words/protocols/msn.py
-twisted/words/protocols/oscar.py
-twisted/words/protocols/jabber/__init__.py
-twisted/words/protocols/jabber/client.py
-twisted/words/protocols/jabber/component.py
-twisted/words/protocols/jabber/error.py
-twisted/words/protocols/jabber/ijabber.py
-twisted/words/protocols/jabber/jid.py
-twisted/words/protocols/jabber/jstrports.py
-twisted/words/protocols/jabber/sasl.py
-twisted/words/protocols/jabber/sasl_mechanisms.py
-twisted/words/protocols/jabber/xmlstream.py
-twisted/words/protocols/jabber/xmpp_stringprep.py
-twisted/words/test/__init__.py
-twisted/words/test/test_basechat.py
-twisted/words/test/test_basesupport.py
-twisted/words/test/test_domish.py
-twisted/words/test/test_irc.py
-twisted/words/test/test_irc_service.py
-twisted/words/test/test_ircsupport.py
-twisted/words/test/test_jabberclient.py
-twisted/words/test/test_jabbercomponent.py
-twisted/words/test/test_jabbererror.py
-twisted/words/test/test_jabberjid.py
-twisted/words/test/test_jabberjstrports.py
-twisted/words/test/test_jabbersasl.py
-twisted/words/test/test_jabbersaslmechanisms.py
-twisted/words/test/test_jabberxmlstream.py
-twisted/words/test/test_jabberxmppstringprep.py
-twisted/words/test/test_msn.py
-twisted/words/test/test_oscar.py
-twisted/words/test/test_service.py
-twisted/words/test/test_tap.py
-twisted/words/test/test_xishutil.py
-twisted/words/test/test_xmlstream.py
-twisted/words/test/test_xmpproutertap.py
-twisted/words/test/test_xpath.py
-twisted/words/xish/__init__.py
-twisted/words/xish/domish.py
-twisted/words/xish/utility.py
-twisted/words/xish/xmlstream.py
-twisted/words/xish/xpath.py
-twisted/words/xish/xpathparser.py
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/installed-files.txt
deleted file mode 100644
index 01f6971..0000000
--- a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/installed-files.txt
+++ /dev/null
@@ -1,1757 +0,0 @@
-../twisted/__init__.py
-../twisted/_version.py
-../twisted/copyright.py
-../twisted/plugin.py
-../twisted/application/__init__.py
-../twisted/application/app.py
-../twisted/application/internet.py
-../twisted/application/reactors.py
-../twisted/application/service.py
-../twisted/application/strports.py
-../twisted/application/test/__init__.py
-../twisted/application/test/test_internet.py
-../twisted/conch/__init__.py
-../twisted/conch/_version.py
-../twisted/conch/avatar.py
-../twisted/conch/checkers.py
-../twisted/conch/endpoints.py
-../twisted/conch/error.py
-../twisted/conch/interfaces.py
-../twisted/conch/ls.py
-../twisted/conch/manhole.py
-../twisted/conch/manhole_ssh.py
-../twisted/conch/manhole_tap.py
-../twisted/conch/mixin.py
-../twisted/conch/recvline.py
-../twisted/conch/stdio.py
-../twisted/conch/tap.py
-../twisted/conch/telnet.py
-../twisted/conch/ttymodes.py
-../twisted/conch/unix.py
-../twisted/conch/client/__init__.py
-../twisted/conch/client/agent.py
-../twisted/conch/client/connect.py
-../twisted/conch/client/default.py
-../twisted/conch/client/direct.py
-../twisted/conch/client/knownhosts.py
-../twisted/conch/client/options.py
-../twisted/conch/insults/__init__.py
-../twisted/conch/insults/client.py
-../twisted/conch/insults/colors.py
-../twisted/conch/insults/helper.py
-../twisted/conch/insults/insults.py
-../twisted/conch/insults/text.py
-../twisted/conch/insults/window.py
-../twisted/conch/openssh_compat/__init__.py
-../twisted/conch/openssh_compat/factory.py
-../twisted/conch/openssh_compat/primes.py
-../twisted/conch/scripts/__init__.py
-../twisted/conch/scripts/cftp.py
-../twisted/conch/scripts/ckeygen.py
-../twisted/conch/scripts/conch.py
-../twisted/conch/scripts/tkconch.py
-../twisted/conch/ssh/__init__.py
-../twisted/conch/ssh/address.py
-../twisted/conch/ssh/agent.py
-../twisted/conch/ssh/channel.py
-../twisted/conch/ssh/common.py
-../twisted/conch/ssh/connection.py
-../twisted/conch/ssh/factory.py
-../twisted/conch/ssh/filetransfer.py
-../twisted/conch/ssh/forwarding.py
-../twisted/conch/ssh/keys.py
-../twisted/conch/ssh/service.py
-../twisted/conch/ssh/session.py
-../twisted/conch/ssh/sexpy.py
-../twisted/conch/ssh/transport.py
-../twisted/conch/ssh/userauth.py
-../twisted/conch/test/__init__.py
-../twisted/conch/test/keydata.py
-../twisted/conch/test/test_address.py
-../twisted/conch/test/test_agent.py
-../twisted/conch/test/test_cftp.py
-../twisted/conch/test/test_channel.py
-../twisted/conch/test/test_checkers.py
-../twisted/conch/test/test_ckeygen.py
-../twisted/conch/test/test_conch.py
-../twisted/conch/test/test_connection.py
-../twisted/conch/test/test_default.py
-../twisted/conch/test/test_endpoints.py
-../twisted/conch/test/test_filetransfer.py
-../twisted/conch/test/test_helper.py
-../twisted/conch/test/test_insults.py
-../twisted/conch/test/test_keys.py
-../twisted/conch/test/test_knownhosts.py
-../twisted/conch/test/test_manhole.py
-../twisted/conch/test/test_mixin.py
-../twisted/conch/test/test_openssh_compat.py
-../twisted/conch/test/test_recvline.py
-../twisted/conch/test/test_scripts.py
-../twisted/conch/test/test_session.py
-../twisted/conch/test/test_ssh.py
-../twisted/conch/test/test_tap.py
-../twisted/conch/test/test_telnet.py
-../twisted/conch/test/test_text.py
-../twisted/conch/test/test_transport.py
-../twisted/conch/test/test_userauth.py
-../twisted/conch/test/test_window.py
-../twisted/conch/ui/__init__.py
-../twisted/conch/ui/ansi.py
-../twisted/conch/ui/tkvt100.py
-../twisted/cred/__init__.py
-../twisted/cred/_digest.py
-../twisted/cred/checkers.py
-../twisted/cred/credentials.py
-../twisted/cred/error.py
-../twisted/cred/pamauth.py
-../twisted/cred/portal.py
-../twisted/cred/strcred.py
-../twisted/enterprise/__init__.py
-../twisted/enterprise/adbapi.py
-../twisted/internet/__init__.py
-../twisted/internet/_baseprocess.py
-../twisted/internet/_dumbwin32proc.py
-../twisted/internet/_glibbase.py
-../twisted/internet/_newtls.py
-../twisted/internet/_pollingfile.py
-../twisted/internet/_posixserialport.py
-../twisted/internet/_posixstdio.py
-../twisted/internet/_signals.py
-../twisted/internet/_ssl.py
-../twisted/internet/_sslverify.py
-../twisted/internet/_threadedselect.py
-../twisted/internet/_win32serialport.py
-../twisted/internet/_win32stdio.py
-../twisted/internet/abstract.py
-../twisted/internet/address.py
-../twisted/internet/base.py
-../twisted/internet/cfreactor.py
-../twisted/internet/default.py
-../twisted/internet/defer.py
-../twisted/internet/endpoints.py
-../twisted/internet/epollreactor.py
-../twisted/internet/error.py
-../twisted/internet/fdesc.py
-../twisted/internet/gireactor.py
-../twisted/internet/glib2reactor.py
-../twisted/internet/gtk2reactor.py
-../twisted/internet/gtk3reactor.py
-../twisted/internet/gtkreactor.py
-../twisted/internet/inotify.py
-../twisted/internet/interfaces.py
-../twisted/internet/kqreactor.py
-../twisted/internet/main.py
-../twisted/internet/pollreactor.py
-../twisted/internet/posixbase.py
-../twisted/internet/process.py
-../twisted/internet/protocol.py
-../twisted/internet/pyuisupport.py
-../twisted/internet/qtreactor.py
-../twisted/internet/reactor.py
-../twisted/internet/selectreactor.py
-../twisted/internet/serialport.py
-../twisted/internet/ssl.py
-../twisted/internet/stdio.py
-../twisted/internet/task.py
-../twisted/internet/tcp.py
-../twisted/internet/threads.py
-../twisted/internet/tksupport.py
-../twisted/internet/udp.py
-../twisted/internet/unix.py
-../twisted/internet/utils.py
-../twisted/internet/win32eventreactor.py
-../twisted/internet/wxreactor.py
-../twisted/internet/wxsupport.py
-../twisted/internet/iocpreactor/__init__.py
-../twisted/internet/iocpreactor/abstract.py
-../twisted/internet/iocpreactor/const.py
-../twisted/internet/iocpreactor/interfaces.py
-../twisted/internet/iocpreactor/reactor.py
-../twisted/internet/iocpreactor/setup.py
-../twisted/internet/iocpreactor/tcp.py
-../twisted/internet/iocpreactor/udp.py
-../twisted/internet/test/__init__.py
-../twisted/internet/test/_posixifaces.py
-../twisted/internet/test/_win32ifaces.py
-../twisted/internet/test/connectionmixins.py
-../twisted/internet/test/fakeendpoint.py
-../twisted/internet/test/modulehelpers.py
-../twisted/internet/test/process_gireactornocompat.py
-../twisted/internet/test/process_helper.py
-../twisted/internet/test/reactormixins.py
-../twisted/internet/test/test_abstract.py
-../twisted/internet/test/test_address.py
-../twisted/internet/test/test_base.py
-../twisted/internet/test/test_baseprocess.py
-../twisted/internet/test/test_core.py
-../twisted/internet/test/test_default.py
-../twisted/internet/test/test_endpoints.py
-../twisted/internet/test/test_epollreactor.py
-../twisted/internet/test/test_fdset.py
-../twisted/internet/test/test_filedescriptor.py
-../twisted/internet/test/test_gireactor.py
-../twisted/internet/test/test_glibbase.py
-../twisted/internet/test/test_gtkreactor.py
-../twisted/internet/test/test_inlinecb.py
-../twisted/internet/test/test_inotify.py
-../twisted/internet/test/test_iocp.py
-../twisted/internet/test/test_main.py
-../twisted/internet/test/test_newtls.py
-../twisted/internet/test/test_pollingfile.py
-../twisted/internet/test/test_posixbase.py
-../twisted/internet/test/test_posixprocess.py
-../twisted/internet/test/test_process.py
-../twisted/internet/test/test_protocol.py
-../twisted/internet/test/test_qtreactor.py
-../twisted/internet/test/test_serialport.py
-../twisted/internet/test/test_sigchld.py
-../twisted/internet/test/test_socket.py
-../twisted/internet/test/test_stdio.py
-../twisted/internet/test/test_tcp.py
-../twisted/internet/test/test_threads.py
-../twisted/internet/test/test_time.py
-../twisted/internet/test/test_tls.py
-../twisted/internet/test/test_udp.py
-../twisted/internet/test/test_udp_internals.py
-../twisted/internet/test/test_unix.py
-../twisted/internet/test/test_win32events.py
-../twisted/lore/__init__.py
-../twisted/lore/_version.py
-../twisted/lore/default.py
-../twisted/lore/docbook.py
-../twisted/lore/htmlbook.py
-../twisted/lore/indexer.py
-../twisted/lore/latex.py
-../twisted/lore/lint.py
-../twisted/lore/lmath.py
-../twisted/lore/man2lore.py
-../twisted/lore/numberer.py
-../twisted/lore/process.py
-../twisted/lore/slides.py
-../twisted/lore/texi.py
-../twisted/lore/tree.py
-../twisted/lore/scripts/__init__.py
-../twisted/lore/scripts/lore.py
-../twisted/lore/test/__init__.py
-../twisted/lore/test/test_docbook.py
-../twisted/lore/test/test_latex.py
-../twisted/lore/test/test_lint.py
-../twisted/lore/test/test_lmath.py
-../twisted/lore/test/test_lore.py
-../twisted/lore/test/test_man2lore.py
-../twisted/lore/test/test_scripts.py
-../twisted/lore/test/test_slides.py
-../twisted/lore/test/test_texi.py
-../twisted/mail/__init__.py
-../twisted/mail/_version.py
-../twisted/mail/alias.py
-../twisted/mail/bounce.py
-../twisted/mail/imap4.py
-../twisted/mail/mail.py
-../twisted/mail/maildir.py
-../twisted/mail/pb.py
-../twisted/mail/pop3.py
-../twisted/mail/pop3client.py
-../twisted/mail/protocols.py
-../twisted/mail/relay.py
-../twisted/mail/relaymanager.py
-../twisted/mail/smtp.py
-../twisted/mail/tap.py
-../twisted/mail/scripts/__init__.py
-../twisted/mail/scripts/mailmail.py
-../twisted/mail/test/__init__.py
-../twisted/mail/test/pop3testserver.py
-../twisted/mail/test/test_bounce.py
-../twisted/mail/test/test_imap.py
-../twisted/mail/test/test_mail.py
-../twisted/mail/test/test_mailmail.py
-../twisted/mail/test/test_options.py
-../twisted/mail/test/test_pop3.py
-../twisted/mail/test/test_pop3client.py
-../twisted/mail/test/test_scripts.py
-../twisted/mail/test/test_smtp.py
-../twisted/manhole/__init__.py
-../twisted/manhole/_inspectro.py
-../twisted/manhole/explorer.py
-../twisted/manhole/gladereactor.py
-../twisted/manhole/service.py
-../twisted/manhole/telnet.py
-../twisted/manhole/test/__init__.py
-../twisted/manhole/test/test_explorer.py
-../twisted/manhole/ui/__init__.py
-../twisted/manhole/ui/gtk2manhole.py
-../twisted/manhole/ui/test/__init__.py
-../twisted/manhole/ui/test/test_gtk2manhole.py
-../twisted/names/__init__.py
-../twisted/names/_rfc1982.py
-../twisted/names/_version.py
-../twisted/names/authority.py
-../twisted/names/cache.py
-../twisted/names/client.py
-../twisted/names/common.py
-../twisted/names/dns.py
-../twisted/names/error.py
-../twisted/names/hosts.py
-../twisted/names/resolve.py
-../twisted/names/root.py
-../twisted/names/secondary.py
-../twisted/names/server.py
-../twisted/names/srvconnect.py
-../twisted/names/tap.py
-../twisted/names/test/__init__.py
-../twisted/names/test/test_cache.py
-../twisted/names/test/test_client.py
-../twisted/names/test/test_common.py
-../twisted/names/test/test_dns.py
-../twisted/names/test/test_examples.py
-../twisted/names/test/test_hosts.py
-../twisted/names/test/test_names.py
-../twisted/names/test/test_resolve.py
-../twisted/names/test/test_rfc1982.py
-../twisted/names/test/test_rootresolve.py
-../twisted/names/test/test_server.py
-../twisted/names/test/test_srvconnect.py
-../twisted/names/test/test_tap.py
-../twisted/news/__init__.py
-../twisted/news/_version.py
-../twisted/news/database.py
-../twisted/news/news.py
-../twisted/news/nntp.py
-../twisted/news/tap.py
-../twisted/news/test/__init__.py
-../twisted/news/test/test_database.py
-../twisted/news/test/test_news.py
-../twisted/news/test/test_nntp.py
-../twisted/pair/__init__.py
-../twisted/pair/_version.py
-../twisted/pair/ethernet.py
-../twisted/pair/ip.py
-../twisted/pair/raw.py
-../twisted/pair/rawudp.py
-../twisted/pair/testing.py
-../twisted/pair/tuntap.py
-../twisted/pair/test/__init__.py
-../twisted/pair/test/test_ethernet.py
-../twisted/pair/test/test_ip.py
-../twisted/pair/test/test_rawudp.py
-../twisted/pair/test/test_tuntap.py
-../twisted/persisted/__init__.py
-../twisted/persisted/aot.py
-../twisted/persisted/crefutil.py
-../twisted/persisted/dirdbm.py
-../twisted/persisted/sob.py
-../twisted/persisted/styles.py
-../twisted/persisted/test/__init__.py
-../twisted/persisted/test/test_styles.py
-../twisted/plugins/__init__.py
-../twisted/plugins/cred_anonymous.py
-../twisted/plugins/cred_file.py
-../twisted/plugins/cred_memory.py
-../twisted/plugins/cred_sshkeys.py
-../twisted/plugins/cred_unix.py
-../twisted/plugins/twisted_conch.py
-../twisted/plugins/twisted_core.py
-../twisted/plugins/twisted_ftp.py
-../twisted/plugins/twisted_inet.py
-../twisted/plugins/twisted_lore.py
-../twisted/plugins/twisted_mail.py
-../twisted/plugins/twisted_manhole.py
-../twisted/plugins/twisted_names.py
-../twisted/plugins/twisted_news.py
-../twisted/plugins/twisted_portforward.py
-../twisted/plugins/twisted_qtstub.py
-../twisted/plugins/twisted_reactors.py
-../twisted/plugins/twisted_runner.py
-../twisted/plugins/twisted_socks.py
-../twisted/plugins/twisted_telnet.py
-../twisted/plugins/twisted_trial.py
-../twisted/plugins/twisted_web.py
-../twisted/plugins/twisted_words.py
-../twisted/positioning/__init__.py
-../twisted/positioning/_sentence.py
-../twisted/positioning/base.py
-../twisted/positioning/ipositioning.py
-../twisted/positioning/nmea.py
-../twisted/positioning/test/__init__.py
-../twisted/positioning/test/receiver.py
-../twisted/positioning/test/test_base.py
-../twisted/positioning/test/test_nmea.py
-../twisted/positioning/test/test_sentence.py
-../twisted/protocols/__init__.py
-../twisted/protocols/amp.py
-../twisted/protocols/basic.py
-../twisted/protocols/dict.py
-../twisted/protocols/finger.py
-../twisted/protocols/ftp.py
-../twisted/protocols/htb.py
-../twisted/protocols/ident.py
-../twisted/protocols/loopback.py
-../twisted/protocols/memcache.py
-../twisted/protocols/pcp.py
-../twisted/protocols/policies.py
-../twisted/protocols/portforward.py
-../twisted/protocols/postfix.py
-../twisted/protocols/shoutcast.py
-../twisted/protocols/sip.py
-../twisted/protocols/socks.py
-../twisted/protocols/stateful.py
-../twisted/protocols/telnet.py
-../twisted/protocols/tls.py
-../twisted/protocols/wire.py
-../twisted/protocols/gps/__init__.py
-../twisted/protocols/gps/nmea.py
-../twisted/protocols/gps/rockwell.py
-../twisted/protocols/mice/__init__.py
-../twisted/protocols/mice/mouseman.py
-../twisted/protocols/test/__init__.py
-../twisted/protocols/test/test_basic.py
-../twisted/protocols/test/test_tls.py
-../twisted/python/__init__.py
-../twisted/python/_inotify.py
-../twisted/python/_release.py
-../twisted/python/_shellcomp.py
-../twisted/python/_textattributes.py
-../twisted/python/compat.py
-../twisted/python/components.py
-../twisted/python/constants.py
-../twisted/python/context.py
-../twisted/python/deprecate.py
-../twisted/python/dist.py
-../twisted/python/dist3.py
-../twisted/python/failure.py
-../twisted/python/fakepwd.py
-../twisted/python/filepath.py
-../twisted/python/finalize.py
-../twisted/python/formmethod.py
-../twisted/python/hashlib.py
-../twisted/python/hook.py
-../twisted/python/htmlizer.py
-../twisted/python/lockfile.py
-../twisted/python/log.py
-../twisted/python/logfile.py
-../twisted/python/modules.py
-../twisted/python/monkey.py
-../twisted/python/procutils.py
-../twisted/python/randbytes.py
-../twisted/python/rebuild.py
-../twisted/python/reflect.py
-../twisted/python/release.py
-../twisted/python/roots.py
-../twisted/python/runtime.py
-../twisted/python/shortcut.py
-../twisted/python/syslog.py
-../twisted/python/systemd.py
-../twisted/python/text.py
-../twisted/python/threadable.py
-../twisted/python/threadpool.py
-../twisted/python/urlpath.py
-../twisted/python/usage.py
-../twisted/python/util.py
-../twisted/python/versions.py
-../twisted/python/win32.py
-../twisted/python/zippath.py
-../twisted/python/zipstream.py
-../twisted/python/test/__init__.py
-../twisted/python/test/deprecatedattributes.py
-../twisted/python/test/modules_helpers.py
-../twisted/python/test/pullpipe.py
-../twisted/python/test/test_components.py
-../twisted/python/test/test_constants.py
-../twisted/python/test/test_deprecate.py
-../twisted/python/test/test_dist.py
-../twisted/python/test/test_dist3.py
-../twisted/python/test/test_fakepwd.py
-../twisted/python/test/test_hashlib.py
-../twisted/python/test/test_htmlizer.py
-../twisted/python/test/test_inotify.py
-../twisted/python/test/test_release.py
-../twisted/python/test/test_runtime.py
-../twisted/python/test/test_sendmsg.py
-../twisted/python/test/test_shellcomp.py
-../twisted/python/test/test_syslog.py
-../twisted/python/test/test_systemd.py
-../twisted/python/test/test_textattributes.py
-../twisted/python/test/test_urlpath.py
-../twisted/python/test/test_util.py
-../twisted/python/test/test_versions.py
-../twisted/python/test/test_win32.py
-../twisted/python/test/test_zippath.py
-../twisted/python/test/test_zipstream.py
-../twisted/runner/__init__.py
-../twisted/runner/_version.py
-../twisted/runner/inetd.py
-../twisted/runner/inetdconf.py
-../twisted/runner/inetdtap.py
-../twisted/runner/procmon.py
-../twisted/runner/procmontap.py
-../twisted/runner/test/__init__.py
-../twisted/runner/test/test_procmon.py
-../twisted/runner/test/test_procmontap.py
-../twisted/scripts/__init__.py
-../twisted/scripts/_twistd_unix.py
-../twisted/scripts/_twistw.py
-../twisted/scripts/htmlizer.py
-../twisted/scripts/manhole.py
-../twisted/scripts/tap2deb.py
-../twisted/scripts/tap2rpm.py
-../twisted/scripts/tapconvert.py
-../twisted/scripts/tkunzip.py
-../twisted/scripts/trial.py
-../twisted/scripts/twistd.py
-../twisted/scripts/test/__init__.py
-../twisted/scripts/test/test_scripts.py
-../twisted/scripts/test/test_tap2deb.py
-../twisted/scripts/test/test_tap2rpm.py
-../twisted/spread/__init__.py
-../twisted/spread/banana.py
-../twisted/spread/flavors.py
-../twisted/spread/interfaces.py
-../twisted/spread/jelly.py
-../twisted/spread/pb.py
-../twisted/spread/publish.py
-../twisted/spread/util.py
-../twisted/spread/ui/__init__.py
-../twisted/spread/ui/gtk2util.py
-../twisted/spread/ui/tktree.py
-../twisted/spread/ui/tkutil.py
-../twisted/tap/__init__.py
-../twisted/tap/ftp.py
-../twisted/tap/manhole.py
-../twisted/tap/portforward.py
-../twisted/tap/socks.py
-../twisted/tap/telnet.py
-../twisted/test/__init__.py
-../twisted/test/_preamble.py
-../twisted/test/crash_test_dummy.py
-../twisted/test/iosim.py
-../twisted/test/mock_win32process.py
-../twisted/test/myrebuilder1.py
-../twisted/test/myrebuilder2.py
-../twisted/test/plugin_basic.py
-../twisted/test/plugin_extra1.py
-../twisted/test/plugin_extra2.py
-../twisted/test/process_cmdline.py
-../twisted/test/process_echoer.py
-../twisted/test/process_fds.py
-../twisted/test/process_linger.py
-../twisted/test/process_reader.py
-../twisted/test/process_signal.py
-../twisted/test/process_stdinreader.py
-../twisted/test/process_tester.py
-../twisted/test/process_tty.py
-../twisted/test/process_twisted.py
-../twisted/test/proto_helpers.py
-../twisted/test/reflect_helper_IE.py
-../twisted/test/reflect_helper_VE.py
-../twisted/test/reflect_helper_ZDE.py
-../twisted/test/ssl_helpers.py
-../twisted/test/stdio_test_consumer.py
-../twisted/test/stdio_test_halfclose.py
-../twisted/test/stdio_test_hostpeer.py
-../twisted/test/stdio_test_lastwrite.py
-../twisted/test/stdio_test_loseconn.py
-../twisted/test/stdio_test_producer.py
-../twisted/test/stdio_test_write.py
-../twisted/test/stdio_test_writeseq.py
-../twisted/test/test_abstract.py
-../twisted/test/test_adbapi.py
-../twisted/test/test_amp.py
-../twisted/test/test_application.py
-../twisted/test/test_banana.py
-../twisted/test/test_compat.py
-../twisted/test/test_context.py
-../twisted/test/test_cooperator.py
-../twisted/test/test_defer.py
-../twisted/test/test_defgen.py
-../twisted/test/test_dict.py
-../twisted/test/test_digestauth.py
-../twisted/test/test_dirdbm.py
-../twisted/test/test_doc.py
-../twisted/test/test_error.py
-../twisted/test/test_explorer.py
-../twisted/test/test_factories.py
-../twisted/test/test_failure.py
-../twisted/test/test_fdesc.py
-../twisted/test/test_finger.py
-../twisted/test/test_formmethod.py
-../twisted/test/test_ftp.py
-../twisted/test/test_ftp_options.py
-../twisted/test/test_hook.py
-../twisted/test/test_htb.py
-../twisted/test/test_ident.py
-../twisted/test/test_internet.py
-../twisted/test/test_iosim.py
-../twisted/test/test_iutils.py
-../twisted/test/test_jelly.py
-../twisted/test/test_lockfile.py
-../twisted/test/test_log.py
-../twisted/test/test_logfile.py
-../twisted/test/test_loopback.py
-../twisted/test/test_manhole.py
-../twisted/test/test_memcache.py
-../twisted/test/test_modules.py
-../twisted/test/test_monkey.py
-../twisted/test/test_newcred.py
-../twisted/test/test_nmea.py
-../twisted/test/test_paths.py
-../twisted/test/test_pb.py
-../twisted/test/test_pbfailure.py
-../twisted/test/test_pcp.py
-../twisted/test/test_persisted.py
-../twisted/test/test_plugin.py
-../twisted/test/test_policies.py
-../twisted/test/test_postfix.py
-../twisted/test/test_process.py
-../twisted/test/test_protocols.py
-../twisted/test/test_randbytes.py
-../twisted/test/test_rebuild.py
-../twisted/test/test_reflect.py
-../twisted/test/test_roots.py
-../twisted/test/test_setup.py
-../twisted/test/test_shortcut.py
-../twisted/test/test_sip.py
-../twisted/test/test_sob.py
-../twisted/test/test_socks.py
-../twisted/test/test_ssl.py
-../twisted/test/test_sslverify.py
-../twisted/test/test_stateful.py
-../twisted/test/test_stdio.py
-../twisted/test/test_strcred.py
-../twisted/test/test_strerror.py
-../twisted/test/test_stringtransport.py
-../twisted/test/test_strports.py
-../twisted/test/test_task.py
-../twisted/test/test_tcp.py
-../twisted/test/test_tcp_internals.py
-../twisted/test/test_text.py
-../twisted/test/test_threadable.py
-../twisted/test/test_threadpool.py
-../twisted/test/test_threads.py
-../twisted/test/test_tpfile.py
-../twisted/test/test_twistd.py
-../twisted/test/test_twisted.py
-../twisted/test/test_udp.py
-../twisted/test/test_unix.py
-../twisted/test/test_usage.py
-../twisted/test/testutils.py
-../twisted/trial/__init__.py
-../twisted/trial/_asyncrunner.py
-../twisted/trial/_asynctest.py
-../twisted/trial/_synctest.py
-../twisted/trial/itrial.py
-../twisted/trial/reporter.py
-../twisted/trial/runner.py
-../twisted/trial/unittest.py
-../twisted/trial/util.py
-../twisted/trial/_dist/__init__.py
-../twisted/trial/_dist/distreporter.py
-../twisted/trial/_dist/disttrial.py
-../twisted/trial/_dist/managercommands.py
-../twisted/trial/_dist/options.py
-../twisted/trial/_dist/worker.py
-../twisted/trial/_dist/workercommands.py
-../twisted/trial/_dist/workerreporter.py
-../twisted/trial/_dist/workertrial.py
-../twisted/trial/_dist/test/__init__.py
-../twisted/trial/_dist/test/test_distreporter.py
-../twisted/trial/_dist/test/test_disttrial.py
-../twisted/trial/_dist/test/test_options.py
-../twisted/trial/_dist/test/test_worker.py
-../twisted/trial/_dist/test/test_workerreporter.py
-../twisted/trial/_dist/test/test_workertrial.py
-../twisted/trial/test/__init__.py
-../twisted/trial/test/detests.py
-../twisted/trial/test/erroneous.py
-../twisted/trial/test/mockcustomsuite.py
-../twisted/trial/test/mockcustomsuite2.py
-../twisted/trial/test/mockcustomsuite3.py
-../twisted/trial/test/mockdoctest.py
-../twisted/trial/test/moduleself.py
-../twisted/trial/test/moduletest.py
-../twisted/trial/test/novars.py
-../twisted/trial/test/ordertests.py
-../twisted/trial/test/packages.py
-../twisted/trial/test/sample.py
-../twisted/trial/test/scripttest.py
-../twisted/trial/test/skipping.py
-../twisted/trial/test/suppression.py
-../twisted/trial/test/test_assertions.py
-../twisted/trial/test/test_asyncassertions.py
-../twisted/trial/test/test_deferred.py
-../twisted/trial/test/test_doctest.py
-../twisted/trial/test/test_keyboard.py
-../twisted/trial/test/test_loader.py
-../twisted/trial/test/test_log.py
-../twisted/trial/test/test_output.py
-../twisted/trial/test/test_plugins.py
-../twisted/trial/test/test_pyunitcompat.py
-../twisted/trial/test/test_reporter.py
-../twisted/trial/test/test_runner.py
-../twisted/trial/test/test_script.py
-../twisted/trial/test/test_suppression.py
-../twisted/trial/test/test_testcase.py
-../twisted/trial/test/test_tests.py
-../twisted/trial/test/test_util.py
-../twisted/trial/test/test_warning.py
-../twisted/trial/test/weird.py
-../twisted/web/__init__.py
-../twisted/web/_element.py
-../twisted/web/_flatten.py
-../twisted/web/_newclient.py
-../twisted/web/_responses.py
-../twisted/web/_stan.py
-../twisted/web/_version.py
-../twisted/web/client.py
-../twisted/web/demo.py
-../twisted/web/distrib.py
-../twisted/web/domhelpers.py
-../twisted/web/error.py
-../twisted/web/guard.py
-../twisted/web/html.py
-../twisted/web/http.py
-../twisted/web/http_headers.py
-../twisted/web/iweb.py
-../twisted/web/microdom.py
-../twisted/web/proxy.py
-../twisted/web/resource.py
-../twisted/web/rewrite.py
-../twisted/web/script.py
-../twisted/web/server.py
-../twisted/web/soap.py
-../twisted/web/static.py
-../twisted/web/sux.py
-../twisted/web/tap.py
-../twisted/web/template.py
-../twisted/web/twcgi.py
-../twisted/web/util.py
-../twisted/web/vhost.py
-../twisted/web/wsgi.py
-../twisted/web/xmlrpc.py
-../twisted/web/_auth/__init__.py
-../twisted/web/_auth/basic.py
-../twisted/web/_auth/digest.py
-../twisted/web/_auth/wrapper.py
-../twisted/web/test/__init__.py
-../twisted/web/test/_util.py
-../twisted/web/test/requesthelper.py
-../twisted/web/test/test_agent.py
-../twisted/web/test/test_cgi.py
-../twisted/web/test/test_distrib.py
-../twisted/web/test/test_domhelpers.py
-../twisted/web/test/test_error.py
-../twisted/web/test/test_flatten.py
-../twisted/web/test/test_http.py
-../twisted/web/test/test_http_headers.py
-../twisted/web/test/test_httpauth.py
-../twisted/web/test/test_newclient.py
-../twisted/web/test/test_proxy.py
-../twisted/web/test/test_resource.py
-../twisted/web/test/test_script.py
-../twisted/web/test/test_soap.py
-../twisted/web/test/test_stan.py
-../twisted/web/test/test_static.py
-../twisted/web/test/test_tap.py
-../twisted/web/test/test_template.py
-../twisted/web/test/test_util.py
-../twisted/web/test/test_vhost.py
-../twisted/web/test/test_web.py
-../twisted/web/test/test_webclient.py
-../twisted/web/test/test_wsgi.py
-../twisted/web/test/test_xml.py
-../twisted/web/test/test_xmlrpc.py
-../twisted/words/__init__.py
-../twisted/words/_version.py
-../twisted/words/ewords.py
-../twisted/words/iwords.py
-../twisted/words/service.py
-../twisted/words/tap.py
-../twisted/words/xmpproutertap.py
-../twisted/words/im/__init__.py
-../twisted/words/im/baseaccount.py
-../twisted/words/im/basechat.py
-../twisted/words/im/basesupport.py
-../twisted/words/im/interfaces.py
-../twisted/words/im/ircsupport.py
-../twisted/words/im/locals.py
-../twisted/words/im/pbsupport.py
-../twisted/words/protocols/__init__.py
-../twisted/words/protocols/irc.py
-../twisted/words/protocols/msn.py
-../twisted/words/protocols/oscar.py
-../twisted/words/protocols/jabber/__init__.py
-../twisted/words/protocols/jabber/client.py
-../twisted/words/protocols/jabber/component.py
-../twisted/words/protocols/jabber/error.py
-../twisted/words/protocols/jabber/ijabber.py
-../twisted/words/protocols/jabber/jid.py
-../twisted/words/protocols/jabber/jstrports.py
-../twisted/words/protocols/jabber/sasl.py
-../twisted/words/protocols/jabber/sasl_mechanisms.py
-../twisted/words/protocols/jabber/xmlstream.py
-../twisted/words/protocols/jabber/xmpp_stringprep.py
-../twisted/words/test/__init__.py
-../twisted/words/test/test_basechat.py
-../twisted/words/test/test_basesupport.py
-../twisted/words/test/test_domish.py
-../twisted/words/test/test_irc.py
-../twisted/words/test/test_irc_service.py
-../twisted/words/test/test_ircsupport.py
-../twisted/words/test/test_jabberclient.py
-../twisted/words/test/test_jabbercomponent.py
-../twisted/words/test/test_jabbererror.py
-../twisted/words/test/test_jabberjid.py
-../twisted/words/test/test_jabberjstrports.py
-../twisted/words/test/test_jabbersasl.py
-../twisted/words/test/test_jabbersaslmechanisms.py
-../twisted/words/test/test_jabberxmlstream.py
-../twisted/words/test/test_jabberxmppstringprep.py
-../twisted/words/test/test_msn.py
-../twisted/words/test/test_oscar.py
-../twisted/words/test/test_service.py
-../twisted/words/test/test_tap.py
-../twisted/words/test/test_xishutil.py
-../twisted/words/test/test_xmlstream.py
-../twisted/words/test/test_xmpproutertap.py
-../twisted/words/test/test_xpath.py
-../twisted/words/xish/__init__.py
-../twisted/words/xish/domish.py
-../twisted/words/xish/utility.py
-../twisted/words/xish/xmlstream.py
-../twisted/words/xish/xpath.py
-../twisted/words/xish/xpathparser.py
-../twisted/internet/iocpreactor/iocpsupport/iocpsupport.c
-../twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c
-../twisted/python/sendmsg.c
-../twisted/runner/portmap.c
-../twisted/test/raiser.c
-../twisted/__init__.pyc
-../twisted/_version.pyc
-../twisted/copyright.pyc
-../twisted/plugin.pyc
-../twisted/application/__init__.pyc
-../twisted/application/app.pyc
-../twisted/application/internet.pyc
-../twisted/application/reactors.pyc
-../twisted/application/service.pyc
-../twisted/application/strports.pyc
-../twisted/application/test/__init__.pyc
-../twisted/application/test/test_internet.pyc
-../twisted/conch/__init__.pyc
-../twisted/conch/_version.pyc
-../twisted/conch/avatar.pyc
-../twisted/conch/checkers.pyc
-../twisted/conch/endpoints.pyc
-../twisted/conch/error.pyc
-../twisted/conch/interfaces.pyc
-../twisted/conch/ls.pyc
-../twisted/conch/manhole.pyc
-../twisted/conch/manhole_ssh.pyc
-../twisted/conch/manhole_tap.pyc
-../twisted/conch/mixin.pyc
-../twisted/conch/recvline.pyc
-../twisted/conch/stdio.pyc
-../twisted/conch/tap.pyc
-../twisted/conch/telnet.pyc
-../twisted/conch/ttymodes.pyc
-../twisted/conch/unix.pyc
-../twisted/conch/client/__init__.pyc
-../twisted/conch/client/agent.pyc
-../twisted/conch/client/connect.pyc
-../twisted/conch/client/default.pyc
-../twisted/conch/client/direct.pyc
-../twisted/conch/client/knownhosts.pyc
-../twisted/conch/client/options.pyc
-../twisted/conch/insults/__init__.pyc
-../twisted/conch/insults/client.pyc
-../twisted/conch/insults/colors.pyc
-../twisted/conch/insults/helper.pyc
-../twisted/conch/insults/insults.pyc
-../twisted/conch/insults/text.pyc
-../twisted/conch/insults/window.pyc
-../twisted/conch/openssh_compat/__init__.pyc
-../twisted/conch/openssh_compat/factory.pyc
-../twisted/conch/openssh_compat/primes.pyc
-../twisted/conch/scripts/__init__.pyc
-../twisted/conch/scripts/cftp.pyc
-../twisted/conch/scripts/ckeygen.pyc
-../twisted/conch/scripts/conch.pyc
-../twisted/conch/scripts/tkconch.pyc
-../twisted/conch/ssh/__init__.pyc
-../twisted/conch/ssh/address.pyc
-../twisted/conch/ssh/agent.pyc
-../twisted/conch/ssh/channel.pyc
-../twisted/conch/ssh/common.pyc
-../twisted/conch/ssh/connection.pyc
-../twisted/conch/ssh/factory.pyc
-../twisted/conch/ssh/filetransfer.pyc
-../twisted/conch/ssh/forwarding.pyc
-../twisted/conch/ssh/keys.pyc
-../twisted/conch/ssh/service.pyc
-../twisted/conch/ssh/session.pyc
-../twisted/conch/ssh/sexpy.pyc
-../twisted/conch/ssh/transport.pyc
-../twisted/conch/ssh/userauth.pyc
-../twisted/conch/test/__init__.pyc
-../twisted/conch/test/keydata.pyc
-../twisted/conch/test/test_address.pyc
-../twisted/conch/test/test_agent.pyc
-../twisted/conch/test/test_cftp.pyc
-../twisted/conch/test/test_channel.pyc
-../twisted/conch/test/test_checkers.pyc
-../twisted/conch/test/test_ckeygen.pyc
-../twisted/conch/test/test_conch.pyc
-../twisted/conch/test/test_connection.pyc
-../twisted/conch/test/test_default.pyc
-../twisted/conch/test/test_endpoints.pyc
-../twisted/conch/test/test_filetransfer.pyc
-../twisted/conch/test/test_helper.pyc
-../twisted/conch/test/test_insults.pyc
-../twisted/conch/test/test_keys.pyc
-../twisted/conch/test/test_knownhosts.pyc
-../twisted/conch/test/test_manhole.pyc
-../twisted/conch/test/test_mixin.pyc
-../twisted/conch/test/test_openssh_compat.pyc
-../twisted/conch/test/test_recvline.pyc
-../twisted/conch/test/test_scripts.pyc
-../twisted/conch/test/test_session.pyc
-../twisted/conch/test/test_ssh.pyc
-../twisted/conch/test/test_tap.pyc
-../twisted/conch/test/test_telnet.pyc
-../twisted/conch/test/test_text.pyc
-../twisted/conch/test/test_transport.pyc
-../twisted/conch/test/test_userauth.pyc
-../twisted/conch/test/test_window.pyc
-../twisted/conch/ui/__init__.pyc
-../twisted/conch/ui/ansi.pyc
-../twisted/conch/ui/tkvt100.pyc
-../twisted/cred/__init__.pyc
-../twisted/cred/_digest.pyc
-../twisted/cred/checkers.pyc
-../twisted/cred/credentials.pyc
-../twisted/cred/error.pyc
-../twisted/cred/pamauth.pyc
-../twisted/cred/portal.pyc
-../twisted/cred/strcred.pyc
-../twisted/enterprise/__init__.pyc
-../twisted/enterprise/adbapi.pyc
-../twisted/internet/__init__.pyc
-../twisted/internet/_baseprocess.pyc
-../twisted/internet/_dumbwin32proc.pyc
-../twisted/internet/_glibbase.pyc
-../twisted/internet/_newtls.pyc
-../twisted/internet/_pollingfile.pyc
-../twisted/internet/_posixserialport.pyc
-../twisted/internet/_posixstdio.pyc
-../twisted/internet/_signals.pyc
-../twisted/internet/_ssl.pyc
-../twisted/internet/_sslverify.pyc
-../twisted/internet/_threadedselect.pyc
-../twisted/internet/_win32serialport.pyc
-../twisted/internet/_win32stdio.pyc
-../twisted/internet/abstract.pyc
-../twisted/internet/address.pyc
-../twisted/internet/base.pyc
-../twisted/internet/cfreactor.pyc
-../twisted/internet/default.pyc
-../twisted/internet/defer.pyc
-../twisted/internet/endpoints.pyc
-../twisted/internet/epollreactor.pyc
-../twisted/internet/error.pyc
-../twisted/internet/fdesc.pyc
-../twisted/internet/gireactor.pyc
-../twisted/internet/glib2reactor.pyc
-../twisted/internet/gtk2reactor.pyc
-../twisted/internet/gtk3reactor.pyc
-../twisted/internet/gtkreactor.pyc
-../twisted/internet/inotify.pyc
-../twisted/internet/interfaces.pyc
-../twisted/internet/kqreactor.pyc
-../twisted/internet/main.pyc
-../twisted/internet/pollreactor.pyc
-../twisted/internet/posixbase.pyc
-../twisted/internet/process.pyc
-../twisted/internet/protocol.pyc
-../twisted/internet/pyuisupport.pyc
-../twisted/internet/qtreactor.pyc
-../twisted/internet/reactor.pyc
-../twisted/internet/selectreactor.pyc
-../twisted/internet/serialport.pyc
-../twisted/internet/ssl.pyc
-../twisted/internet/stdio.pyc
-../twisted/internet/task.pyc
-../twisted/internet/tcp.pyc
-../twisted/internet/threads.pyc
-../twisted/internet/tksupport.pyc
-../twisted/internet/udp.pyc
-../twisted/internet/unix.pyc
-../twisted/internet/utils.pyc
-../twisted/internet/win32eventreactor.pyc
-../twisted/internet/wxreactor.pyc
-../twisted/internet/wxsupport.pyc
-../twisted/internet/iocpreactor/__init__.pyc
-../twisted/internet/iocpreactor/abstract.pyc
-../twisted/internet/iocpreactor/const.pyc
-../twisted/internet/iocpreactor/interfaces.pyc
-../twisted/internet/iocpreactor/reactor.pyc
-../twisted/internet/iocpreactor/setup.pyc
-../twisted/internet/iocpreactor/tcp.pyc
-../twisted/internet/iocpreactor/udp.pyc
-../twisted/internet/test/__init__.pyc
-../twisted/internet/test/_posixifaces.pyc
-../twisted/internet/test/_win32ifaces.pyc
-../twisted/internet/test/connectionmixins.pyc
-../twisted/internet/test/fakeendpoint.pyc
-../twisted/internet/test/modulehelpers.pyc
-../twisted/internet/test/process_gireactornocompat.pyc
-../twisted/internet/test/process_helper.pyc
-../twisted/internet/test/reactormixins.pyc
-../twisted/internet/test/test_abstract.pyc
-../twisted/internet/test/test_address.pyc
-../twisted/internet/test/test_base.pyc
-../twisted/internet/test/test_baseprocess.pyc
-../twisted/internet/test/test_core.pyc
-../twisted/internet/test/test_default.pyc
-../twisted/internet/test/test_endpoints.pyc
-../twisted/internet/test/test_epollreactor.pyc
-../twisted/internet/test/test_fdset.pyc
-../twisted/internet/test/test_filedescriptor.pyc
-../twisted/internet/test/test_gireactor.pyc
-../twisted/internet/test/test_glibbase.pyc
-../twisted/internet/test/test_gtkreactor.pyc
-../twisted/internet/test/test_inlinecb.pyc
-../twisted/internet/test/test_inotify.pyc
-../twisted/internet/test/test_iocp.pyc
-../twisted/internet/test/test_main.pyc
-../twisted/internet/test/test_newtls.pyc
-../twisted/internet/test/test_pollingfile.pyc
-../twisted/internet/test/test_posixbase.pyc
-../twisted/internet/test/test_posixprocess.pyc
-../twisted/internet/test/test_process.pyc
-../twisted/internet/test/test_protocol.pyc
-../twisted/internet/test/test_qtreactor.pyc
-../twisted/internet/test/test_serialport.pyc
-../twisted/internet/test/test_sigchld.pyc
-../twisted/internet/test/test_socket.pyc
-../twisted/internet/test/test_stdio.pyc
-../twisted/internet/test/test_tcp.pyc
-../twisted/internet/test/test_threads.pyc
-../twisted/internet/test/test_time.pyc
-../twisted/internet/test/test_tls.pyc
-../twisted/internet/test/test_udp.pyc
-../twisted/internet/test/test_udp_internals.pyc
-../twisted/internet/test/test_unix.pyc
-../twisted/internet/test/test_win32events.pyc
-../twisted/lore/__init__.pyc
-../twisted/lore/_version.pyc
-../twisted/lore/default.pyc
-../twisted/lore/docbook.pyc
-../twisted/lore/htmlbook.pyc
-../twisted/lore/indexer.pyc
-../twisted/lore/latex.pyc
-../twisted/lore/lint.pyc
-../twisted/lore/lmath.pyc
-../twisted/lore/man2lore.pyc
-../twisted/lore/numberer.pyc
-../twisted/lore/process.pyc
-../twisted/lore/slides.pyc
-../twisted/lore/texi.pyc
-../twisted/lore/tree.pyc
-../twisted/lore/scripts/__init__.pyc
-../twisted/lore/scripts/lore.pyc
-../twisted/lore/test/__init__.pyc
-../twisted/lore/test/test_docbook.pyc
-../twisted/lore/test/test_latex.pyc
-../twisted/lore/test/test_lint.pyc
-../twisted/lore/test/test_lmath.pyc
-../twisted/lore/test/test_lore.pyc
-../twisted/lore/test/test_man2lore.pyc
-../twisted/lore/test/test_scripts.pyc
-../twisted/lore/test/test_slides.pyc
-../twisted/lore/test/test_texi.pyc
-../twisted/mail/__init__.pyc
-../twisted/mail/_version.pyc
-../twisted/mail/alias.pyc
-../twisted/mail/bounce.pyc
-../twisted/mail/imap4.pyc
-../twisted/mail/mail.pyc
-../twisted/mail/maildir.pyc
-../twisted/mail/pb.pyc
-../twisted/mail/pop3.pyc
-../twisted/mail/pop3client.pyc
-../twisted/mail/protocols.pyc
-../twisted/mail/relay.pyc
-../twisted/mail/relaymanager.pyc
-../twisted/mail/smtp.pyc
-../twisted/mail/tap.pyc
-../twisted/mail/scripts/__init__.pyc
-../twisted/mail/scripts/mailmail.pyc
-../twisted/mail/test/__init__.pyc
-../twisted/mail/test/pop3testserver.pyc
-../twisted/mail/test/test_bounce.pyc
-../twisted/mail/test/test_imap.pyc
-../twisted/mail/test/test_mail.pyc
-../twisted/mail/test/test_mailmail.pyc
-../twisted/mail/test/test_options.pyc
-../twisted/mail/test/test_pop3.pyc
-../twisted/mail/test/test_pop3client.pyc
-../twisted/mail/test/test_scripts.pyc
-../twisted/mail/test/test_smtp.pyc
-../twisted/manhole/__init__.pyc
-../twisted/manhole/_inspectro.pyc
-../twisted/manhole/explorer.pyc
-../twisted/manhole/gladereactor.pyc
-../twisted/manhole/service.pyc
-../twisted/manhole/telnet.pyc
-../twisted/manhole/test/__init__.pyc
-../twisted/manhole/test/test_explorer.pyc
-../twisted/manhole/ui/__init__.pyc
-../twisted/manhole/ui/gtk2manhole.pyc
-../twisted/manhole/ui/test/__init__.pyc
-../twisted/manhole/ui/test/test_gtk2manhole.pyc
-../twisted/names/__init__.pyc
-../twisted/names/_rfc1982.pyc
-../twisted/names/_version.pyc
-../twisted/names/authority.pyc
-../twisted/names/cache.pyc
-../twisted/names/client.pyc
-../twisted/names/common.pyc
-../twisted/names/dns.pyc
-../twisted/names/error.pyc
-../twisted/names/hosts.pyc
-../twisted/names/resolve.pyc
-../twisted/names/root.pyc
-../twisted/names/secondary.pyc
-../twisted/names/server.pyc
-../twisted/names/srvconnect.pyc
-../twisted/names/tap.pyc
-../twisted/names/test/__init__.pyc
-../twisted/names/test/test_cache.pyc
-../twisted/names/test/test_client.pyc
-../twisted/names/test/test_common.pyc
-../twisted/names/test/test_dns.pyc
-../twisted/names/test/test_examples.pyc
-../twisted/names/test/test_hosts.pyc
-../twisted/names/test/test_names.pyc
-../twisted/names/test/test_resolve.pyc
-../twisted/names/test/test_rfc1982.pyc
-../twisted/names/test/test_rootresolve.pyc
-../twisted/names/test/test_server.pyc
-../twisted/names/test/test_srvconnect.pyc
-../twisted/names/test/test_tap.pyc
-../twisted/news/__init__.pyc
-../twisted/news/_version.pyc
-../twisted/news/database.pyc
-../twisted/news/news.pyc
-../twisted/news/nntp.pyc
-../twisted/news/tap.pyc
-../twisted/news/test/__init__.pyc
-../twisted/news/test/test_database.pyc
-../twisted/news/test/test_news.pyc
-../twisted/news/test/test_nntp.pyc
-../twisted/pair/__init__.pyc
-../twisted/pair/_version.pyc
-../twisted/pair/ethernet.pyc
-../twisted/pair/ip.pyc
-../twisted/pair/raw.pyc
-../twisted/pair/rawudp.pyc
-../twisted/pair/testing.pyc
-../twisted/pair/tuntap.pyc
-../twisted/pair/test/__init__.pyc
-../twisted/pair/test/test_ethernet.pyc
-../twisted/pair/test/test_ip.pyc
-../twisted/pair/test/test_rawudp.pyc
-../twisted/pair/test/test_tuntap.pyc
-../twisted/persisted/__init__.pyc
-../twisted/persisted/aot.pyc
-../twisted/persisted/crefutil.pyc
-../twisted/persisted/dirdbm.pyc
-../twisted/persisted/sob.pyc
-../twisted/persisted/styles.pyc
-../twisted/persisted/test/__init__.pyc
-../twisted/persisted/test/test_styles.pyc
-../twisted/plugins/__init__.pyc
-../twisted/plugins/cred_anonymous.pyc
-../twisted/plugins/cred_file.pyc
-../twisted/plugins/cred_memory.pyc
-../twisted/plugins/cred_sshkeys.pyc
-../twisted/plugins/cred_unix.pyc
-../twisted/plugins/twisted_conch.pyc
-../twisted/plugins/twisted_core.pyc
-../twisted/plugins/twisted_ftp.pyc
-../twisted/plugins/twisted_inet.pyc
-../twisted/plugins/twisted_lore.pyc
-../twisted/plugins/twisted_mail.pyc
-../twisted/plugins/twisted_manhole.pyc
-../twisted/plugins/twisted_names.pyc
-../twisted/plugins/twisted_news.pyc
-../twisted/plugins/twisted_portforward.pyc
-../twisted/plugins/twisted_qtstub.pyc
-../twisted/plugins/twisted_reactors.pyc
-../twisted/plugins/twisted_runner.pyc
-../twisted/plugins/twisted_socks.pyc
-../twisted/plugins/twisted_telnet.pyc
-../twisted/plugins/twisted_trial.pyc
-../twisted/plugins/twisted_web.pyc
-../twisted/plugins/twisted_words.pyc
-../twisted/positioning/__init__.pyc
-../twisted/positioning/_sentence.pyc
-../twisted/positioning/base.pyc
-../twisted/positioning/ipositioning.pyc
-../twisted/positioning/nmea.pyc
-../twisted/positioning/test/__init__.pyc
-../twisted/positioning/test/receiver.pyc
-../twisted/positioning/test/test_base.pyc
-../twisted/positioning/test/test_nmea.pyc
-../twisted/positioning/test/test_sentence.pyc
-../twisted/protocols/__init__.pyc
-../twisted/protocols/amp.pyc
-../twisted/protocols/basic.pyc
-../twisted/protocols/dict.pyc
-../twisted/protocols/finger.pyc
-../twisted/protocols/ftp.pyc
-../twisted/protocols/htb.pyc
-../twisted/protocols/ident.pyc
-../twisted/protocols/loopback.pyc
-../twisted/protocols/memcache.pyc
-../twisted/protocols/pcp.pyc
-../twisted/protocols/policies.pyc
-../twisted/protocols/portforward.pyc
-../twisted/protocols/postfix.pyc
-../twisted/protocols/shoutcast.pyc
-../twisted/protocols/sip.pyc
-../twisted/protocols/socks.pyc
-../twisted/protocols/stateful.pyc
-../twisted/protocols/telnet.pyc
-../twisted/protocols/tls.pyc
-../twisted/protocols/wire.pyc
-../twisted/protocols/gps/__init__.pyc
-../twisted/protocols/gps/nmea.pyc
-../twisted/protocols/gps/rockwell.pyc
-../twisted/protocols/mice/__init__.pyc
-../twisted/protocols/mice/mouseman.pyc
-../twisted/protocols/test/__init__.pyc
-../twisted/protocols/test/test_basic.pyc
-../twisted/protocols/test/test_tls.pyc
-../twisted/python/__init__.pyc
-../twisted/python/_inotify.pyc
-../twisted/python/_release.pyc
-../twisted/python/_shellcomp.pyc
-../twisted/python/_textattributes.pyc
-../twisted/python/compat.pyc
-../twisted/python/components.pyc
-../twisted/python/constants.pyc
-../twisted/python/context.pyc
-../twisted/python/deprecate.pyc
-../twisted/python/dist.pyc
-../twisted/python/dist3.pyc
-../twisted/python/failure.pyc
-../twisted/python/fakepwd.pyc
-../twisted/python/filepath.pyc
-../twisted/python/finalize.pyc
-../twisted/python/formmethod.pyc
-../twisted/python/hashlib.pyc
-../twisted/python/hook.pyc
-../twisted/python/htmlizer.pyc
-../twisted/python/lockfile.pyc
-../twisted/python/log.pyc
-../twisted/python/logfile.pyc
-../twisted/python/modules.pyc
-../twisted/python/monkey.pyc
-../twisted/python/procutils.pyc
-../twisted/python/randbytes.pyc
-../twisted/python/rebuild.pyc
-../twisted/python/reflect.pyc
-../twisted/python/release.pyc
-../twisted/python/roots.pyc
-../twisted/python/runtime.pyc
-../twisted/python/shortcut.pyc
-../twisted/python/syslog.pyc
-../twisted/python/systemd.pyc
-../twisted/python/text.pyc
-../twisted/python/threadable.pyc
-../twisted/python/threadpool.pyc
-../twisted/python/urlpath.pyc
-../twisted/python/usage.pyc
-../twisted/python/util.pyc
-../twisted/python/versions.pyc
-../twisted/python/win32.pyc
-../twisted/python/zippath.pyc
-../twisted/python/zipstream.pyc
-../twisted/python/test/__init__.pyc
-../twisted/python/test/deprecatedattributes.pyc
-../twisted/python/test/modules_helpers.pyc
-../twisted/python/test/pullpipe.pyc
-../twisted/python/test/test_components.pyc
-../twisted/python/test/test_constants.pyc
-../twisted/python/test/test_deprecate.pyc
-../twisted/python/test/test_dist.pyc
-../twisted/python/test/test_dist3.pyc
-../twisted/python/test/test_fakepwd.pyc
-../twisted/python/test/test_hashlib.pyc
-../twisted/python/test/test_htmlizer.pyc
-../twisted/python/test/test_inotify.pyc
-../twisted/python/test/test_release.pyc
-../twisted/python/test/test_runtime.pyc
-../twisted/python/test/test_sendmsg.pyc
-../twisted/python/test/test_shellcomp.pyc
-../twisted/python/test/test_syslog.pyc
-../twisted/python/test/test_systemd.pyc
-../twisted/python/test/test_textattributes.pyc
-../twisted/python/test/test_urlpath.pyc
-../twisted/python/test/test_util.pyc
-../twisted/python/test/test_versions.pyc
-../twisted/python/test/test_win32.pyc
-../twisted/python/test/test_zippath.pyc
-../twisted/python/test/test_zipstream.pyc
-../twisted/runner/__init__.pyc
-../twisted/runner/_version.pyc
-../twisted/runner/inetd.pyc
-../twisted/runner/inetdconf.pyc
-../twisted/runner/inetdtap.pyc
-../twisted/runner/procmon.pyc
-../twisted/runner/procmontap.pyc
-../twisted/runner/test/__init__.pyc
-../twisted/runner/test/test_procmon.pyc
-../twisted/runner/test/test_procmontap.pyc
-../twisted/scripts/__init__.pyc
-../twisted/scripts/_twistd_unix.pyc
-../twisted/scripts/_twistw.pyc
-../twisted/scripts/htmlizer.pyc
-../twisted/scripts/manhole.pyc
-../twisted/scripts/tap2deb.pyc
-../twisted/scripts/tap2rpm.pyc
-../twisted/scripts/tapconvert.pyc
-../twisted/scripts/tkunzip.pyc
-../twisted/scripts/trial.pyc
-../twisted/scripts/twistd.pyc
-../twisted/scripts/test/__init__.pyc
-../twisted/scripts/test/test_scripts.pyc
-../twisted/scripts/test/test_tap2deb.pyc
-../twisted/scripts/test/test_tap2rpm.pyc
-../twisted/spread/__init__.pyc
-../twisted/spread/banana.pyc
-../twisted/spread/flavors.pyc
-../twisted/spread/interfaces.pyc
-../twisted/spread/jelly.pyc
-../twisted/spread/pb.pyc
-../twisted/spread/publish.pyc
-../twisted/spread/util.pyc
-../twisted/spread/ui/__init__.pyc
-../twisted/spread/ui/gtk2util.pyc
-../twisted/spread/ui/tktree.pyc
-../twisted/spread/ui/tkutil.pyc
-../twisted/tap/__init__.pyc
-../twisted/tap/ftp.pyc
-../twisted/tap/manhole.pyc
-../twisted/tap/portforward.pyc
-../twisted/tap/socks.pyc
-../twisted/tap/telnet.pyc
-../twisted/test/__init__.pyc
-../twisted/test/_preamble.pyc
-../twisted/test/crash_test_dummy.pyc
-../twisted/test/iosim.pyc
-../twisted/test/mock_win32process.pyc
-../twisted/test/myrebuilder1.pyc
-../twisted/test/myrebuilder2.pyc
-../twisted/test/plugin_basic.pyc
-../twisted/test/plugin_extra1.pyc
-../twisted/test/plugin_extra2.pyc
-../twisted/test/process_cmdline.pyc
-../twisted/test/process_echoer.pyc
-../twisted/test/process_fds.pyc
-../twisted/test/process_linger.pyc
-../twisted/test/process_reader.pyc
-../twisted/test/process_signal.pyc
-../twisted/test/process_stdinreader.pyc
-../twisted/test/process_tester.pyc
-../twisted/test/process_tty.pyc
-../twisted/test/process_twisted.pyc
-../twisted/test/proto_helpers.pyc
-../twisted/test/reflect_helper_IE.pyc
-../twisted/test/reflect_helper_VE.pyc
-../twisted/test/reflect_helper_ZDE.pyc
-../twisted/test/ssl_helpers.pyc
-../twisted/test/stdio_test_consumer.pyc
-../twisted/test/stdio_test_halfclose.pyc
-../twisted/test/stdio_test_hostpeer.pyc
-../twisted/test/stdio_test_lastwrite.pyc
-../twisted/test/stdio_test_loseconn.pyc
-../twisted/test/stdio_test_producer.pyc
-../twisted/test/stdio_test_write.pyc
-../twisted/test/stdio_test_writeseq.pyc
-../twisted/test/test_abstract.pyc
-../twisted/test/test_adbapi.pyc
-../twisted/test/test_amp.pyc
-../twisted/test/test_application.pyc
-../twisted/test/test_banana.pyc
-../twisted/test/test_compat.pyc
-../twisted/test/test_context.pyc
-../twisted/test/test_cooperator.pyc
-../twisted/test/test_defer.pyc
-../twisted/test/test_defgen.pyc
-../twisted/test/test_dict.pyc
-../twisted/test/test_digestauth.pyc
-../twisted/test/test_dirdbm.pyc
-../twisted/test/test_doc.pyc
-../twisted/test/test_error.pyc
-../twisted/test/test_explorer.pyc
-../twisted/test/test_factories.pyc
-../twisted/test/test_failure.pyc
-../twisted/test/test_fdesc.pyc
-../twisted/test/test_finger.pyc
-../twisted/test/test_formmethod.pyc
-../twisted/test/test_ftp.pyc
-../twisted/test/test_ftp_options.pyc
-../twisted/test/test_hook.pyc
-../twisted/test/test_htb.pyc
-../twisted/test/test_ident.pyc
-../twisted/test/test_internet.pyc
-../twisted/test/test_iosim.pyc
-../twisted/test/test_iutils.pyc
-../twisted/test/test_jelly.pyc
-../twisted/test/test_lockfile.pyc
-../twisted/test/test_log.pyc
-../twisted/test/test_logfile.pyc
-../twisted/test/test_loopback.pyc
-../twisted/test/test_manhole.pyc
-../twisted/test/test_memcache.pyc
-../twisted/test/test_modules.pyc
-../twisted/test/test_monkey.pyc
-../twisted/test/test_newcred.pyc
-../twisted/test/test_nmea.pyc
-../twisted/test/test_paths.pyc
-../twisted/test/test_pb.pyc
-../twisted/test/test_pbfailure.pyc
-../twisted/test/test_pcp.pyc
-../twisted/test/test_persisted.pyc
-../twisted/test/test_plugin.pyc
-../twisted/test/test_policies.pyc
-../twisted/test/test_postfix.pyc
-../twisted/test/test_process.pyc
-../twisted/test/test_protocols.pyc
-../twisted/test/test_randbytes.pyc
-../twisted/test/test_rebuild.pyc
-../twisted/test/test_reflect.pyc
-../twisted/test/test_roots.pyc
-../twisted/test/test_setup.pyc
-../twisted/test/test_shortcut.pyc
-../twisted/test/test_sip.pyc
-../twisted/test/test_sob.pyc
-../twisted/test/test_socks.pyc
-../twisted/test/test_ssl.pyc
-../twisted/test/test_sslverify.pyc
-../twisted/test/test_stateful.pyc
-../twisted/test/test_stdio.pyc
-../twisted/test/test_strcred.pyc
-../twisted/test/test_strerror.pyc
-../twisted/test/test_stringtransport.pyc
-../twisted/test/test_strports.pyc
-../twisted/test/test_task.pyc
-../twisted/test/test_tcp.pyc
-../twisted/test/test_tcp_internals.pyc
-../twisted/test/test_text.pyc
-../twisted/test/test_threadable.pyc
-../twisted/test/test_threadpool.pyc
-../twisted/test/test_threads.pyc
-../twisted/test/test_tpfile.pyc
-../twisted/test/test_twistd.pyc
-../twisted/test/test_twisted.pyc
-../twisted/test/test_udp.pyc
-../twisted/test/test_unix.pyc
-../twisted/test/test_usage.pyc
-../twisted/test/testutils.pyc
-../twisted/trial/__init__.pyc
-../twisted/trial/_asyncrunner.pyc
-../twisted/trial/_asynctest.pyc
-../twisted/trial/_synctest.pyc
-../twisted/trial/itrial.pyc
-../twisted/trial/reporter.pyc
-../twisted/trial/runner.pyc
-../twisted/trial/unittest.pyc
-../twisted/trial/util.pyc
-../twisted/trial/_dist/__init__.pyc
-../twisted/trial/_dist/distreporter.pyc
-../twisted/trial/_dist/disttrial.pyc
-../twisted/trial/_dist/managercommands.pyc
-../twisted/trial/_dist/options.pyc
-../twisted/trial/_dist/worker.pyc
-../twisted/trial/_dist/workercommands.pyc
-../twisted/trial/_dist/workerreporter.pyc
-../twisted/trial/_dist/workertrial.pyc
-../twisted/trial/_dist/test/__init__.pyc
-../twisted/trial/_dist/test/test_distreporter.pyc
-../twisted/trial/_dist/test/test_disttrial.pyc
-../twisted/trial/_dist/test/test_options.pyc
-../twisted/trial/_dist/test/test_worker.pyc
-../twisted/trial/_dist/test/test_workerreporter.pyc
-../twisted/trial/_dist/test/test_workertrial.pyc
-../twisted/trial/test/__init__.pyc
-../twisted/trial/test/detests.pyc
-../twisted/trial/test/erroneous.pyc
-../twisted/trial/test/mockcustomsuite.pyc
-../twisted/trial/test/mockcustomsuite2.pyc
-../twisted/trial/test/mockcustomsuite3.pyc
-../twisted/trial/test/mockdoctest.pyc
-../twisted/trial/test/moduleself.pyc
-../twisted/trial/test/moduletest.pyc
-../twisted/trial/test/novars.pyc
-../twisted/trial/test/ordertests.pyc
-../twisted/trial/test/packages.pyc
-../twisted/trial/test/sample.pyc
-../twisted/trial/test/scripttest.pyc
-../twisted/trial/test/skipping.pyc
-../twisted/trial/test/suppression.pyc
-../twisted/trial/test/test_assertions.pyc
-../twisted/trial/test/test_asyncassertions.pyc
-../twisted/trial/test/test_deferred.pyc
-../twisted/trial/test/test_doctest.pyc
-../twisted/trial/test/test_keyboard.pyc
-../twisted/trial/test/test_loader.pyc
-../twisted/trial/test/test_log.pyc
-../twisted/trial/test/test_output.pyc
-../twisted/trial/test/test_plugins.pyc
-../twisted/trial/test/test_pyunitcompat.pyc
-../twisted/trial/test/test_reporter.pyc
-../twisted/trial/test/test_runner.pyc
-../twisted/trial/test/test_script.pyc
-../twisted/trial/test/test_suppression.pyc
-../twisted/trial/test/test_testcase.pyc
-../twisted/trial/test/test_tests.pyc
-../twisted/trial/test/test_util.pyc
-../twisted/trial/test/test_warning.pyc
-../twisted/trial/test/weird.pyc
-../twisted/web/__init__.pyc
-../twisted/web/_element.pyc
-../twisted/web/_flatten.pyc
-../twisted/web/_newclient.pyc
-../twisted/web/_responses.pyc
-../twisted/web/_stan.pyc
-../twisted/web/_version.pyc
-../twisted/web/client.pyc
-../twisted/web/demo.pyc
-../twisted/web/distrib.pyc
-../twisted/web/domhelpers.pyc
-../twisted/web/error.pyc
-../twisted/web/guard.pyc
-../twisted/web/html.pyc
-../twisted/web/http.pyc
-../twisted/web/http_headers.pyc
-../twisted/web/iweb.pyc
-../twisted/web/microdom.pyc
-../twisted/web/proxy.pyc
-../twisted/web/resource.pyc
-../twisted/web/rewrite.pyc
-../twisted/web/script.pyc
-../twisted/web/server.pyc
-../twisted/web/soap.pyc
-../twisted/web/static.pyc
-../twisted/web/sux.pyc
-../twisted/web/tap.pyc
-../twisted/web/template.pyc
-../twisted/web/twcgi.pyc
-../twisted/web/util.pyc
-../twisted/web/vhost.pyc
-../twisted/web/wsgi.pyc
-../twisted/web/xmlrpc.pyc
-../twisted/web/_auth/__init__.pyc
-../twisted/web/_auth/basic.pyc
-../twisted/web/_auth/digest.pyc
-../twisted/web/_auth/wrapper.pyc
-../twisted/web/test/__init__.pyc
-../twisted/web/test/_util.pyc
-../twisted/web/test/requesthelper.pyc
-../twisted/web/test/test_agent.pyc
-../twisted/web/test/test_cgi.pyc
-../twisted/web/test/test_distrib.pyc
-../twisted/web/test/test_domhelpers.pyc
-../twisted/web/test/test_error.pyc
-../twisted/web/test/test_flatten.pyc
-../twisted/web/test/test_http.pyc
-../twisted/web/test/test_http_headers.pyc
-../twisted/web/test/test_httpauth.pyc
-../twisted/web/test/test_newclient.pyc
-../twisted/web/test/test_proxy.pyc
-../twisted/web/test/test_resource.pyc
-../twisted/web/test/test_script.pyc
-../twisted/web/test/test_soap.pyc
-../twisted/web/test/test_stan.pyc
-../twisted/web/test/test_static.pyc
-../twisted/web/test/test_tap.pyc
-../twisted/web/test/test_template.pyc
-../twisted/web/test/test_util.pyc
-../twisted/web/test/test_vhost.pyc
-../twisted/web/test/test_web.pyc
-../twisted/web/test/test_webclient.pyc
-../twisted/web/test/test_wsgi.pyc
-../twisted/web/test/test_xml.pyc
-../twisted/web/test/test_xmlrpc.pyc
-../twisted/words/__init__.pyc
-../twisted/words/_version.pyc
-../twisted/words/ewords.pyc
-../twisted/words/iwords.pyc
-../twisted/words/service.pyc
-../twisted/words/tap.pyc
-../twisted/words/xmpproutertap.pyc
-../twisted/words/im/__init__.pyc
-../twisted/words/im/baseaccount.pyc
-../twisted/words/im/basechat.pyc
-../twisted/words/im/basesupport.pyc
-../twisted/words/im/interfaces.pyc
-../twisted/words/im/ircsupport.pyc
-../twisted/words/im/locals.pyc
-../twisted/words/im/pbsupport.pyc
-../twisted/words/protocols/__init__.pyc
-../twisted/words/protocols/irc.pyc
-../twisted/words/protocols/msn.pyc
-../twisted/words/protocols/oscar.pyc
-../twisted/words/protocols/jabber/__init__.pyc
-../twisted/words/protocols/jabber/client.pyc
-../twisted/words/protocols/jabber/component.pyc
-../twisted/words/protocols/jabber/error.pyc
-../twisted/words/protocols/jabber/ijabber.pyc
-../twisted/words/protocols/jabber/jid.pyc
-../twisted/words/protocols/jabber/jstrports.pyc
-../twisted/words/protocols/jabber/sasl.pyc
-../twisted/words/protocols/jabber/sasl_mechanisms.pyc
-../twisted/words/protocols/jabber/xmlstream.pyc
-../twisted/words/protocols/jabber/xmpp_stringprep.pyc
-../twisted/words/test/__init__.pyc
-../twisted/words/test/test_basechat.pyc
-../twisted/words/test/test_basesupport.pyc
-../twisted/words/test/test_domish.pyc
-../twisted/words/test/test_irc.pyc
-../twisted/words/test/test_irc_service.pyc
-../twisted/words/test/test_ircsupport.pyc
-../twisted/words/test/test_jabberclient.pyc
-../twisted/words/test/test_jabbercomponent.pyc
-../twisted/words/test/test_jabbererror.pyc
-../twisted/words/test/test_jabberjid.pyc
-../twisted/words/test/test_jabberjstrports.pyc
-../twisted/words/test/test_jabbersasl.pyc
-../twisted/words/test/test_jabbersaslmechanisms.pyc
-../twisted/words/test/test_jabberxmlstream.pyc
-../twisted/words/test/test_jabberxmppstringprep.pyc
-../twisted/words/test/test_msn.pyc
-../twisted/words/test/test_oscar.pyc
-../twisted/words/test/test_service.pyc
-../twisted/words/test/test_tap.pyc
-../twisted/words/test/test_xishutil.pyc
-../twisted/words/test/test_xmlstream.pyc
-../twisted/words/test/test_xmpproutertap.pyc
-../twisted/words/test/test_xpath.pyc
-../twisted/words/xish/__init__.pyc
-../twisted/words/xish/domish.pyc
-../twisted/words/xish/utility.pyc
-../twisted/words/xish/xmlstream.pyc
-../twisted/words/xish/xpath.pyc
-../twisted/words/xish/xpathparser.pyc
-../twisted/runner/portmap.so
-../twisted/test/raiser.so
-../twisted/python/sendmsg.so
-../twisted/conch/topfiles/NEWS
-../twisted/conch/topfiles/README
-../twisted/internet/iocpreactor/build.bat
-../twisted/internet/iocpreactor/notes.txt
-../twisted/internet/iocpreactor/iocpsupport/acceptex.pxi
-../twisted/internet/iocpreactor/iocpsupport/connectex.pxi
-../twisted/internet/iocpreactor/iocpsupport/iocpsupport.c
-../twisted/internet/iocpreactor/iocpsupport/iocpsupport.pyx
-../twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c
-../twisted/internet/iocpreactor/iocpsupport/winsock_pointers.h
-../twisted/internet/iocpreactor/iocpsupport/wsarecv.pxi
-../twisted/internet/iocpreactor/iocpsupport/wsasend.pxi
-../twisted/internet/test/fake_CAs/chain.pem
-../twisted/internet/test/fake_CAs/not-a-certificate
-../twisted/internet/test/fake_CAs/thing1.pem
-../twisted/internet/test/fake_CAs/thing2-duplicate.pem
-../twisted/internet/test/fake_CAs/thing2.pem
-../twisted/lore/template.mgp
-../twisted/lore/xhtml-lat1.ent
-../twisted/lore/xhtml-special.ent
-../twisted/lore/xhtml-symbol.ent
-../twisted/lore/xhtml1-strict.dtd
-../twisted/lore/xhtml1-transitional.dtd
-../twisted/lore/test/lore_index_file_out.html
-../twisted/lore/test/lore_index_file_out_multiple.html
-../twisted/lore/test/lore_index_file_unnumbered_out.html
-../twisted/lore/test/lore_index_test.xhtml
-../twisted/lore/test/lore_index_test2.xhtml
-../twisted/lore/test/lore_numbering_test_out.html
-../twisted/lore/test/lore_numbering_test_out2.html
-../twisted/lore/test/simple.html
-../twisted/lore/test/simple3.html
-../twisted/lore/test/simple4.html
-../twisted/lore/test/template.tpl
-../twisted/lore/topfiles/NEWS
-../twisted/lore/topfiles/README
-../twisted/mail/test/rfc822.message
-../twisted/mail/test/server.pem
-../twisted/mail/topfiles/NEWS
-../twisted/mail/topfiles/README
-../twisted/manhole/gladereactor.glade
-../twisted/manhole/inspectro.glade
-../twisted/manhole/logview.glade
-../twisted/manhole/ui/gtk2manhole.glade
-../twisted/names/topfiles/NEWS
-../twisted/names/topfiles/README
-../twisted/news/topfiles/NEWS
-../twisted/news/topfiles/README
-../twisted/pair/topfiles/NEWS
-../twisted/pair/topfiles/README
-../twisted/python/_initgroups.c
-../twisted/python/sendmsg.c
-../twisted/python/twisted-completion.zsh
-../twisted/python/zsh/_cftp
-../twisted/python/zsh/_ckeygen
-../twisted/python/zsh/_conch
-../twisted/python/zsh/_lore
-../twisted/python/zsh/_manhole
-../twisted/python/zsh/_mktap
-../twisted/python/zsh/_pyhtmlizer
-../twisted/python/zsh/_tap2deb
-../twisted/python/zsh/_tap2rpm
-../twisted/python/zsh/_tapconvert
-../twisted/python/zsh/_tkconch
-../twisted/python/zsh/_tkmktap
-../twisted/python/zsh/_trial
-../twisted/python/zsh/_twistd
-../twisted/python/zsh/_websetroot
-../twisted/python/zsh/README.txt
-../twisted/runner/portmap.c
-../twisted/runner/topfiles/NEWS
-../twisted/runner/topfiles/README
-../twisted/spread/ui/login2.glade
-../twisted/test/raiser.c
-../twisted/test/raiser.pyx
-../twisted/test/server.pem
-../twisted/topfiles/ChangeLog.Old
-../twisted/topfiles/CREDITS
-../twisted/topfiles/NEWS
-../twisted/topfiles/README
-../twisted/web/failure.xhtml
-../twisted/web/topfiles/NEWS
-../twisted/web/topfiles/README
-../twisted/words/im/instancemessenger.glade
-../twisted/words/topfiles/NEWS
-../twisted/words/topfiles/README
-../twisted/words/xish/xpathparser.g
-./
-dependency_links.txt
-not-zip-safe
-PKG-INFO
-requires.txt
-SOURCES.txt
-top_level.txt
-../../../../bin/cftp
-../../../../bin/ckeygen
-../../../../bin/conch
-../../../../bin/lore
-../../../../bin/mailmail
-../../../../bin/manhole
-../../../../bin/pyhtmlizer
-../../../../bin/tap2deb
-../../../../bin/tap2rpm
-../../../../bin/tapconvert
-../../../../bin/tkconch
-../../../../bin/trial
-../../../../bin/twistd
diff --git a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/requires.txt b/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/requires.txt
deleted file mode 100644
index fcdfa93..0000000
--- a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/requires.txt
+++ /dev/null
@@ -1 +0,0 @@
-zope.interface >= 3.6.0
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/top_level.txt
deleted file mode 100644
index 3eb29f0..0000000
--- a/Darwin/lib/python2.7/site-packages/Twisted-14.0.0-py2.7.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-twisted
diff --git a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/PKG-INFO b/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/PKG-INFO
deleted file mode 100644
index a4d99cb..0000000
--- a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/PKG-INFO
+++ /dev/null
@@ -1,72 +0,0 @@
-Metadata-Version: 1.1
-Name: Werkzeug
-Version: 0.9.4
-Summary: The Swiss Army knife of Python web development
-Home-page: http://werkzeug.pocoo.org/
-Author: Armin Ronacher
-Author-email: armin.ronacher@active-4.com
-License: BSD
-Description:
- Werkzeug
- ========
-
- Werkzeug started as simple collection of various utilities for WSGI
- applications and has become one of the most advanced WSGI utility
- modules. It includes a powerful debugger, full featured request and
- response objects, HTTP utilities to handle entity tags, cache control
- headers, HTTP dates, cookie handling, file uploads, a powerful URL
- routing system and a bunch of community contributed addon modules.
-
- Werkzeug is unicode aware and doesn't enforce a specific template
- engine, database adapter or anything else. It doesn't even enforce
- a specific way of handling requests and leaves all that up to the
- developer. It's most useful for end user applications which should work
- on as many server environments as possible (such as blogs, wikis,
- bulletin boards, etc.).
-
- Details and example applications are available on the
- `Werkzeug website `_.
-
-
- Features
- --------
-
- - unicode awareness
-
- - request and response objects
-
- - various utility functions for dealing with HTTP headers such as
- `Accept` and `Cache-Control` headers.
-
- - thread local objects with proper cleanup at request end
-
- - an interactive debugger
-
- - A simple WSGI server with support for threading and forking
- with an automatic reloader.
-
- - a flexible URL routing system with REST support.
-
- - fully WSGI compatible
-
-
- Development Version
- -------------------
-
- The Werkzeug development version can be installed by cloning the git
- repository from `github`_::
-
- git clone git@github.com:mitsuhiko/werkzeug.git
-
- .. _github: http://github.com/mitsuhiko/werkzeug
-
-Platform: any
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Environment :: Web Environment
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Operating System :: OS Independent
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 3
-Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
-Classifier: Topic :: Software Development :: Libraries :: Python Modules
diff --git a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/SOURCES.txt
deleted file mode 100644
index be54ff7..0000000
--- a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,289 +0,0 @@
-AUTHORS
-CHANGES
-LICENSE
-MANIFEST.in
-Makefile
-setup.cfg
-setup.py
-Werkzeug.egg-info/PKG-INFO
-Werkzeug.egg-info/SOURCES.txt
-Werkzeug.egg-info/dependency_links.txt
-Werkzeug.egg-info/not-zip-safe
-Werkzeug.egg-info/top_level.txt
-artwork/logo.png
-artwork/logo.svg
-docs/Makefile
-docs/changes.rst
-docs/conf.py
-docs/contents.rst.inc
-docs/datastructures.rst
-docs/debug.rst
-docs/exceptions.rst
-docs/http.rst
-docs/index.rst
-docs/installation.rst
-docs/latexindex.rst
-docs/levels.rst
-docs/local.rst
-docs/logo.pdf
-docs/make.bat
-docs/makearchive.py
-docs/middlewares.rst
-docs/python3.rst
-docs/quickstart.rst
-docs/request_data.rst
-docs/routing.rst
-docs/serving.rst
-docs/terms.rst
-docs/test.rst
-docs/transition.rst
-docs/tutorial.rst
-docs/unicode.rst
-docs/utils.rst
-docs/werkzeugext.py
-docs/werkzeugstyle.sty
-docs/wrappers.rst
-docs/wsgi.rst
-docs/_static/background.png
-docs/_static/codebackground.png
-docs/_static/contents.png
-docs/_static/debug-screenshot.png
-docs/_static/favicon.ico
-docs/_static/header.png
-docs/_static/navigation.png
-docs/_static/navigation_active.png
-docs/_static/shortly.png
-docs/_static/shorty-screenshot.png
-docs/_static/style.css
-docs/_static/werkzeug.js
-docs/_static/werkzeug.png
-docs/_templates/sidebarintro.html
-docs/_templates/sidebarlogo.html
-docs/_themes/LICENSE
-docs/_themes/README
-docs/_themes/werkzeug_theme_support.py
-docs/_themes/werkzeug/layout.html
-docs/_themes/werkzeug/relations.html
-docs/_themes/werkzeug/theme.conf
-docs/_themes/werkzeug/static/werkzeug.css_t
-docs/contrib/atom.rst
-docs/contrib/cache.rst
-docs/contrib/fixers.rst
-docs/contrib/index.rst
-docs/contrib/iterio.rst
-docs/contrib/lint.rst
-docs/contrib/profiler.rst
-docs/contrib/securecookie.rst
-docs/contrib/sessions.rst
-docs/contrib/wrappers.rst
-docs/deployment/cgi.rst
-docs/deployment/fastcgi.rst
-docs/deployment/index.rst
-docs/deployment/mod_wsgi.rst
-docs/deployment/proxying.rst
-examples/README
-examples/cookieauth.py
-examples/httpbasicauth.py
-examples/manage-coolmagic.py
-examples/manage-couchy.py
-examples/manage-cupoftee.py
-examples/manage-i18nurls.py
-examples/manage-plnt.py
-examples/manage-shorty.py
-examples/manage-simplewiki.py
-examples/manage-webpylike.py
-examples/upload.py
-examples/contrib/README
-examples/contrib/securecookie.py
-examples/contrib/sessions.py
-examples/coolmagic/__init__.py
-examples/coolmagic/application.py
-examples/coolmagic/helpers.py
-examples/coolmagic/utils.py
-examples/coolmagic/public/style.css
-examples/coolmagic/templates/layout.html
-examples/coolmagic/templates/static/about.html
-examples/coolmagic/templates/static/index.html
-examples/coolmagic/templates/static/not_found.html
-examples/coolmagic/views/__init__.py
-examples/coolmagic/views/static.py
-examples/couchy/README
-examples/couchy/__init__.py
-examples/couchy/application.py
-examples/couchy/models.py
-examples/couchy/utils.py
-examples/couchy/views.py
-examples/couchy/static/style.css
-examples/couchy/templates/display.html
-examples/couchy/templates/layout.html
-examples/couchy/templates/list.html
-examples/couchy/templates/new.html
-examples/couchy/templates/not_found.html
-examples/cupoftee/__init__.py
-examples/cupoftee/application.py
-examples/cupoftee/db.py
-examples/cupoftee/network.py
-examples/cupoftee/pages.py
-examples/cupoftee/utils.py
-examples/cupoftee/shared/content.png
-examples/cupoftee/shared/down.png
-examples/cupoftee/shared/favicon.ico
-examples/cupoftee/shared/header.png
-examples/cupoftee/shared/logo.png
-examples/cupoftee/shared/style.css
-examples/cupoftee/shared/up.png
-examples/cupoftee/templates/layout.html
-examples/cupoftee/templates/missingpage.html
-examples/cupoftee/templates/search.html
-examples/cupoftee/templates/server.html
-examples/cupoftee/templates/serverlist.html
-examples/i18nurls/__init__.py
-examples/i18nurls/application.py
-examples/i18nurls/urls.py
-examples/i18nurls/views.py
-examples/i18nurls/templates/about.html
-examples/i18nurls/templates/blog.html
-examples/i18nurls/templates/index.html
-examples/i18nurls/templates/layout.html
-examples/partial/README
-examples/partial/complex_routing.py
-examples/plnt/__init__.py
-examples/plnt/database.py
-examples/plnt/sync.py
-examples/plnt/utils.py
-examples/plnt/views.py
-examples/plnt/webapp.py
-examples/plnt/shared/style.css
-examples/plnt/templates/about.html
-examples/plnt/templates/index.html
-examples/plnt/templates/layout.html
-examples/shortly/shortly.py
-examples/shortly/static/style.css
-examples/shortly/templates/404.html
-examples/shortly/templates/layout.html
-examples/shortly/templates/new_url.html
-examples/shortly/templates/short_link_details.html
-examples/shorty/__init__.py
-examples/shorty/application.py
-examples/shorty/models.py
-examples/shorty/utils.py
-examples/shorty/views.py
-examples/shorty/static/style.css
-examples/shorty/templates/display.html
-examples/shorty/templates/layout.html
-examples/shorty/templates/list.html
-examples/shorty/templates/new.html
-examples/shorty/templates/not_found.html
-examples/simplewiki/__init__.py
-examples/simplewiki/actions.py
-examples/simplewiki/application.py
-examples/simplewiki/database.py
-examples/simplewiki/specialpages.py
-examples/simplewiki/utils.py
-examples/simplewiki/shared/style.css
-examples/simplewiki/templates/action_diff.html
-examples/simplewiki/templates/action_edit.html
-examples/simplewiki/templates/action_log.html
-examples/simplewiki/templates/action_revert.html
-examples/simplewiki/templates/action_show.html
-examples/simplewiki/templates/layout.html
-examples/simplewiki/templates/macros.xml
-examples/simplewiki/templates/missing_action.html
-examples/simplewiki/templates/page_index.html
-examples/simplewiki/templates/page_missing.html
-examples/simplewiki/templates/recent_changes.html
-examples/webpylike/example.py
-examples/webpylike/webpylike.py
-werkzeug/__init__.py
-werkzeug/_compat.py
-werkzeug/_internal.py
-werkzeug/datastructures.py
-werkzeug/exceptions.py
-werkzeug/formparser.py
-werkzeug/http.py
-werkzeug/local.py
-werkzeug/posixemulation.py
-werkzeug/routing.py
-werkzeug/script.py
-werkzeug/security.py
-werkzeug/serving.py
-werkzeug/test.py
-werkzeug/testapp.py
-werkzeug/urls.py
-werkzeug/useragents.py
-werkzeug/utils.py
-werkzeug/wrappers.py
-werkzeug/wsgi.py
-werkzeug/contrib/__init__.py
-werkzeug/contrib/atom.py
-werkzeug/contrib/cache.py
-werkzeug/contrib/fixers.py
-werkzeug/contrib/iterio.py
-werkzeug/contrib/jsrouting.py
-werkzeug/contrib/limiter.py
-werkzeug/contrib/lint.py
-werkzeug/contrib/profiler.py
-werkzeug/contrib/securecookie.py
-werkzeug/contrib/sessions.py
-werkzeug/contrib/testtools.py
-werkzeug/contrib/wrappers.py
-werkzeug/debug/__init__.py
-werkzeug/debug/console.py
-werkzeug/debug/repr.py
-werkzeug/debug/tbtools.py
-werkzeug/debug/shared/FONT_LICENSE
-werkzeug/debug/shared/console.png
-werkzeug/debug/shared/debugger.js
-werkzeug/debug/shared/jquery.js
-werkzeug/debug/shared/less.png
-werkzeug/debug/shared/more.png
-werkzeug/debug/shared/source.png
-werkzeug/debug/shared/style.css
-werkzeug/debug/shared/ubuntu.ttf
-werkzeug/testsuite/__init__.py
-werkzeug/testsuite/compat.py
-werkzeug/testsuite/datastructures.py
-werkzeug/testsuite/debug.py
-werkzeug/testsuite/exceptions.py
-werkzeug/testsuite/formparser.py
-werkzeug/testsuite/http.py
-werkzeug/testsuite/internal.py
-werkzeug/testsuite/local.py
-werkzeug/testsuite/routing.py
-werkzeug/testsuite/security.py
-werkzeug/testsuite/serving.py
-werkzeug/testsuite/test.py
-werkzeug/testsuite/urls.py
-werkzeug/testsuite/utils.py
-werkzeug/testsuite/wrappers.py
-werkzeug/testsuite/wsgi.py
-werkzeug/testsuite/contrib/__init__.py
-werkzeug/testsuite/contrib/cache.py
-werkzeug/testsuite/contrib/fixers.py
-werkzeug/testsuite/contrib/iterio.py
-werkzeug/testsuite/contrib/securecookie.py
-werkzeug/testsuite/contrib/sessions.py
-werkzeug/testsuite/contrib/wrappers.py
-werkzeug/testsuite/multipart/collect.py
-werkzeug/testsuite/multipart/ie7_full_path_request.txt
-werkzeug/testsuite/multipart/firefox3-2png1txt/file1.png
-werkzeug/testsuite/multipart/firefox3-2png1txt/file2.png
-werkzeug/testsuite/multipart/firefox3-2png1txt/request.txt
-werkzeug/testsuite/multipart/firefox3-2png1txt/text.txt
-werkzeug/testsuite/multipart/firefox3-2pnglongtext/file1.png
-werkzeug/testsuite/multipart/firefox3-2pnglongtext/file2.png
-werkzeug/testsuite/multipart/firefox3-2pnglongtext/request.txt
-werkzeug/testsuite/multipart/firefox3-2pnglongtext/text.txt
-werkzeug/testsuite/multipart/ie6-2png1txt/file1.png
-werkzeug/testsuite/multipart/ie6-2png1txt/file2.png
-werkzeug/testsuite/multipart/ie6-2png1txt/request.txt
-werkzeug/testsuite/multipart/ie6-2png1txt/text.txt
-werkzeug/testsuite/multipart/opera8-2png1txt/file1.png
-werkzeug/testsuite/multipart/opera8-2png1txt/file2.png
-werkzeug/testsuite/multipart/opera8-2png1txt/request.txt
-werkzeug/testsuite/multipart/opera8-2png1txt/text.txt
-werkzeug/testsuite/multipart/webkit3-2png1txt/file1.png
-werkzeug/testsuite/multipart/webkit3-2png1txt/file2.png
-werkzeug/testsuite/multipart/webkit3-2png1txt/request.txt
-werkzeug/testsuite/multipart/webkit3-2png1txt/text.txt
-werkzeug/testsuite/res/test.txt
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/installed-files.txt
deleted file mode 100644
index 6810861..0000000
--- a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/installed-files.txt
+++ /dev/null
@@ -1,161 +0,0 @@
-../werkzeug/__init__.py
-../werkzeug/_compat.py
-../werkzeug/_internal.py
-../werkzeug/datastructures.py
-../werkzeug/exceptions.py
-../werkzeug/formparser.py
-../werkzeug/http.py
-../werkzeug/local.py
-../werkzeug/posixemulation.py
-../werkzeug/routing.py
-../werkzeug/script.py
-../werkzeug/security.py
-../werkzeug/serving.py
-../werkzeug/test.py
-../werkzeug/testapp.py
-../werkzeug/urls.py
-../werkzeug/useragents.py
-../werkzeug/utils.py
-../werkzeug/wrappers.py
-../werkzeug/wsgi.py
-../werkzeug/debug/__init__.py
-../werkzeug/debug/console.py
-../werkzeug/debug/repr.py
-../werkzeug/debug/tbtools.py
-../werkzeug/contrib/__init__.py
-../werkzeug/contrib/atom.py
-../werkzeug/contrib/cache.py
-../werkzeug/contrib/fixers.py
-../werkzeug/contrib/iterio.py
-../werkzeug/contrib/jsrouting.py
-../werkzeug/contrib/limiter.py
-../werkzeug/contrib/lint.py
-../werkzeug/contrib/profiler.py
-../werkzeug/contrib/securecookie.py
-../werkzeug/contrib/sessions.py
-../werkzeug/contrib/testtools.py
-../werkzeug/contrib/wrappers.py
-../werkzeug/testsuite/__init__.py
-../werkzeug/testsuite/compat.py
-../werkzeug/testsuite/datastructures.py
-../werkzeug/testsuite/debug.py
-../werkzeug/testsuite/exceptions.py
-../werkzeug/testsuite/formparser.py
-../werkzeug/testsuite/http.py
-../werkzeug/testsuite/internal.py
-../werkzeug/testsuite/local.py
-../werkzeug/testsuite/routing.py
-../werkzeug/testsuite/security.py
-../werkzeug/testsuite/serving.py
-../werkzeug/testsuite/test.py
-../werkzeug/testsuite/urls.py
-../werkzeug/testsuite/utils.py
-../werkzeug/testsuite/wrappers.py
-../werkzeug/testsuite/wsgi.py
-../werkzeug/testsuite/contrib/__init__.py
-../werkzeug/testsuite/contrib/cache.py
-../werkzeug/testsuite/contrib/fixers.py
-../werkzeug/testsuite/contrib/iterio.py
-../werkzeug/testsuite/contrib/securecookie.py
-../werkzeug/testsuite/contrib/sessions.py
-../werkzeug/testsuite/contrib/wrappers.py
-../werkzeug/debug/shared/FONT_LICENSE
-../werkzeug/debug/shared/console.png
-../werkzeug/debug/shared/debugger.js
-../werkzeug/debug/shared/jquery.js
-../werkzeug/debug/shared/less.png
-../werkzeug/debug/shared/more.png
-../werkzeug/debug/shared/source.png
-../werkzeug/debug/shared/style.css
-../werkzeug/debug/shared/ubuntu.ttf
-../werkzeug/testsuite/multipart/collect.py
-../werkzeug/testsuite/multipart/ie7_full_path_request.txt
-../werkzeug/testsuite/multipart/firefox3-2png1txt/file1.png
-../werkzeug/testsuite/multipart/firefox3-2png1txt/file2.png
-../werkzeug/testsuite/multipart/firefox3-2png1txt/request.txt
-../werkzeug/testsuite/multipart/firefox3-2png1txt/text.txt
-../werkzeug/testsuite/multipart/firefox3-2pnglongtext/file1.png
-../werkzeug/testsuite/multipart/firefox3-2pnglongtext/file2.png
-../werkzeug/testsuite/multipart/firefox3-2pnglongtext/request.txt
-../werkzeug/testsuite/multipart/firefox3-2pnglongtext/text.txt
-../werkzeug/testsuite/multipart/ie6-2png1txt/file1.png
-../werkzeug/testsuite/multipart/ie6-2png1txt/file2.png
-../werkzeug/testsuite/multipart/ie6-2png1txt/request.txt
-../werkzeug/testsuite/multipart/ie6-2png1txt/text.txt
-../werkzeug/testsuite/multipart/opera8-2png1txt/file1.png
-../werkzeug/testsuite/multipart/opera8-2png1txt/file2.png
-../werkzeug/testsuite/multipart/opera8-2png1txt/request.txt
-../werkzeug/testsuite/multipart/opera8-2png1txt/text.txt
-../werkzeug/testsuite/multipart/webkit3-2png1txt/file1.png
-../werkzeug/testsuite/multipart/webkit3-2png1txt/file2.png
-../werkzeug/testsuite/multipart/webkit3-2png1txt/request.txt
-../werkzeug/testsuite/multipart/webkit3-2png1txt/text.txt
-../werkzeug/testsuite/res/test.txt
-../werkzeug/__init__.pyc
-../werkzeug/_compat.pyc
-../werkzeug/_internal.pyc
-../werkzeug/datastructures.pyc
-../werkzeug/exceptions.pyc
-../werkzeug/formparser.pyc
-../werkzeug/http.pyc
-../werkzeug/local.pyc
-../werkzeug/posixemulation.pyc
-../werkzeug/routing.pyc
-../werkzeug/script.pyc
-../werkzeug/security.pyc
-../werkzeug/serving.pyc
-../werkzeug/test.pyc
-../werkzeug/testapp.pyc
-../werkzeug/urls.pyc
-../werkzeug/useragents.pyc
-../werkzeug/utils.pyc
-../werkzeug/wrappers.pyc
-../werkzeug/wsgi.pyc
-../werkzeug/debug/__init__.pyc
-../werkzeug/debug/console.pyc
-../werkzeug/debug/repr.pyc
-../werkzeug/debug/tbtools.pyc
-../werkzeug/contrib/__init__.pyc
-../werkzeug/contrib/atom.pyc
-../werkzeug/contrib/cache.pyc
-../werkzeug/contrib/fixers.pyc
-../werkzeug/contrib/iterio.pyc
-../werkzeug/contrib/jsrouting.pyc
-../werkzeug/contrib/limiter.pyc
-../werkzeug/contrib/lint.pyc
-../werkzeug/contrib/profiler.pyc
-../werkzeug/contrib/securecookie.pyc
-../werkzeug/contrib/sessions.pyc
-../werkzeug/contrib/testtools.pyc
-../werkzeug/contrib/wrappers.pyc
-../werkzeug/testsuite/__init__.pyc
-../werkzeug/testsuite/compat.pyc
-../werkzeug/testsuite/datastructures.pyc
-../werkzeug/testsuite/debug.pyc
-../werkzeug/testsuite/exceptions.pyc
-../werkzeug/testsuite/formparser.pyc
-../werkzeug/testsuite/http.pyc
-../werkzeug/testsuite/internal.pyc
-../werkzeug/testsuite/local.pyc
-../werkzeug/testsuite/routing.pyc
-../werkzeug/testsuite/security.pyc
-../werkzeug/testsuite/serving.pyc
-../werkzeug/testsuite/test.pyc
-../werkzeug/testsuite/urls.pyc
-../werkzeug/testsuite/utils.pyc
-../werkzeug/testsuite/wrappers.pyc
-../werkzeug/testsuite/wsgi.pyc
-../werkzeug/testsuite/contrib/__init__.pyc
-../werkzeug/testsuite/contrib/cache.pyc
-../werkzeug/testsuite/contrib/fixers.pyc
-../werkzeug/testsuite/contrib/iterio.pyc
-../werkzeug/testsuite/contrib/securecookie.pyc
-../werkzeug/testsuite/contrib/sessions.pyc
-../werkzeug/testsuite/contrib/wrappers.pyc
-../werkzeug/testsuite/multipart/collect.pyc
-./
-dependency_links.txt
-not-zip-safe
-PKG-INFO
-SOURCES.txt
-top_level.txt
diff --git a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/top_level.txt
deleted file mode 100644
index 6fe8da8..0000000
--- a/Darwin/lib/python2.7/site-packages/Werkzeug-0.9.4-py2.7.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-werkzeug
diff --git a/Darwin/lib/python2.7/site-packages/_cffi_backend.so b/Darwin/lib/python2.7/site-packages/_cffi_backend.so
index d259391..20dbf17 100755
Binary files a/Darwin/lib/python2.7/site-packages/_cffi_backend.so and b/Darwin/lib/python2.7/site-packages/_cffi_backend.so differ
diff --git a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/PKG-INFO b/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/PKG-INFO
deleted file mode 100644
index 3e0ec60..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/PKG-INFO
+++ /dev/null
@@ -1,96 +0,0 @@
-Metadata-Version: 1.1
-Name: alembic
-Version: 0.6.5
-Summary: A database migration tool for SQLAlchemy.
-Home-page: http://bitbucket.org/zzzeek/alembic
-Author: Mike Bayer
-Author-email: mike@zzzcomputing.com
-License: MIT
-Description: Alembic is a new database migrations tool, written by the author
- of `SQLAlchemy `_. A migrations tool
- offers the following functionality:
-
- * Can emit ALTER statements to a database in order to change
- the structure of tables and other constructs
- * Provides a system whereby "migration scripts" may be constructed;
- each script indicates a particular series of steps that can "upgrade" a
- target database to a new version, and optionally a series of steps that can
- "downgrade" similarly, doing the same steps in reverse.
- * Allows the scripts to execute in some sequential manner.
-
- The goals of Alembic are:
-
- * Very open ended and transparent configuration and operation. A new
- Alembic environment is generated from a set of templates which is selected
- among a set of options when setup first occurs. The templates then deposit a
- series of scripts that define fully how database connectivity is established
- and how migration scripts are invoked; the migration scripts themselves are
- generated from a template within that series of scripts. The scripts can
- then be further customized to define exactly how databases will be
- interacted with and what structure new migration files should take.
- * Full support for transactional DDL. The default scripts ensure that all
- migrations occur within a transaction - for those databases which support
- this (Postgresql, Microsoft SQL Server), migrations can be tested with no
- need to manually undo changes upon failure.
- * Minimalist script construction. Basic operations like renaming
- tables/columns, adding/removing columns, changing column attributes can be
- performed through one line commands like alter_column(), rename_table(),
- add_constraint(). There is no need to recreate full SQLAlchemy Table
- structures for simple operations like these - the functions themselves
- generate minimalist schema structures behind the scenes to achieve the given
- DDL sequence.
- * "auto generation" of migrations. While real world migrations are far more
- complex than what can be automatically determined, Alembic can still
- eliminate the initial grunt work in generating new migration directives
- from an altered schema. The ``--autogenerate`` feature will inspect the
- current status of a database using SQLAlchemy's schema inspection
- capabilities, compare it to the current state of the database model as
- specified in Python, and generate a series of "candidate" migrations,
- rendering them into a new migration script as Python directives. The
- developer then edits the new file, adding additional directives and data
- migrations as needed, to produce a finished migration. Table and column
- level changes can be detected, with constraints and indexes to follow as
- well.
- * Full support for migrations generated as SQL scripts. Those of us who
- work in corporate environments know that direct access to DDL commands on a
- production database is a rare privilege, and DBAs want textual SQL scripts.
- Alembic's usage model and commands are oriented towards being able to run a
- series of migrations into a textual output file as easily as it runs them
- directly to a database. Care must be taken in this mode to not invoke other
- operations that rely upon in-memory SELECTs of rows - Alembic tries to
- provide helper constructs like bulk_insert() to help with data-oriented
- operations that are compatible with script-based DDL.
- * Non-linear versioning. Scripts are given UUID identifiers similarly
- to a DVCS, and the linkage of one script to the next is achieved via markers
- within the scripts themselves. Through this open-ended mechanism, branches
- containing other migration scripts can be merged - the linkages can be
- manually edited within the script files to create the new sequence.
- * Provide a library of ALTER constructs that can be used by any SQLAlchemy
- application. The DDL constructs build upon SQLAlchemy's own DDLElement base
- and can be used standalone by any application or script.
- * Don't break our necks over SQLite's inability to ALTER things. SQLite
- has almost no support for table or column alteration, and this is likely
- intentional. Alembic's design
- is kept simple by not contorting its core API around these limitations,
- understanding that SQLite is simply not intended to support schema
- changes. While Alembic's architecture can support SQLite's workarounds, and
- we will support these features provided someone takes the initiative
- to implement and test, until the SQLite developers decide
- to provide a fully working version of ALTER, it's still vastly preferable
- to use Alembic, or any migrations tool, with databases that
- are designed to work under the assumption of in-place schema migrations
- taking place.
-
- Documentation and status of Alembic is at http://readthedocs.org/docs/alembic/.
-
-
-Keywords: SQLAlchemy migrations
-Platform: UNKNOWN
-Classifier: Development Status :: 4 - Beta
-Classifier: Environment :: Console
-Classifier: Intended Audience :: Developers
-Classifier: Programming Language :: Python
-Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: Implementation :: CPython
-Classifier: Programming Language :: Python :: Implementation :: PyPy
-Classifier: Topic :: Database :: Front-Ends
diff --git a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/SOURCES.txt
deleted file mode 100644
index 19bf79b..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/SOURCES.txt
+++ /dev/null
@@ -1,123 +0,0 @@
-CHANGES
-LICENSE
-MANIFEST.in
-README.rst
-README.unittests
-setup.cfg
-setup.py
-test.cfg
-alembic/__init__.py
-alembic/command.py
-alembic/compat.py
-alembic/config.py
-alembic/context.py
-alembic/environment.py
-alembic/migration.py
-alembic/op.py
-alembic/operations.py
-alembic/script.py
-alembic/util.py
-alembic.egg-info/PKG-INFO
-alembic.egg-info/SOURCES.txt
-alembic.egg-info/dependency_links.txt
-alembic.egg-info/entry_points.txt
-alembic.egg-info/not-zip-safe
-alembic.egg-info/requires.txt
-alembic.egg-info/top_level.txt
-alembic/autogenerate/__init__.py
-alembic/autogenerate/api.py
-alembic/autogenerate/compare.py
-alembic/autogenerate/render.py
-alembic/ddl/__init__.py
-alembic/ddl/base.py
-alembic/ddl/impl.py
-alembic/ddl/mssql.py
-alembic/ddl/mysql.py
-alembic/ddl/oracle.py
-alembic/ddl/postgresql.py
-alembic/ddl/sqlite.py
-alembic/templates/generic/README
-alembic/templates/generic/alembic.ini.mako
-alembic/templates/generic/env.py
-alembic/templates/generic/script.py.mako
-alembic/templates/multidb/README
-alembic/templates/multidb/alembic.ini.mako
-alembic/templates/multidb/env.py
-alembic/templates/multidb/script.py.mako
-alembic/templates/pylons/README
-alembic/templates/pylons/alembic.ini.mako
-alembic/templates/pylons/env.py
-alembic/templates/pylons/script.py.mako
-docs/api.html
-docs/changelog.html
-docs/cookbook.html
-docs/front.html
-docs/genindex.html
-docs/index.html
-docs/ops.html
-docs/py-modindex.html
-docs/search.html
-docs/searchindex.js
-docs/tutorial.html
-docs/_images/api_overview.png
-docs/_sources/api.txt
-docs/_sources/changelog.txt
-docs/_sources/cookbook.txt
-docs/_sources/front.txt
-docs/_sources/index.txt
-docs/_sources/ops.txt
-docs/_sources/tutorial.txt
-docs/_static/basic.css
-docs/_static/changelog.css
-docs/_static/comment-bright.png
-docs/_static/comment-close.png
-docs/_static/comment.png
-docs/_static/doctools.js
-docs/_static/down-pressed.png
-docs/_static/down.png
-docs/_static/file.png
-docs/_static/jquery.js
-docs/_static/minus.png
-docs/_static/nature.css
-docs/_static/nature_override.css
-docs/_static/plus.png
-docs/_static/pygments.css
-docs/_static/searchtools.js
-docs/_static/sphinx_paramlinks.css
-docs/_static/underscore.js
-docs/_static/up-pressed.png
-docs/_static/up.png
-docs/_static/websupport.js
-docs/build/Makefile
-docs/build/api.rst
-docs/build/api_overview.png
-docs/build/changelog.rst
-docs/build/conf.py
-docs/build/cookbook.rst
-docs/build/front.rst
-docs/build/index.rst
-docs/build/ops.rst
-docs/build/requirements.txt
-docs/build/tutorial.rst
-docs/build/_static/nature_override.css
-tests/__init__.py
-tests/test_autogen_indexes.py
-tests/test_autogen_render.py
-tests/test_autogenerate.py
-tests/test_bulk_insert.py
-tests/test_command.py
-tests/test_config.py
-tests/test_environment.py
-tests/test_mssql.py
-tests/test_mysql.py
-tests/test_offline_environment.py
-tests/test_op.py
-tests/test_op_naming_convention.py
-tests/test_oracle.py
-tests/test_postgresql.py
-tests/test_revision_create.py
-tests/test_revision_paths.py
-tests/test_sql_script.py
-tests/test_sqlite.py
-tests/test_version_table.py
-tests/test_versioning.py
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/entry_points.txt b/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/entry_points.txt
deleted file mode 100644
index 27ac374..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/entry_points.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-[console_scripts]
-alembic = alembic.config:main
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/installed-files.txt
deleted file mode 100644
index bab3a7d..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/installed-files.txt
+++ /dev/null
@@ -1,70 +0,0 @@
-../alembic/__init__.py
-../alembic/command.py
-../alembic/compat.py
-../alembic/config.py
-../alembic/context.py
-../alembic/environment.py
-../alembic/migration.py
-../alembic/op.py
-../alembic/operations.py
-../alembic/script.py
-../alembic/util.py
-../alembic/autogenerate/__init__.py
-../alembic/autogenerate/api.py
-../alembic/autogenerate/compare.py
-../alembic/autogenerate/render.py
-../alembic/ddl/__init__.py
-../alembic/ddl/base.py
-../alembic/ddl/impl.py
-../alembic/ddl/mssql.py
-../alembic/ddl/mysql.py
-../alembic/ddl/oracle.py
-../alembic/ddl/postgresql.py
-../alembic/ddl/sqlite.py
-../alembic/templates/generic/README
-../alembic/templates/generic/alembic.ini.mako
-../alembic/templates/generic/env.py
-../alembic/templates/generic/script.py.mako
-../alembic/templates/multidb/README
-../alembic/templates/multidb/alembic.ini.mako
-../alembic/templates/multidb/env.py
-../alembic/templates/multidb/script.py.mako
-../alembic/templates/pylons/README
-../alembic/templates/pylons/alembic.ini.mako
-../alembic/templates/pylons/env.py
-../alembic/templates/pylons/script.py.mako
-../alembic/__init__.pyc
-../alembic/command.pyc
-../alembic/compat.pyc
-../alembic/config.pyc
-../alembic/context.pyc
-../alembic/environment.pyc
-../alembic/migration.pyc
-../alembic/op.pyc
-../alembic/operations.pyc
-../alembic/script.pyc
-../alembic/util.pyc
-../alembic/autogenerate/__init__.pyc
-../alembic/autogenerate/api.pyc
-../alembic/autogenerate/compare.pyc
-../alembic/autogenerate/render.pyc
-../alembic/ddl/__init__.pyc
-../alembic/ddl/base.pyc
-../alembic/ddl/impl.pyc
-../alembic/ddl/mssql.pyc
-../alembic/ddl/mysql.pyc
-../alembic/ddl/oracle.pyc
-../alembic/ddl/postgresql.pyc
-../alembic/ddl/sqlite.pyc
-../alembic/templates/generic/env.pyc
-../alembic/templates/multidb/env.pyc
-../alembic/templates/pylons/env.pyc
-./
-dependency_links.txt
-entry_points.txt
-not-zip-safe
-PKG-INFO
-requires.txt
-SOURCES.txt
-top_level.txt
-../../../../bin/alembic
diff --git a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/requires.txt b/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/requires.txt
deleted file mode 100644
index 39a2c32..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/requires.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-SQLAlchemy>=0.7.3
-Mako
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/top_level.txt
deleted file mode 100644
index b5bd98d..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic-0.6.5-py2.7.egg-info/top_level.txt
+++ /dev/null
@@ -1 +0,0 @@
-alembic
diff --git a/Darwin/lib/python2.7/site-packages/alembic/__init__.py b/Darwin/lib/python2.7/site-packages/alembic/__init__.py
deleted file mode 100644
index 6680966..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/__init__.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from os import path
-
-__version__ = '0.6.5'
-
-package_dir = path.abspath(path.dirname(__file__))
-
-
-from . import op
-from . import context
-
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/autogenerate/__init__.py b/Darwin/lib/python2.7/site-packages/alembic/autogenerate/__init__.py
deleted file mode 100644
index d0f54ba..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/autogenerate/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from .api import compare_metadata, _produce_migration_diffs, _produce_net_changes
diff --git a/Darwin/lib/python2.7/site-packages/alembic/autogenerate/api.py b/Darwin/lib/python2.7/site-packages/alembic/autogenerate/api.py
deleted file mode 100644
index 148e352..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/autogenerate/api.py
+++ /dev/null
@@ -1,301 +0,0 @@
-"""Provide the 'autogenerate' feature which can produce migration operations
-automatically."""
-
-import logging
-import re
-
-from sqlalchemy.engine.reflection import Inspector
-from sqlalchemy.util import OrderedSet
-from .compare import _compare_tables
-from .render import _drop_table, _drop_column, _drop_index, _drop_constraint, \
- _add_table, _add_column, _add_index, _add_constraint, _modify_col
-from .. import util
-
-log = logging.getLogger(__name__)
-
-###################################################
-# public
-def compare_metadata(context, metadata):
- """Compare a database schema to that given in a
- :class:`~sqlalchemy.schema.MetaData` instance.
-
- The database connection is presented in the context
- of a :class:`.MigrationContext` object, which
- provides database connectivity as well as optional
- comparison functions to use for datatypes and
- server defaults - see the "autogenerate" arguments
- at :meth:`.EnvironmentContext.configure`
- for details on these.
-
- The return format is a list of "diff" directives,
- each representing individual differences::
-
- from alembic.migration import MigrationContext
- from alembic.autogenerate import compare_metadata
- from sqlalchemy.schema import SchemaItem
- from sqlalchemy.types import TypeEngine
- from sqlalchemy import (create_engine, MetaData, Column,
- Integer, String, Table)
- import pprint
-
- engine = create_engine("sqlite://")
-
- engine.execute('''
- create table foo (
- id integer not null primary key,
- old_data varchar,
- x integer
- )''')
-
- engine.execute('''
- create table bar (
- data varchar
- )''')
-
- metadata = MetaData()
- Table('foo', metadata,
- Column('id', Integer, primary_key=True),
- Column('data', Integer),
- Column('x', Integer, nullable=False)
- )
- Table('bat', metadata,
- Column('info', String)
- )
-
- mc = MigrationContext.configure(engine.connect())
-
- diff = compare_metadata(mc, metadata)
- pprint.pprint(diff, indent=2, width=20)
-
- Output::
-
- [ ( 'add_table',
- Table('bat', MetaData(bind=None),
- Column('info', String(), table=), schema=None)),
- ( 'remove_table',
- Table(u'bar', MetaData(bind=None),
- Column(u'data', VARCHAR(), table=), schema=None)),
- ( 'add_column',
- None,
- 'foo',
- Column('data', Integer(), table=)),
- ( 'remove_column',
- None,
- 'foo',
- Column(u'old_data', VARCHAR(), table=None)),
- [ ( 'modify_nullable',
- None,
- 'foo',
- u'x',
- { 'existing_server_default': None,
- 'existing_type': INTEGER()},
- True,
- False)]]
-
-
- :param context: a :class:`.MigrationContext`
- instance.
- :param metadata: a :class:`~sqlalchemy.schema.MetaData`
- instance.
-
- """
- autogen_context, connection = _autogen_context(context, None)
- diffs = []
-
- object_filters = _get_object_filters(context.opts)
- include_schemas = context.opts.get('include_schemas', False)
-
- _produce_net_changes(connection, metadata, diffs, autogen_context,
- object_filters, include_schemas)
-
- return diffs
-
-###################################################
-# top level
-
-def _produce_migration_diffs(context, template_args,
- imports, include_symbol=None,
- include_object=None,
- include_schemas=False):
- opts = context.opts
- metadata = opts['target_metadata']
- include_schemas = opts.get('include_schemas', include_schemas)
-
- object_filters = _get_object_filters(opts, include_symbol, include_object)
-
- if metadata is None:
- raise util.CommandError(
- "Can't proceed with --autogenerate option; environment "
- "script %s does not provide "
- "a MetaData object to the context." % (
- context.script.env_py_location
- ))
- autogen_context, connection = _autogen_context(context, imports)
-
- diffs = []
- _produce_net_changes(connection, metadata, diffs,
- autogen_context, object_filters, include_schemas)
- template_args[opts['upgrade_token']] = \
- _indent(_produce_upgrade_commands(diffs, autogen_context))
- template_args[opts['downgrade_token']] = \
- _indent(_produce_downgrade_commands(diffs, autogen_context))
- template_args['imports'] = "\n".join(sorted(imports))
-
-
-def _get_object_filters(context_opts, include_symbol=None, include_object=None):
- include_symbol = context_opts.get('include_symbol', include_symbol)
- include_object = context_opts.get('include_object', include_object)
-
- object_filters = []
- if include_symbol:
- def include_symbol_filter(object, name, type_, reflected, compare_to):
- if type_ == "table":
- return include_symbol(name, object.schema)
- else:
- return True
- object_filters.append(include_symbol_filter)
- if include_object:
- object_filters.append(include_object)
-
- return object_filters
-
-
-def _autogen_context(context, imports):
- opts = context.opts
- connection = context.bind
- return {
- 'imports': imports,
- 'connection': connection,
- 'dialect': connection.dialect,
- 'context': context,
- 'opts': opts
- }, connection
-
-def _indent(text):
- text = "### commands auto generated by Alembic - "\
- "please adjust! ###\n" + text
- text += "\n### end Alembic commands ###"
- text = re.compile(r'^', re.M).sub(" ", text).strip()
- return text
-
-###################################################
-# walk structures
-
-
-def _produce_net_changes(connection, metadata, diffs, autogen_context,
- object_filters=(),
- include_schemas=False):
- inspector = Inspector.from_engine(connection)
- # TODO: not hardcode alembic_version here ?
- conn_table_names = set()
-
- default_schema = connection.dialect.default_schema_name
- if include_schemas:
- schemas = set(inspector.get_schema_names())
- # replace default schema name with None
- schemas.discard("information_schema")
- # replace the "default" schema with None
- schemas.add(None)
- schemas.discard(default_schema)
- else:
- schemas = [None]
-
- for s in schemas:
- tables = set(inspector.get_table_names(schema=s)).\
- difference(['alembic_version'])
- conn_table_names.update(zip([s] * len(tables), tables))
-
- metadata_table_names = OrderedSet([(table.schema, table.name)
- for table in metadata.sorted_tables])
-
- _compare_tables(conn_table_names, metadata_table_names,
- object_filters,
- inspector, metadata, diffs, autogen_context)
-
-
-###################################################
-# element comparison
-
-
-###################################################
-# render python
-
-
-###################################################
-# produce command structure
-
-def _produce_upgrade_commands(diffs, autogen_context):
- buf = []
- for diff in diffs:
- buf.append(_invoke_command("upgrade", diff, autogen_context))
- if not buf:
- buf = ["pass"]
- return "\n".join(buf)
-
-def _produce_downgrade_commands(diffs, autogen_context):
- buf = []
- for diff in reversed(diffs):
- buf.append(_invoke_command("downgrade", diff, autogen_context))
- if not buf:
- buf = ["pass"]
- return "\n".join(buf)
-
-def _invoke_command(updown, args, autogen_context):
- if isinstance(args, tuple):
- return _invoke_adddrop_command(updown, args, autogen_context)
- else:
- return _invoke_modify_command(updown, args, autogen_context)
-
-def _invoke_adddrop_command(updown, args, autogen_context):
- cmd_type = args[0]
- adddrop, cmd_type = cmd_type.split("_")
-
- cmd_args = args[1:] + (autogen_context,)
-
- _commands = {
- "table": (_drop_table, _add_table),
- "column": (_drop_column, _add_column),
- "index": (_drop_index, _add_index),
- "constraint": (_drop_constraint, _add_constraint),
- }
-
- cmd_callables = _commands[cmd_type]
-
- if (
- updown == "upgrade" and adddrop == "add"
- ) or (
- updown == "downgrade" and adddrop == "remove"
- ):
- return cmd_callables[1](*cmd_args)
- else:
- return cmd_callables[0](*cmd_args)
-
-def _invoke_modify_command(updown, args, autogen_context):
- sname, tname, cname = args[0][1:4]
- kw = {}
-
- _arg_struct = {
- "modify_type": ("existing_type", "type_"),
- "modify_nullable": ("existing_nullable", "nullable"),
- "modify_default": ("existing_server_default", "server_default"),
- }
- for diff in args:
- diff_kw = diff[4]
- for arg in ("existing_type", \
- "existing_nullable", \
- "existing_server_default"):
- if arg in diff_kw:
- kw.setdefault(arg, diff_kw[arg])
- old_kw, new_kw = _arg_struct[diff[0]]
- if updown == "upgrade":
- kw[new_kw] = diff[-1]
- kw[old_kw] = diff[-2]
- else:
- kw[new_kw] = diff[-2]
- kw[old_kw] = diff[-1]
-
- if "nullable" in kw:
- kw.pop("existing_nullable", None)
- if "server_default" in kw:
- kw.pop("existing_server_default", None)
- return _modify_col(tname, cname, autogen_context, schema=sname, **kw)
diff --git a/Darwin/lib/python2.7/site-packages/alembic/autogenerate/compare.py b/Darwin/lib/python2.7/site-packages/alembic/autogenerate/compare.py
deleted file mode 100644
index ec077fd..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/autogenerate/compare.py
+++ /dev/null
@@ -1,490 +0,0 @@
-from sqlalchemy.exc import NoSuchTableError
-from sqlalchemy import schema as sa_schema, types as sqltypes
-import logging
-from .. import compat
-from .render import _render_server_default
-from sqlalchemy.util import OrderedSet
-
-
-log = logging.getLogger(__name__)
-
-def _run_filters(object_, name, type_, reflected, compare_to, object_filters):
- for fn in object_filters:
- if not fn(object_, name, type_, reflected, compare_to):
- return False
- else:
- return True
-
-def _compare_tables(conn_table_names, metadata_table_names,
- object_filters,
- inspector, metadata, diffs, autogen_context):
-
- default_schema = inspector.bind.dialect.default_schema_name
-
- # tables coming from the connection will not have "schema"
- # set if it matches default_schema_name; so we need a list
- # of table names from local metadata that also have "None" if schema
- # == default_schema_name. Most setups will be like this anyway but
- # some are not (see #170)
- metadata_table_names_no_dflt_schema = OrderedSet([
- (schema if schema != default_schema else None, tname)
- for schema, tname in metadata_table_names
- ])
-
- # to adjust for the MetaData collection storing the tables either
- # as "schemaname.tablename" or just "tablename", create a new lookup
- # which will match the "non-default-schema" keys to the Table object.
- tname_to_table = dict(
- (
- no_dflt_schema,
- metadata.tables[sa_schema._get_table_key(tname, schema)]
- )
- for no_dflt_schema, (schema, tname) in zip(
- metadata_table_names_no_dflt_schema,
- metadata_table_names)
- )
- metadata_table_names = metadata_table_names_no_dflt_schema
-
- for s, tname in metadata_table_names.difference(conn_table_names):
- name = '%s.%s' % (s, tname) if s else tname
- metadata_table = tname_to_table[(s, tname)]
- if _run_filters(metadata_table, tname, "table", False, None, object_filters):
- diffs.append(("add_table", metadata_table))
- log.info("Detected added table %r", name)
- _compare_indexes_and_uniques(s, tname, object_filters,
- None,
- metadata_table,
- diffs, autogen_context, inspector)
-
- removal_metadata = sa_schema.MetaData()
- for s, tname in conn_table_names.difference(metadata_table_names):
- name = sa_schema._get_table_key(tname, s)
- exists = name in removal_metadata.tables
- t = sa_schema.Table(tname, removal_metadata, schema=s)
- if not exists:
- inspector.reflecttable(t, None)
- if _run_filters(t, tname, "table", True, None, object_filters):
- diffs.append(("remove_table", t))
- log.info("Detected removed table %r", name)
-
- existing_tables = conn_table_names.intersection(metadata_table_names)
-
- existing_metadata = sa_schema.MetaData()
- conn_column_info = {}
- for s, tname in existing_tables:
- name = sa_schema._get_table_key(tname, s)
- exists = name in existing_metadata.tables
- t = sa_schema.Table(tname, existing_metadata, schema=s)
- if not exists:
- inspector.reflecttable(t, None)
- conn_column_info[(s, tname)] = t
-
- for s, tname in sorted(existing_tables):
- name = '%s.%s' % (s, tname) if s else tname
- metadata_table = tname_to_table[(s, tname)]
- conn_table = existing_metadata.tables[name]
-
- if _run_filters(metadata_table, tname, "table", False, conn_table, object_filters):
- _compare_columns(s, tname, object_filters,
- conn_table,
- metadata_table,
- diffs, autogen_context, inspector)
- _compare_indexes_and_uniques(s, tname, object_filters,
- conn_table,
- metadata_table,
- diffs, autogen_context, inspector)
-
- # TODO:
- # table constraints
- # sequences
-
-def _make_index(params, conn_table):
- return sa_schema.Index(
- params['name'],
- *[conn_table.c[cname] for cname in params['column_names']],
- unique=params['unique']
- )
-
-def _make_unique_constraint(params, conn_table):
- return sa_schema.UniqueConstraint(
- *[conn_table.c[cname] for cname in params['column_names']],
- name=params['name']
- )
-
-def _compare_columns(schema, tname, object_filters, conn_table, metadata_table,
- diffs, autogen_context, inspector):
- name = '%s.%s' % (schema, tname) if schema else tname
- metadata_cols_by_name = dict((c.name, c) for c in metadata_table.c)
- conn_col_names = dict((c.name, c) for c in conn_table.c)
- metadata_col_names = OrderedSet(sorted(metadata_cols_by_name))
-
- for cname in metadata_col_names.difference(conn_col_names):
- if _run_filters(metadata_cols_by_name[cname], cname,
- "column", False, None, object_filters):
- diffs.append(
- ("add_column", schema, tname, metadata_cols_by_name[cname])
- )
- log.info("Detected added column '%s.%s'", name, cname)
-
- for cname in set(conn_col_names).difference(metadata_col_names):
- if _run_filters(conn_table.c[cname], cname,
- "column", True, None, object_filters):
- diffs.append(
- ("remove_column", schema, tname, conn_table.c[cname])
- )
- log.info("Detected removed column '%s.%s'", name, cname)
-
- for colname in metadata_col_names.intersection(conn_col_names):
- metadata_col = metadata_cols_by_name[colname]
- conn_col = conn_table.c[colname]
- if not _run_filters(
- metadata_col, colname, "column", False, conn_col, object_filters):
- continue
- col_diff = []
- _compare_type(schema, tname, colname,
- conn_col,
- metadata_col,
- col_diff, autogen_context
- )
- _compare_nullable(schema, tname, colname,
- conn_col,
- metadata_col.nullable,
- col_diff, autogen_context
- )
- _compare_server_default(schema, tname, colname,
- conn_col,
- metadata_col,
- col_diff, autogen_context
- )
- if col_diff:
- diffs.append(col_diff)
-
-class _constraint_sig(object):
- def __eq__(self, other):
- return self.const == other.const
-
- def __ne__(self, other):
- return self.const != other.const
-
- def __hash__(self):
- return hash(self.const)
-
-class _uq_constraint_sig(_constraint_sig):
- is_index = False
- is_unique = True
-
- def __init__(self, const):
- self.const = const
- self.name = const.name
- self.sig = tuple(sorted([col.name for col in const.columns]))
-
- @property
- def column_names(self):
- return [col.name for col in self.const.columns]
-
-class _ix_constraint_sig(_constraint_sig):
- is_index = True
-
- def __init__(self, const):
- self.const = const
- self.name = const.name
- self.sig = tuple(sorted([col.name for col in const.columns]))
- self.is_unique = bool(const.unique)
-
- @property
- def column_names(self):
- return _get_index_column_names(self.const)
-
-def _get_index_column_names(idx):
- if compat.sqla_08:
- return [getattr(exp, "name", None) for exp in idx.expressions]
- else:
- return [getattr(col, "name", None) for col in idx.columns]
-
-def _compare_indexes_and_uniques(schema, tname, object_filters, conn_table,
- metadata_table, diffs, autogen_context, inspector):
-
- is_create_table = conn_table is None
-
- # 1a. get raw indexes and unique constraints from metadata ...
- metadata_unique_constraints = set(uq for uq in metadata_table.constraints
- if isinstance(uq, sa_schema.UniqueConstraint)
- )
- metadata_indexes = set(metadata_table.indexes)
-
- conn_uniques = conn_indexes = frozenset()
-
- supports_unique_constraints = False
-
- if conn_table is not None:
- # 1b. ... and from connection, if the table exists
- if hasattr(inspector, "get_unique_constraints"):
- try:
- conn_uniques = inspector.get_unique_constraints(
- tname, schema=schema)
- supports_unique_constraints = True
- except NotImplementedError:
- pass
- try:
- conn_indexes = inspector.get_indexes(tname, schema=schema)
- except NotImplementedError:
- pass
-
- # 2. convert conn-level objects from raw inspector records
- # into schema objects
- conn_uniques = set(_make_unique_constraint(uq_def, conn_table)
- for uq_def in conn_uniques)
- conn_indexes = set(_make_index(ix, conn_table) for ix in conn_indexes)
-
- # 3. give the dialect a chance to omit indexes and constraints that
- # we know are either added implicitly by the DB or that the DB
- # can't accurately report on
- autogen_context['context'].impl.\
- correct_for_autogen_constraints(
- conn_uniques, conn_indexes,
- metadata_unique_constraints,
- metadata_indexes
- )
-
- # 4. organize the constraints into "signature" collections, the
- # _constraint_sig() objects provide a consistent facade over both
- # Index and UniqueConstraint so we can easily work with them
- # interchangeably
- metadata_unique_constraints = set(_uq_constraint_sig(uq)
- for uq in metadata_unique_constraints
- )
-
- metadata_indexes = set(_ix_constraint_sig(ix) for ix in metadata_indexes)
-
- conn_unique_constraints = set(_uq_constraint_sig(uq) for uq in conn_uniques)
-
- conn_indexes = set(_ix_constraint_sig(ix) for ix in conn_indexes)
-
- # 5. index things by name, for those objects that have names
- metadata_names = dict(
- (c.name, c) for c in
- metadata_unique_constraints.union(metadata_indexes)
- if c.name is not None)
-
- conn_uniques_by_name = dict((c.name, c) for c in conn_unique_constraints)
- conn_indexes_by_name = dict((c.name, c) for c in conn_indexes)
-
- conn_names = dict((c.name, c) for c in
- conn_unique_constraints.union(conn_indexes)
- if c.name is not None)
-
- doubled_constraints = dict(
- (name, (conn_uniques_by_name[name], conn_indexes_by_name[name]))
- for name in set(conn_uniques_by_name).intersection(conn_indexes_by_name)
- )
-
- # 6. index things by "column signature", to help with unnamed unique
- # constraints.
- conn_uniques_by_sig = dict((uq.sig, uq) for uq in conn_unique_constraints)
- metadata_uniques_by_sig = dict(
- (uq.sig, uq) for uq in metadata_unique_constraints)
- metadata_indexes_by_sig = dict(
- (ix.sig, ix) for ix in metadata_indexes)
- unnamed_metadata_uniques = dict((uq.sig, uq) for uq in
- metadata_unique_constraints if uq.name is None)
-
- # assumptions:
- # 1. a unique constraint or an index from the connection *always*
- # has a name.
- # 2. an index on the metadata side *always* has a name.
- # 3. a unique constraint on the metadata side *might* have a name.
- # 4. The backend may double up indexes as unique constraints and
- # vice versa (e.g. MySQL, Postgresql)
-
- def obj_added(obj):
- if obj.is_index:
- diffs.append(("add_index", obj.const))
- log.info("Detected added index '%s' on %s",
- obj.name, ', '.join([
- "'%s'" % obj.column_names
- ])
- )
- else:
- if not supports_unique_constraints:
- # can't report unique indexes as added if we don't
- # detect them
- return
- if is_create_table:
- # unique constraints are created inline with table defs
- return
- diffs.append(("add_constraint", obj.const))
- log.info("Detected added unique constraint '%s' on %s",
- obj.name, ', '.join([
- "'%s'" % obj.column_names
- ])
- )
-
- def obj_removed(obj):
- if obj.is_index:
- if obj.is_unique and not supports_unique_constraints:
- # many databases double up unique constraints
- # as unique indexes. without that list we can't
- # be sure what we're doing here
- return
-
- diffs.append(("remove_index", obj.const))
- log.info("Detected removed index '%s' on '%s'", obj.name, tname)
- else:
- diffs.append(("remove_constraint", obj.const))
- log.info("Detected removed unique constraint '%s' on '%s'",
- obj.name, tname
- )
-
- def obj_changed(old, new, msg):
- if old.is_index:
- log.info("Detected changed index '%s' on '%s':%s",
- old.name, tname, ', '.join(msg)
- )
- diffs.append(("remove_index", old.const))
- diffs.append(("add_index", new.const))
- else:
- log.info("Detected changed unique constraint '%s' on '%s':%s",
- old.name, tname, ', '.join(msg)
- )
- diffs.append(("remove_constraint", old.const))
- diffs.append(("add_constraint", new.const))
-
- for added_name in sorted(set(metadata_names).difference(conn_names)):
- obj = metadata_names[added_name]
- obj_added(obj)
-
-
- for existing_name in sorted(set(metadata_names).intersection(conn_names)):
- metadata_obj = metadata_names[existing_name]
-
- if existing_name in doubled_constraints:
- conn_uq, conn_idx = doubled_constraints[existing_name]
- if metadata_obj.is_index:
- conn_obj = conn_idx
- else:
- conn_obj = conn_uq
- else:
- conn_obj = conn_names[existing_name]
-
- if conn_obj.is_index != metadata_obj.is_index:
- obj_removed(conn_obj)
- obj_added(metadata_obj)
- else:
- msg = []
- if conn_obj.is_unique != metadata_obj.is_unique:
- msg.append(' unique=%r to unique=%r' % (
- conn_obj.is_unique, metadata_obj.is_unique
- ))
- if conn_obj.sig != metadata_obj.sig:
- msg.append(' columns %r to %r' % (
- conn_obj.sig, metadata_obj.sig
- ))
-
- if msg:
- obj_changed(conn_obj, metadata_obj, msg)
-
-
- for removed_name in sorted(set(conn_names).difference(metadata_names)):
- conn_obj = conn_names[removed_name]
- if not conn_obj.is_index and conn_obj.sig in unnamed_metadata_uniques:
- continue
- elif removed_name in doubled_constraints:
- if conn_obj.sig not in metadata_indexes_by_sig and \
- conn_obj.sig not in metadata_uniques_by_sig:
- conn_uq, conn_idx = doubled_constraints[removed_name]
- obj_removed(conn_uq)
- obj_removed(conn_idx)
- else:
- obj_removed(conn_obj)
-
- for uq_sig in unnamed_metadata_uniques:
- if uq_sig not in conn_uniques_by_sig:
- obj_added(unnamed_metadata_uniques[uq_sig])
-
-
-def _compare_nullable(schema, tname, cname, conn_col,
- metadata_col_nullable, diffs,
- autogen_context):
- conn_col_nullable = conn_col.nullable
- if conn_col_nullable is not metadata_col_nullable:
- diffs.append(
- ("modify_nullable", schema, tname, cname,
- {
- "existing_type": conn_col.type,
- "existing_server_default": conn_col.server_default,
- },
- conn_col_nullable,
- metadata_col_nullable),
- )
- log.info("Detected %s on column '%s.%s'",
- "NULL" if metadata_col_nullable else "NOT NULL",
- tname,
- cname
- )
-
-def _compare_type(schema, tname, cname, conn_col,
- metadata_col, diffs,
- autogen_context):
-
- conn_type = conn_col.type
- metadata_type = metadata_col.type
- if conn_type._type_affinity is sqltypes.NullType:
- log.info("Couldn't determine database type "
- "for column '%s.%s'", tname, cname)
- return
- if metadata_type._type_affinity is sqltypes.NullType:
- log.info("Column '%s.%s' has no type within "
- "the model; can't compare", tname, cname)
- return
-
- isdiff = autogen_context['context']._compare_type(conn_col, metadata_col)
-
- if isdiff:
-
- diffs.append(
- ("modify_type", schema, tname, cname,
- {
- "existing_nullable": conn_col.nullable,
- "existing_server_default": conn_col.server_default,
- },
- conn_type,
- metadata_type),
- )
- log.info("Detected type change from %r to %r on '%s.%s'",
- conn_type, metadata_type, tname, cname
- )
-
-def _compare_server_default(schema, tname, cname, conn_col, metadata_col,
- diffs, autogen_context):
-
- metadata_default = metadata_col.server_default
- conn_col_default = conn_col.server_default
- if conn_col_default is None and metadata_default is None:
- return False
- rendered_metadata_default = _render_server_default(
- metadata_default, autogen_context)
- rendered_conn_default = conn_col.server_default.arg.text \
- if conn_col.server_default else None
- isdiff = autogen_context['context']._compare_server_default(
- conn_col, metadata_col,
- rendered_metadata_default,
- rendered_conn_default
- )
- if isdiff:
- conn_col_default = rendered_conn_default
- diffs.append(
- ("modify_default", schema, tname, cname,
- {
- "existing_nullable": conn_col.nullable,
- "existing_type": conn_col.type,
- },
- conn_col_default,
- metadata_default),
- )
- log.info("Detected server default on column '%s.%s'",
- tname,
- cname
- )
-
-
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/autogenerate/render.py b/Darwin/lib/python2.7/site-packages/alembic/autogenerate/render.py
deleted file mode 100644
index ed9536c..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/autogenerate/render.py
+++ /dev/null
@@ -1,457 +0,0 @@
-from sqlalchemy import schema as sa_schema, types as sqltypes, sql
-import logging
-from .. import compat
-import re
-from ..compat import string_types
-
-log = logging.getLogger(__name__)
-
-try:
- from sqlalchemy.sql.naming import conv
- def _render_gen_name(autogen_context, name):
- if isinstance(name, conv):
- return _f_name(_alembic_autogenerate_prefix(autogen_context), name)
- else:
- return name
-except ImportError:
- def _render_gen_name(autogen_context, name):
- return name
-
-class _f_name(object):
- def __init__(self, prefix, name):
- self.prefix = prefix
- self.name = name
-
- def __repr__(self):
- return "%sf(%r)" % (self.prefix, self.name)
-
-def _render_potential_expr(value, autogen_context):
- if isinstance(value, sql.ClauseElement):
- if compat.sqla_08:
- compile_kw = dict(compile_kwargs={'literal_binds': True})
- else:
- compile_kw = {}
-
- return "%(prefix)stext(%(sql)r)" % {
- "prefix": _sqlalchemy_autogenerate_prefix(autogen_context),
- "sql": str(
- value.compile(dialect=autogen_context['dialect'],
- **compile_kw)
- )
- }
-
- else:
- return repr(value)
-
-def _add_table(table, autogen_context):
- text = "%(prefix)screate_table(%(tablename)r,\n%(args)s" % {
- 'tablename': table.name,
- 'prefix': _alembic_autogenerate_prefix(autogen_context),
- 'args': ',\n'.join(
- [col for col in
- [_render_column(col, autogen_context) for col in table.c]
- if col] +
- sorted([rcons for rcons in
- [_render_constraint(cons, autogen_context) for cons in
- table.constraints]
- if rcons is not None
- ])
- )
- }
- if table.schema:
- text += ",\nschema=%r" % table.schema
- for k in sorted(table.kwargs):
- text += ",\n%s=%r" % (k.replace(" ", "_"), table.kwargs[k])
- text += "\n)"
- return text
-
-def _drop_table(table, autogen_context):
- text = "%(prefix)sdrop_table(%(tname)r" % {
- "prefix": _alembic_autogenerate_prefix(autogen_context),
- "tname": table.name
- }
- if table.schema:
- text += ", schema=%r" % table.schema
- text += ")"
- return text
-
-def _add_index(index, autogen_context):
- """
- Generate Alembic operations for the CREATE INDEX of an
- :class:`~sqlalchemy.schema.Index` instance.
- """
- from .compare import _get_index_column_names
-
- text = "%(prefix)screate_index(%(name)r, '%(table)s', %(columns)s, "\
- "unique=%(unique)r%(schema)s%(kwargs)s)" % {
- 'prefix': _alembic_autogenerate_prefix(autogen_context),
- 'name': _render_gen_name(autogen_context, index.name),
- 'table': index.table.name,
- 'columns': _get_index_column_names(index),
- 'unique': index.unique or False,
- 'schema': (", schema='%s'" % index.table.schema) if index.table.schema else '',
- 'kwargs': (', '+', '.join(
- ["%s=%s" % (key, _render_potential_expr(val, autogen_context))
- for key, val in index.kwargs.items()]))\
- if len(index.kwargs) else ''
- }
- return text
-
-def _drop_index(index, autogen_context):
- """
- Generate Alembic operations for the DROP INDEX of an
- :class:`~sqlalchemy.schema.Index` instance.
- """
- text = "%(prefix)sdrop_index(%(name)r, "\
- "table_name='%(table_name)s'%(schema)s)" % {
- 'prefix': _alembic_autogenerate_prefix(autogen_context),
- 'name': _render_gen_name(autogen_context, index.name),
- 'table_name': index.table.name,
- 'schema': ((", schema='%s'" % index.table.schema)
- if index.table.schema else '')
- }
- return text
-
-
-def _render_unique_constraint(constraint, autogen_context):
- rendered = _user_defined_render("unique", constraint, autogen_context)
- if rendered is not False:
- return rendered
-
- return _uq_constraint(constraint, autogen_context, False)
-
-
-def _add_unique_constraint(constraint, autogen_context):
- """
- Generate Alembic operations for the ALTER TABLE .. ADD CONSTRAINT ...
- UNIQUE of a :class:`~sqlalchemy.schema.UniqueConstraint` instance.
- """
- return _uq_constraint(constraint, autogen_context, True)
-
-def _uq_constraint(constraint, autogen_context, alter):
- opts = []
- if constraint.deferrable:
- opts.append(("deferrable", str(constraint.deferrable)))
- if constraint.initially:
- opts.append(("initially", str(constraint.initially)))
- if alter and constraint.table.schema:
- opts.append(("schema", str(constraint.table.schema)))
- if not alter and constraint.name:
- opts.append(("name", _render_gen_name(autogen_context, constraint.name)))
-
- if alter:
- args = [repr(_render_gen_name(autogen_context, constraint.name)),
- repr(constraint.table.name)]
- args.append(repr([col.name for col in constraint.columns]))
- args.extend(["%s=%r" % (k, v) for k, v in opts])
- return "%(prefix)screate_unique_constraint(%(args)s)" % {
- 'prefix': _alembic_autogenerate_prefix(autogen_context),
- 'args': ", ".join(args)
- }
- else:
- args = [repr(col.name) for col in constraint.columns]
- args.extend(["%s=%r" % (k, v) for k, v in opts])
- return "%(prefix)sUniqueConstraint(%(args)s)" % {
- "prefix": _sqlalchemy_autogenerate_prefix(autogen_context),
- "args": ", ".join(args)
- }
-
-
-def _add_fk_constraint(constraint, autogen_context):
- raise NotImplementedError()
-
-def _add_pk_constraint(constraint, autogen_context):
- raise NotImplementedError()
-
-def _add_check_constraint(constraint, autogen_context):
- raise NotImplementedError()
-
-def _add_constraint(constraint, autogen_context):
- """
- Dispatcher for the different types of constraints.
- """
- funcs = {
- "unique_constraint": _add_unique_constraint,
- "foreign_key_constraint": _add_fk_constraint,
- "primary_key_constraint": _add_pk_constraint,
- "check_constraint": _add_check_constraint,
- "column_check_constraint": _add_check_constraint,
- }
- return funcs[constraint.__visit_name__](constraint, autogen_context)
-
-def _drop_constraint(constraint, autogen_context):
- """
- Generate Alembic operations for the ALTER TABLE ... DROP CONSTRAINT
- of a :class:`~sqlalchemy.schema.UniqueConstraint` instance.
- """
- text = "%(prefix)sdrop_constraint(%(name)r, '%(table_name)s'%(schema)s)" % {
- 'prefix': _alembic_autogenerate_prefix(autogen_context),
- 'name': _render_gen_name(autogen_context, constraint.name),
- 'table_name': constraint.table.name,
- 'schema': (", schema='%s'" % constraint.table.schema)
- if constraint.table.schema else '',
- }
- return text
-
-def _add_column(schema, tname, column, autogen_context):
- text = "%(prefix)sadd_column(%(tname)r, %(column)s" % {
- "prefix": _alembic_autogenerate_prefix(autogen_context),
- "tname": tname,
- "column": _render_column(column, autogen_context)
- }
- if schema:
- text += ", schema=%r" % schema
- text += ")"
- return text
-
-def _drop_column(schema, tname, column, autogen_context):
- text = "%(prefix)sdrop_column(%(tname)r, %(cname)r" % {
- "prefix": _alembic_autogenerate_prefix(autogen_context),
- "tname": tname,
- "cname": column.name
- }
- if schema:
- text += ", schema=%r" % schema
- text += ")"
- return text
-
-def _modify_col(tname, cname,
- autogen_context,
- server_default=False,
- type_=None,
- nullable=None,
- existing_type=None,
- existing_nullable=None,
- existing_server_default=False,
- schema=None):
- indent = " " * 11
- text = "%(prefix)salter_column(%(tname)r, %(cname)r" % {
- 'prefix': _alembic_autogenerate_prefix(
- autogen_context),
- 'tname': tname,
- 'cname': cname}
- text += ",\n%sexisting_type=%s" % (indent,
- _repr_type(existing_type, autogen_context))
- if server_default is not False:
- rendered = _render_server_default(
- server_default, autogen_context)
- text += ",\n%sserver_default=%s" % (indent, rendered)
-
- if type_ is not None:
- text += ",\n%stype_=%s" % (indent,
- _repr_type(type_, autogen_context))
- if nullable is not None:
- text += ",\n%snullable=%r" % (
- indent, nullable,)
- if existing_nullable is not None:
- text += ",\n%sexisting_nullable=%r" % (
- indent, existing_nullable)
- if existing_server_default:
- rendered = _render_server_default(
- existing_server_default,
- autogen_context)
- text += ",\n%sexisting_server_default=%s" % (
- indent, rendered)
- if schema:
- text += ",\n%sschema=%r" % (indent, schema)
- text += ")"
- return text
-
-def _user_autogenerate_prefix(autogen_context):
- prefix = autogen_context['opts']['user_module_prefix']
- if prefix is None:
- return _sqlalchemy_autogenerate_prefix(autogen_context)
- else:
- return prefix
-
-def _sqlalchemy_autogenerate_prefix(autogen_context):
- return autogen_context['opts']['sqlalchemy_module_prefix'] or ''
-
-def _alembic_autogenerate_prefix(autogen_context):
- return autogen_context['opts']['alembic_module_prefix'] or ''
-
-def _user_defined_render(type_, object_, autogen_context):
- if 'opts' in autogen_context and \
- 'render_item' in autogen_context['opts']:
- render = autogen_context['opts']['render_item']
- if render:
- rendered = render(type_, object_, autogen_context)
- if rendered is not False:
- return rendered
- return False
-
-def _render_column(column, autogen_context):
- rendered = _user_defined_render("column", column, autogen_context)
- if rendered is not False:
- return rendered
-
- opts = []
- if column.server_default:
- rendered = _render_server_default(
- column.server_default, autogen_context
- )
- if rendered:
- opts.append(("server_default", rendered))
-
- if not column.autoincrement:
- opts.append(("autoincrement", column.autoincrement))
-
- if column.nullable is not None:
- opts.append(("nullable", column.nullable))
-
- # TODO: for non-ascii colname, assign a "key"
- return "%(prefix)sColumn(%(name)r, %(type)s, %(kw)s)" % {
- 'prefix': _sqlalchemy_autogenerate_prefix(autogen_context),
- 'name': column.name,
- 'type': _repr_type(column.type, autogen_context),
- 'kw': ", ".join(["%s=%s" % (kwname, val) for kwname, val in opts])
- }
-
-def _render_server_default(default, autogen_context):
- rendered = _user_defined_render("server_default", default, autogen_context)
- if rendered is not False:
- return rendered
-
- if isinstance(default, sa_schema.DefaultClause):
- if isinstance(default.arg, string_types):
- default = default.arg
- else:
- default = str(default.arg.compile(
- dialect=autogen_context['dialect']))
- if isinstance(default, string_types):
- # TODO: this is just a hack to get
- # tests to pass until we figure out
- # WTF sqlite is doing
- default = re.sub(r"^'|'$", "", default)
- return repr(default)
- else:
- return None
-
-def _repr_type(type_, autogen_context):
- rendered = _user_defined_render("type", type_, autogen_context)
- if rendered is not False:
- return rendered
-
- mod = type(type_).__module__
- imports = autogen_context.get('imports', None)
- if mod.startswith("sqlalchemy.dialects"):
- dname = re.match(r"sqlalchemy\.dialects\.(\w+)", mod).group(1)
- if imports is not None:
- imports.add("from sqlalchemy.dialects import %s" % dname)
- return "%s.%r" % (dname, type_)
- elif mod.startswith("sqlalchemy"):
- prefix = _sqlalchemy_autogenerate_prefix(autogen_context)
- return "%s%r" % (prefix, type_)
- else:
- prefix = _user_autogenerate_prefix(autogen_context)
- return "%s%r" % (prefix, type_)
-
-def _render_constraint(constraint, autogen_context):
- renderer = _constraint_renderers.get(type(constraint), None)
- if renderer:
- return renderer(constraint, autogen_context)
- else:
- return None
-
-def _render_primary_key(constraint, autogen_context):
- rendered = _user_defined_render("primary_key", constraint, autogen_context)
- if rendered is not False:
- return rendered
-
- if not constraint.columns:
- return None
-
- opts = []
- if constraint.name:
- opts.append(("name", repr(_render_gen_name(autogen_context, constraint.name))))
- return "%(prefix)sPrimaryKeyConstraint(%(args)s)" % {
- "prefix": _sqlalchemy_autogenerate_prefix(autogen_context),
- "args": ", ".join(
- [repr(c.key) for c in constraint.columns] +
- ["%s=%s" % (kwname, val) for kwname, val in opts]
- ),
- }
-
-def _fk_colspec(fk, metadata_schema):
- """Implement a 'safe' version of ForeignKey._get_colspec() that
- never tries to resolve the remote table.
-
- """
- if metadata_schema is None:
- return fk._get_colspec()
- else:
- # need to render schema breaking up tokens by hand, since the
- # ForeignKeyConstraint here may not actually have a remote
- # Table present
- tokens = fk._colspec.split(".")
- # no schema in the colspec, render it
- if len(tokens) == 2:
- return "%s.%s" % (metadata_schema, fk._colspec)
- else:
- return fk._colspec
-
-def _render_foreign_key(constraint, autogen_context):
- rendered = _user_defined_render("foreign_key", constraint, autogen_context)
- if rendered is not False:
- return rendered
-
- opts = []
- if constraint.name:
- opts.append(("name", repr(_render_gen_name(autogen_context, constraint.name))))
- if constraint.onupdate:
- opts.append(("onupdate", repr(constraint.onupdate)))
- if constraint.ondelete:
- opts.append(("ondelete", repr(constraint.ondelete)))
- if constraint.initially:
- opts.append(("initially", repr(constraint.initially)))
- if constraint.deferrable:
- opts.append(("deferrable", repr(constraint.deferrable)))
- if constraint.use_alter:
- opts.append(("use_alter", repr(constraint.use_alter)))
-
- apply_metadata_schema = constraint.parent.metadata.schema
- return "%(prefix)sForeignKeyConstraint([%(cols)s], "\
- "[%(refcols)s], %(args)s)" % {
- "prefix": _sqlalchemy_autogenerate_prefix(autogen_context),
- "cols": ", ".join("'%s'" % f.parent.key for f in constraint.elements),
- "refcols": ", ".join(repr(_fk_colspec(f, apply_metadata_schema))
- for f in constraint.elements),
- "args": ", ".join(
- ["%s=%s" % (kwname, val) for kwname, val in opts]
- ),
- }
-
-def _render_check_constraint(constraint, autogen_context):
- rendered = _user_defined_render("check", constraint, autogen_context)
- if rendered is not False:
- return rendered
-
- # detect the constraint being part of
- # a parent type which is probably in the Table already.
- # ideally SQLAlchemy would give us more of a first class
- # way to detect this.
- if constraint._create_rule and \
- hasattr(constraint._create_rule, 'target') and \
- isinstance(constraint._create_rule.target,
- sqltypes.TypeEngine):
- return None
- opts = []
- if constraint.name:
- opts.append(("name", repr(_render_gen_name(autogen_context, constraint.name))))
- return "%(prefix)sCheckConstraint(%(sqltext)r%(opts)s)" % {
- "prefix": _sqlalchemy_autogenerate_prefix(autogen_context),
- "opts": ", " + (", ".join("%s=%s" % (k, v)
- for k, v in opts)) if opts else "",
- "sqltext": str(
- constraint.sqltext.compile(
- dialect=autogen_context['dialect']
- )
- )
- }
-
-_constraint_renderers = {
- sa_schema.PrimaryKeyConstraint: _render_primary_key,
- sa_schema.ForeignKeyConstraint: _render_foreign_key,
- sa_schema.UniqueConstraint: _render_unique_constraint,
- sa_schema.CheckConstraint: _render_check_constraint
-}
diff --git a/Darwin/lib/python2.7/site-packages/alembic/command.py b/Darwin/lib/python2.7/site-packages/alembic/command.py
deleted file mode 100644
index f1c5962..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/command.py
+++ /dev/null
@@ -1,266 +0,0 @@
-import os
-
-from .script import ScriptDirectory
-from .environment import EnvironmentContext
-from . import util, autogenerate as autogen
-
-def list_templates(config):
- """List available templates"""
-
- config.print_stdout("Available templates:\n")
- for tempname in os.listdir(config.get_template_directory()):
- with open(os.path.join(
- config.get_template_directory(),
- tempname,
- 'README')) as readme:
- synopsis = next(readme)
- config.print_stdout("%s - %s", tempname, synopsis)
-
- config.print_stdout("\nTemplates are used via the 'init' command, e.g.:")
- config.print_stdout("\n alembic init --template pylons ./scripts")
-
-def init(config, directory, template='generic'):
- """Initialize a new scripts directory."""
-
- if os.access(directory, os.F_OK):
- raise util.CommandError("Directory %s already exists" % directory)
-
- template_dir = os.path.join(config.get_template_directory(),
- template)
- if not os.access(template_dir, os.F_OK):
- raise util.CommandError("No such template %r" % template)
-
- util.status("Creating directory %s" % os.path.abspath(directory),
- os.makedirs, directory)
-
- versions = os.path.join(directory, 'versions')
- util.status("Creating directory %s" % os.path.abspath(versions),
- os.makedirs, versions)
-
- script = ScriptDirectory(directory)
-
- for file_ in os.listdir(template_dir):
- file_path = os.path.join(template_dir, file_)
- if file_ == 'alembic.ini.mako':
- config_file = os.path.abspath(config.config_file_name)
- if os.access(config_file, os.F_OK):
- util.msg("File %s already exists, skipping" % config_file)
- else:
- script._generate_template(
- file_path,
- config_file,
- script_location=directory
- )
- elif os.path.isfile(file_path):
- output_file = os.path.join(directory, file_)
- script._copy_file(
- file_path,
- output_file
- )
-
- util.msg("Please edit configuration/connection/logging "\
- "settings in %r before proceeding." % config_file)
-
-def revision(config, message=None, autogenerate=False, sql=False):
- """Create a new revision file."""
-
- script = ScriptDirectory.from_config(config)
- template_args = {
- 'config': config # Let templates use config for
- # e.g. multiple databases
- }
- imports = set()
-
- environment = util.asbool(
- config.get_main_option("revision_environment")
- )
-
- if autogenerate:
- environment = True
- def retrieve_migrations(rev, context):
- if script.get_revision(rev) is not script.get_revision("head"):
- raise util.CommandError("Target database is not up to date.")
- autogen._produce_migration_diffs(context, template_args, imports)
- return []
- elif environment:
- def retrieve_migrations(rev, context):
- return []
-
- if environment:
- with EnvironmentContext(
- config,
- script,
- fn=retrieve_migrations,
- as_sql=sql,
- template_args=template_args,
- ):
- script.run_env()
- return script.generate_revision(util.rev_id(), message, refresh=True,
- **template_args)
-
-
-def upgrade(config, revision, sql=False, tag=None):
- """Upgrade to a later version."""
-
- script = ScriptDirectory.from_config(config)
-
- starting_rev = None
- if ":" in revision:
- if not sql:
- raise util.CommandError("Range revision not allowed")
- starting_rev, revision = revision.split(':', 2)
-
- def upgrade(rev, context):
- return script._upgrade_revs(revision, rev)
-
- with EnvironmentContext(
- config,
- script,
- fn=upgrade,
- as_sql=sql,
- starting_rev=starting_rev,
- destination_rev=revision,
- tag=tag
- ):
- script.run_env()
-
-def downgrade(config, revision, sql=False, tag=None):
- """Revert to a previous version."""
-
- script = ScriptDirectory.from_config(config)
- starting_rev = None
- if ":" in revision:
- if not sql:
- raise util.CommandError("Range revision not allowed")
- starting_rev, revision = revision.split(':', 2)
- elif sql:
- raise util.CommandError("downgrade with --sql requires :")
-
- def downgrade(rev, context):
- return script._downgrade_revs(revision, rev)
-
- with EnvironmentContext(
- config,
- script,
- fn=downgrade,
- as_sql=sql,
- starting_rev=starting_rev,
- destination_rev=revision,
- tag=tag
- ):
- script.run_env()
-
-def history(config, rev_range=None):
- """List changeset scripts in chronological order."""
-
- script = ScriptDirectory.from_config(config)
- if rev_range is not None:
- if ":" not in rev_range:
- raise util.CommandError(
- "History range requires [start]:[end], "
- "[start]:, or :[end]")
- base, head = rev_range.strip().split(":")
- else:
- base = head = None
-
- def _display_history(config, script, base, head):
- for sc in script.walk_revisions(
- base=base or "base",
- head=head or "head"):
- if sc.is_head:
- config.print_stdout("")
- config.print_stdout(sc.log_entry)
-
- def _display_history_w_current(config, script, base=None, head=None):
- def _display_current_history(rev, context):
- if head is None:
- _display_history(config, script, base, rev)
- elif base is None:
- _display_history(config, script, rev, head)
- return []
-
- with EnvironmentContext(
- config,
- script,
- fn=_display_current_history
- ):
- script.run_env()
-
- if base == "current":
- _display_history_w_current(config, script, head=head)
- elif head == "current":
- _display_history_w_current(config, script, base=base)
- else:
- _display_history(config, script, base, head)
-
-
-def branches(config):
- """Show current un-spliced branch points"""
- script = ScriptDirectory.from_config(config)
- for sc in script.walk_revisions():
- if sc.is_branch_point:
- config.print_stdout(sc)
- for rev in sc.nextrev:
- config.print_stdout("%s -> %s",
- " " * len(str(sc.down_revision)),
- script.get_revision(rev)
- )
-
-def current(config, head_only=False):
- """Display the current revision for each database."""
-
- script = ScriptDirectory.from_config(config)
- def display_version(rev, context):
- rev = script.get_revision(rev)
-
- if head_only:
- config.print_stdout("%s%s" % (
- rev.revision if rev else None,
- " (head)" if rev and rev.is_head else ""))
-
- else:
- config.print_stdout("Current revision for %s: %s",
- util.obfuscate_url_pw(
- context.connection.engine.url),
- rev)
- return []
-
- with EnvironmentContext(
- config,
- script,
- fn=display_version
- ):
- script.run_env()
-
-def stamp(config, revision, sql=False, tag=None):
- """'stamp' the revision table with the given revision; don't
- run any migrations."""
-
- script = ScriptDirectory.from_config(config)
- def do_stamp(rev, context):
- if sql:
- current = False
- else:
- current = context._current_rev()
- dest = script.get_revision(revision)
- if dest is not None:
- dest = dest.revision
- context._update_current_rev(current, dest)
- return []
- with EnvironmentContext(
- config,
- script,
- fn=do_stamp,
- as_sql=sql,
- destination_rev=revision,
- tag=tag
- ):
- script.run_env()
-
-def splice(config, parent, child):
- """'splice' two branches, creating a new revision file.
-
- this command isn't implemented right now.
-
- """
- raise NotImplementedError()
diff --git a/Darwin/lib/python2.7/site-packages/alembic/compat.py b/Darwin/lib/python2.7/site-packages/alembic/compat.py
deleted file mode 100644
index aac0560..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/compat.py
+++ /dev/null
@@ -1,130 +0,0 @@
-import io
-import sys
-from sqlalchemy import __version__ as sa_version
-
-if sys.version_info < (2, 6):
- raise NotImplementedError("Python 2.6 or greater is required.")
-
-sqla_08 = sa_version >= '0.8.0'
-sqla_09 = sa_version >= '0.9.0'
-
-py2k = sys.version_info < (3, 0)
-py3k = sys.version_info >= (3, 0)
-py33 = sys.version_info >= (3, 3)
-
-if py3k:
- import builtins as compat_builtins
- string_types = str,
- binary_type = bytes
- text_type = str
- def callable(fn):
- return hasattr(fn, '__call__')
-
- def u(s):
- return s
-
-else:
- import __builtin__ as compat_builtins
- string_types = basestring,
- binary_type = str
- text_type = unicode
- callable = callable
-
- def u(s):
- return unicode(s, "utf-8")
-
-if py3k:
- from configparser import ConfigParser as SafeConfigParser
- import configparser
-else:
- from ConfigParser import SafeConfigParser
- import ConfigParser as configparser
-
-if py2k:
- from mako.util import parse_encoding
-
-if py33:
- from importlib import machinery
- def load_module_py(module_id, path):
- return machinery.SourceFileLoader(module_id, path).load_module(module_id)
-
- def load_module_pyc(module_id, path):
- return machinery.SourcelessFileLoader(module_id, path).load_module(module_id)
-
-else:
- import imp
- def load_module_py(module_id, path):
- with open(path, 'rb') as fp:
- mod = imp.load_source(module_id, path, fp)
- if py2k:
- source_encoding = parse_encoding(fp)
- if source_encoding:
- mod._alembic_source_encoding = source_encoding
- return mod
-
- def load_module_pyc(module_id, path):
- with open(path, 'rb') as fp:
- mod = imp.load_compiled(module_id, path, fp)
- # no source encoding here
- return mod
-
-try:
- exec_ = getattr(compat_builtins, 'exec')
-except AttributeError:
- # Python 2
- def exec_(func_text, globals_, lcl):
- exec('exec func_text in globals_, lcl')
-
-################################################
-# cross-compatible metaclass implementation
-# Copyright (c) 2010-2012 Benjamin Peterson
-def with_metaclass(meta, base=object):
- """Create a base class with a metaclass."""
- return meta("%sBase" % meta.__name__, (base,), {})
-################################################
-
-
-# produce a wrapper that allows encoded text to stream
-# into a given buffer, but doesn't close it.
-# not sure of a more idiomatic approach to this.
-class EncodedIO(io.TextIOWrapper):
- def close(self):
- pass
-
-if py2k:
- # in Py2K, the io.* package is awkward because it does not
- # easily wrap the file type (e.g. sys.stdout) and I can't
- # figure out at all how to wrap StringIO.StringIO (used by nosetests)
- # and also might be user specified too. So create a full
- # adapter.
-
- class ActLikePy3kIO(object):
- """Produce an object capable of wrapping either
- sys.stdout (e.g. file) *or* StringIO.StringIO().
-
- """
- def _false(self):
- return False
-
- def _true(self):
- return True
-
- readable = seekable = _false
- writable = _true
- closed = False
-
- def __init__(self, file_):
- self.file_ = file_
-
- def write(self, text):
- return self.file_.write(text)
-
- def flush(self):
- return self.file_.flush()
-
- class EncodedIO(EncodedIO):
- def __init__(self, file_, encoding):
- super(EncodedIO, self).__init__(
- ActLikePy3kIO(file_), encoding=encoding)
-
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/config.py b/Darwin/lib/python2.7/site-packages/alembic/config.py
deleted file mode 100644
index 86ff1df..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/config.py
+++ /dev/null
@@ -1,301 +0,0 @@
-from argparse import ArgumentParser
-from .compat import SafeConfigParser
-import inspect
-import os
-import sys
-
-from . import command, util, package_dir, compat
-
-class Config(object):
- """Represent an Alembic configuration.
-
- Within an ``env.py`` script, this is available
- via the :attr:`.EnvironmentContext.config` attribute,
- which in turn is available at ``alembic.context``::
-
- from alembic import context
-
- some_param = context.config.get_main_option("my option")
-
- When invoking Alembic programatically, a new
- :class:`.Config` can be created by passing
- the name of an .ini file to the constructor::
-
- from alembic.config import Config
- alembic_cfg = Config("/path/to/yourapp/alembic.ini")
-
- With a :class:`.Config` object, you can then
- run Alembic commands programmatically using the directives
- in :mod:`alembic.command`.
-
- The :class:`.Config` object can also be constructed without
- a filename. Values can be set programmatically, and
- new sections will be created as needed::
-
- from alembic.config import Config
- alembic_cfg = Config()
- alembic_cfg.set_main_option("script_location", "myapp:migrations")
- alembic_cfg.set_main_option("url", "postgresql://foo/bar")
- alembic_cfg.set_section_option("mysection", "foo", "bar")
-
- :param file_: name of the .ini file to open.
- :param ini_section: name of the main Alembic section within the
- .ini file
- :param output_buffer: optional file-like input buffer which
- will be passed to the :class:`.MigrationContext` - used to redirect
- the output of "offline generation" when using Alembic programmatically.
- :param stdout: buffer where the "print" output of commands will be sent.
- Defaults to ``sys.stdout``.
-
- ..versionadded:: 0.4
-
- """
- def __init__(self, file_=None, ini_section='alembic', output_buffer=None,
- stdout=sys.stdout, cmd_opts=None):
- """Construct a new :class:`.Config`
-
- """
- self.config_file_name = file_
- self.config_ini_section = ini_section
- self.output_buffer = output_buffer
- self.stdout = stdout
- self.cmd_opts = cmd_opts
-
- cmd_opts = None
- """The command-line options passed to the ``alembic`` script.
-
- Within an ``env.py`` script this can be accessed via the
- :attr:`.EnvironmentContext.config` attribute.
-
- .. versionadded:: 0.6.0
-
- .. seealso::
-
- :meth:`.EnvironmentContext.get_x_argument`
-
- """
-
- config_file_name = None
- """Filesystem path to the .ini file in use."""
-
- config_ini_section = None
- """Name of the config file section to read basic configuration
- from. Defaults to ``alembic``, that is the ``[alembic]`` section
- of the .ini file. This value is modified using the ``-n/--name``
- option to the Alembic runnier.
-
- """
-
- def print_stdout(self, text, *arg):
- """Render a message to standard out."""
-
- util.write_outstream(
- self.stdout,
- (compat.text_type(text) % arg),
- "\n"
- )
-
- @util.memoized_property
- def file_config(self):
- """Return the underlying :class:`ConfigParser` object.
-
- Direct access to the .ini file is available here,
- though the :meth:`.Config.get_section` and
- :meth:`.Config.get_main_option`
- methods provide a possibly simpler interface.
-
- """
-
- if self.config_file_name:
- here = os.path.abspath(os.path.dirname(self.config_file_name))
- else:
- here = ""
- file_config = SafeConfigParser({'here': here})
- if self.config_file_name:
- file_config.read([self.config_file_name])
- else:
- file_config.add_section(self.config_ini_section)
- return file_config
-
- def get_template_directory(self):
- """Return the directory where Alembic setup templates are found.
-
- This method is used by the alembic ``init`` and ``list_templates``
- commands.
-
- """
- return os.path.join(package_dir, 'templates')
-
- def get_section(self, name):
- """Return all the configuration options from a given .ini file section
- as a dictionary.
-
- """
- return dict(self.file_config.items(name))
-
- def set_main_option(self, name, value):
- """Set an option programmatically within the 'main' section.
-
- This overrides whatever was in the .ini file.
-
- """
- self.file_config.set(self.config_ini_section, name, value)
-
- def remove_main_option(self, name):
- self.file_config.remove_option(self.config_ini_section, name)
-
- def set_section_option(self, section, name, value):
- """Set an option programmatically within the given section.
-
- The section is created if it doesn't exist already.
- The value here will override whatever was in the .ini
- file.
-
- """
- if not self.file_config.has_section(section):
- self.file_config.add_section(section)
- self.file_config.set(section, name, value)
-
- def get_section_option(self, section, name, default=None):
- """Return an option from the given section of the .ini file.
-
- """
- if not self.file_config.has_section(section):
- raise util.CommandError("No config file %r found, or file has no "
- "'[%s]' section" %
- (self.config_file_name, section))
- if self.file_config.has_option(section, name):
- return self.file_config.get(section, name)
- else:
- return default
-
- def get_main_option(self, name, default=None):
- """Return an option from the 'main' section of the .ini file.
-
- This defaults to being a key from the ``[alembic]``
- section, unless the ``-n/--name`` flag were used to
- indicate a different section.
-
- """
- return self.get_section_option(self.config_ini_section, name, default)
-
-
-class CommandLine(object):
- def __init__(self, prog=None):
- self._generate_args(prog)
-
-
- def _generate_args(self, prog):
- def add_options(parser, positional, kwargs):
- if 'template' in kwargs:
- parser.add_argument("-t", "--template",
- default='generic',
- type=str,
- help="Setup template for use with 'init'")
- if 'message' in kwargs:
- parser.add_argument("-m", "--message",
- type=str,
- help="Message string to use with 'revision'")
- if 'sql' in kwargs:
- parser.add_argument("--sql",
- action="store_true",
- help="Don't emit SQL to database - dump to "
- "standard output/file instead")
- if 'tag' in kwargs:
- parser.add_argument("--tag",
- type=str,
- help="Arbitrary 'tag' name - can be used by "
- "custom env.py scripts.")
- if 'autogenerate' in kwargs:
- parser.add_argument("--autogenerate",
- action="store_true",
- help="Populate revision script with candidate "
- "migration operations, based on comparison "
- "of database to model.")
- # "current" command
- if 'head_only' in kwargs:
- parser.add_argument("--head-only",
- action="store_true",
- help="Only show current version and "
- "whether or not this is the head revision.")
-
- if 'rev_range' in kwargs:
- parser.add_argument("-r", "--rev-range",
- action="store",
- help="Specify a revision range; "
- "format is [start]:[end]")
-
-
- positional_help = {
- 'directory': "location of scripts directory",
- 'revision': "revision identifier"
- }
- for arg in positional:
- subparser.add_argument(arg, help=positional_help.get(arg))
-
- parser = ArgumentParser(prog=prog)
- parser.add_argument("-c", "--config",
- type=str,
- default="alembic.ini",
- help="Alternate config file")
- parser.add_argument("-n", "--name",
- type=str,
- default="alembic",
- help="Name of section in .ini file to "
- "use for Alembic config")
- parser.add_argument("-x", action="append",
- help="Additional arguments consumed by "
- "custom env.py scripts, e.g. -x "
- "setting1=somesetting -x setting2=somesetting")
-
- subparsers = parser.add_subparsers()
-
- for fn in [getattr(command, n) for n in dir(command)]:
- if inspect.isfunction(fn) and \
- fn.__name__[0] != '_' and \
- fn.__module__ == 'alembic.command':
-
- spec = inspect.getargspec(fn)
- if spec[3]:
- positional = spec[0][1:-len(spec[3])]
- kwarg = spec[0][-len(spec[3]):]
- else:
- positional = spec[0][1:]
- kwarg = []
-
- subparser = subparsers.add_parser(
- fn.__name__,
- help=fn.__doc__)
- add_options(subparser, positional, kwarg)
- subparser.set_defaults(cmd=(fn, positional, kwarg))
- self.parser = parser
-
- def run_cmd(self, config, options):
- fn, positional, kwarg = options.cmd
-
- try:
- fn(config,
- *[getattr(options, k) for k in positional],
- **dict((k, getattr(options, k)) for k in kwarg)
- )
- except util.CommandError as e:
- util.err(str(e))
-
- def main(self, argv=None):
- options = self.parser.parse_args(argv)
- if not hasattr(options, "cmd"):
- # see http://bugs.python.org/issue9253, argparse
- # behavior changed incompatibly in py3.3
- self.parser.error("too few arguments")
- else:
- cfg = Config(file_=options.config,
- ini_section=options.name, cmd_opts=options)
- self.run_cmd(cfg, options)
-
-def main(argv=None, prog=None, **kwargs):
- """The console runner function for Alembic."""
-
- CommandLine(prog=prog).main(argv=argv)
-
-if __name__ == '__main__':
- main()
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/alembic/context.py b/Darwin/lib/python2.7/site-packages/alembic/context.py
deleted file mode 100644
index 9c0f676..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/context.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from .environment import EnvironmentContext
-from . import util
-
-# create proxy functions for
-# each method on the EnvironmentContext class.
-util.create_module_class_proxy(EnvironmentContext, globals(), locals())
diff --git a/Darwin/lib/python2.7/site-packages/alembic/ddl/__init__.py b/Darwin/lib/python2.7/site-packages/alembic/ddl/__init__.py
deleted file mode 100644
index bfc8ab4..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/ddl/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-from . import postgresql, mysql, sqlite, mssql, oracle
-from .impl import DefaultImpl
diff --git a/Darwin/lib/python2.7/site-packages/alembic/ddl/base.py b/Darwin/lib/python2.7/site-packages/alembic/ddl/base.py
deleted file mode 100644
index 5d703a5..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/ddl/base.py
+++ /dev/null
@@ -1,161 +0,0 @@
-import functools
-
-from sqlalchemy.ext.compiler import compiles
-from sqlalchemy.schema import DDLElement, Column
-from sqlalchemy import Integer
-from sqlalchemy import types as sqltypes
-
-class AlterTable(DDLElement):
- """Represent an ALTER TABLE statement.
-
- Only the string name and optional schema name of the table
- is required, not a full Table object.
-
- """
- def __init__(self, table_name, schema=None):
- self.table_name = table_name
- self.schema = schema
-
-class RenameTable(AlterTable):
- def __init__(self, old_table_name, new_table_name, schema=None):
- super(RenameTable, self).__init__(old_table_name, schema=schema)
- self.new_table_name = new_table_name
-
-class AlterColumn(AlterTable):
- def __init__(self, name, column_name, schema=None,
- existing_type=None,
- existing_nullable=None,
- existing_server_default=None):
- super(AlterColumn, self).__init__(name, schema=schema)
- self.column_name = column_name
- self.existing_type=sqltypes.to_instance(existing_type) \
- if existing_type is not None else None
- self.existing_nullable=existing_nullable
- self.existing_server_default=existing_server_default
-
-class ColumnNullable(AlterColumn):
- def __init__(self, name, column_name, nullable, **kw):
- super(ColumnNullable, self).__init__(name, column_name,
- **kw)
- self.nullable = nullable
-
-class ColumnType(AlterColumn):
- def __init__(self, name, column_name, type_, **kw):
- super(ColumnType, self).__init__(name, column_name,
- **kw)
- self.type_ = sqltypes.to_instance(type_)
-
-class ColumnName(AlterColumn):
- def __init__(self, name, column_name, newname, **kw):
- super(ColumnName, self).__init__(name, column_name, **kw)
- self.newname = newname
-
-class ColumnDefault(AlterColumn):
- def __init__(self, name, column_name, default, **kw):
- super(ColumnDefault, self).__init__(name, column_name, **kw)
- self.default = default
-
-class AddColumn(AlterTable):
- def __init__(self, name, column, schema=None):
- super(AddColumn, self).__init__(name, schema=schema)
- self.column = column
-
-class DropColumn(AlterTable):
- def __init__(self, name, column, schema=None):
- super(DropColumn, self).__init__(name, schema=schema)
- self.column = column
-
-
-@compiles(RenameTable)
-def visit_rename_table(element, compiler, **kw):
- return "%s RENAME TO %s" % (
- alter_table(compiler, element.table_name, element.schema),
- format_table_name(compiler, element.new_table_name, element.schema)
- )
-
-@compiles(AddColumn)
-def visit_add_column(element, compiler, **kw):
- return "%s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- add_column(compiler, element.column, **kw)
- )
-
-@compiles(DropColumn)
-def visit_drop_column(element, compiler, **kw):
- return "%s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- drop_column(compiler, element.column.name, **kw)
- )
-
-@compiles(ColumnNullable)
-def visit_column_nullable(element, compiler, **kw):
- return "%s %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- alter_column(compiler, element.column_name),
- "DROP NOT NULL" if element.nullable else "SET NOT NULL"
- )
-
-@compiles(ColumnType)
-def visit_column_type(element, compiler, **kw):
- return "%s %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- alter_column(compiler, element.column_name),
- "TYPE %s" % format_type(compiler, element.type_)
- )
-
-@compiles(ColumnName)
-def visit_column_name(element, compiler, **kw):
- return "%s RENAME %s TO %s" % (
- alter_table(compiler, element.table_name, element.schema),
- format_column_name(compiler, element.column_name),
- format_column_name(compiler, element.newname)
- )
-
-@compiles(ColumnDefault)
-def visit_column_default(element, compiler, **kw):
- return "%s %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- alter_column(compiler, element.column_name),
- "SET DEFAULT %s" %
- format_server_default(compiler, element.default)
- if element.default is not None
- else "DROP DEFAULT"
- )
-
-def quote_dotted(name, quote):
- """quote the elements of a dotted name"""
-
- result = '.'.join([quote(x) for x in name.split('.')])
- return result
-
-def format_table_name(compiler, name, schema):
- quote = functools.partial(compiler.preparer.quote, force=None)
- if schema:
- return quote_dotted(schema, quote) + "." + quote(name)
- else:
- return quote(name)
-
-def format_column_name(compiler, name):
- return compiler.preparer.quote(name, None)
-
-def format_server_default(compiler, default):
- return compiler.get_column_default_string(
- Column("x", Integer, server_default=default)
- )
-
-def format_type(compiler, type_):
- return compiler.dialect.type_compiler.process(type_)
-
-def alter_table(compiler, name, schema):
- return "ALTER TABLE %s" % format_table_name(compiler, name, schema)
-
-def drop_column(compiler, name):
- return 'DROP COLUMN %s' % format_column_name(compiler, name)
-
-def alter_column(compiler, name):
- return 'ALTER COLUMN %s' % format_column_name(compiler, name)
-
-def add_column(compiler, column, **kw):
- return "ADD COLUMN %s" % compiler.get_column_specification(column, **kw)
-
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/ddl/impl.py b/Darwin/lib/python2.7/site-packages/alembic/ddl/impl.py
deleted file mode 100644
index 79cbd36..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/ddl/impl.py
+++ /dev/null
@@ -1,279 +0,0 @@
-from sqlalchemy.sql.expression import _BindParamClause
-from sqlalchemy.ext.compiler import compiles
-from sqlalchemy import schema, text
-from sqlalchemy import types as sqltypes
-
-from ..compat import string_types, text_type, with_metaclass
-from .. import util
-from . import base
-
-class ImplMeta(type):
- def __init__(cls, classname, bases, dict_):
- newtype = type.__init__(cls, classname, bases, dict_)
- if '__dialect__' in dict_:
- _impls[dict_['__dialect__']] = cls
- return newtype
-
-_impls = {}
-
-class DefaultImpl(with_metaclass(ImplMeta)):
- """Provide the entrypoint for major migration operations,
- including database-specific behavioral variances.
-
- While individual SQL/DDL constructs already provide
- for database-specific implementations, variances here
- allow for entirely different sequences of operations
- to take place for a particular migration, such as
- SQL Server's special 'IDENTITY INSERT' step for
- bulk inserts.
-
- """
- __dialect__ = 'default'
-
- transactional_ddl = False
- command_terminator = ";"
-
- def __init__(self, dialect, connection, as_sql,
- transactional_ddl, output_buffer,
- context_opts):
- self.dialect = dialect
- self.connection = connection
- self.as_sql = as_sql
- self.output_buffer = output_buffer
- self.memo = {}
- self.context_opts = context_opts
- if transactional_ddl is not None:
- self.transactional_ddl = transactional_ddl
-
- @classmethod
- def get_by_dialect(cls, dialect):
- return _impls[dialect.name]
-
- def static_output(self, text):
- self.output_buffer.write(text_type(text + "\n\n"))
- self.output_buffer.flush()
-
- @property
- def bind(self):
- return self.connection
-
- def _exec(self, construct, execution_options=None,
- multiparams=(),
- params=util.immutabledict()):
- if isinstance(construct, string_types):
- construct = text(construct)
- if self.as_sql:
- if multiparams or params:
- # TODO: coverage
- raise Exception("Execution arguments not allowed with as_sql")
- self.static_output(text_type(
- construct.compile(dialect=self.dialect)
- ).replace("\t", " ").strip() + self.command_terminator)
- else:
- conn = self.connection
- if execution_options:
- conn = conn.execution_options(**execution_options)
- conn.execute(construct, *multiparams, **params)
-
- def execute(self, sql, execution_options=None):
- self._exec(sql, execution_options)
-
- def alter_column(self, table_name, column_name,
- nullable=None,
- server_default=False,
- name=None,
- type_=None,
- schema=None,
- autoincrement=None,
- existing_type=None,
- existing_server_default=None,
- existing_nullable=None,
- existing_autoincrement=None
- ):
- if autoincrement is not None or existing_autoincrement is not None:
- util.warn("nautoincrement and existing_autoincrement only make sense for MySQL")
- if nullable is not None:
- self._exec(base.ColumnNullable(table_name, column_name,
- nullable, schema=schema,
- existing_type=existing_type,
- existing_server_default=existing_server_default,
- existing_nullable=existing_nullable,
- ))
- if server_default is not False:
- self._exec(base.ColumnDefault(
- table_name, column_name, server_default,
- schema=schema,
- existing_type=existing_type,
- existing_server_default=existing_server_default,
- existing_nullable=existing_nullable,
- ))
- if type_ is not None:
- self._exec(base.ColumnType(
- table_name, column_name, type_, schema=schema,
- existing_type=existing_type,
- existing_server_default=existing_server_default,
- existing_nullable=existing_nullable,
- ))
- # do the new name last ;)
- if name is not None:
- self._exec(base.ColumnName(
- table_name, column_name, name, schema=schema,
- existing_type=existing_type,
- existing_server_default=existing_server_default,
- existing_nullable=existing_nullable,
- ))
-
- def add_column(self, table_name, column, schema=None):
- self._exec(base.AddColumn(table_name, column, schema=schema))
-
- def drop_column(self, table_name, column, schema=None, **kw):
- self._exec(base.DropColumn(table_name, column, schema=schema))
-
- def add_constraint(self, const):
- if const._create_rule is None or \
- const._create_rule(self):
- self._exec(schema.AddConstraint(const))
-
- def drop_constraint(self, const):
- self._exec(schema.DropConstraint(const))
-
- def rename_table(self, old_table_name, new_table_name, schema=None):
- self._exec(base.RenameTable(old_table_name,
- new_table_name, schema=schema))
-
- def create_table(self, table):
- if util.sqla_07:
- table.dispatch.before_create(table, self.connection,
- checkfirst=False,
- _ddl_runner=self)
- self._exec(schema.CreateTable(table))
- if util.sqla_07:
- table.dispatch.after_create(table, self.connection,
- checkfirst=False,
- _ddl_runner=self)
- for index in table.indexes:
- self._exec(schema.CreateIndex(index))
-
- def drop_table(self, table):
- self._exec(schema.DropTable(table))
-
- def create_index(self, index):
- self._exec(schema.CreateIndex(index))
-
- def drop_index(self, index):
- self._exec(schema.DropIndex(index))
-
- def bulk_insert(self, table, rows, multiinsert=True):
- if not isinstance(rows, list):
- raise TypeError("List expected")
- elif rows and not isinstance(rows[0], dict):
- raise TypeError("List of dictionaries expected")
- if self.as_sql:
- for row in rows:
- self._exec(table.insert(inline=True).values(**dict(
- (k,
- _literal_bindparam(k, v, type_=table.c[k].type)
- if not isinstance(v, _literal_bindparam) else v)
- for k, v in row.items()
- )))
- else:
- # work around http://www.sqlalchemy.org/trac/ticket/2461
- if not hasattr(table, '_autoincrement_column'):
- table._autoincrement_column = None
- if rows:
- if multiinsert:
- self._exec(table.insert(inline=True), multiparams=rows)
- else:
- for row in rows:
- self._exec(table.insert(inline=True).values(**row))
-
- def compare_type(self, inspector_column, metadata_column):
-
- conn_type = inspector_column.type
- metadata_type = metadata_column.type
-
- metadata_impl = metadata_type.dialect_impl(self.dialect)
-
- # work around SQLAlchemy bug "stale value for type affinity"
- # fixed in 0.7.4
- metadata_impl.__dict__.pop('_type_affinity', None)
-
- if conn_type._compare_type_affinity(
- metadata_impl
- ):
- comparator = _type_comparators.get(conn_type._type_affinity, None)
-
- return comparator and comparator(metadata_type, conn_type)
- else:
- return True
-
- def compare_server_default(self, inspector_column,
- metadata_column,
- rendered_metadata_default,
- rendered_inspector_default):
- return rendered_inspector_default != rendered_metadata_default
-
- def correct_for_autogen_constraints(self, conn_uniques, conn_indexes,
- metadata_unique_constraints,
- metadata_indexes):
- pass
-
- def start_migrations(self):
- """A hook called when :meth:`.EnvironmentContext.run_migrations`
- is called.
-
- Implementations can set up per-migration-run state here.
-
- """
-
- def emit_begin(self):
- """Emit the string ``BEGIN``, or the backend-specific
- equivalent, on the current connection context.
-
- This is used in offline mode and typically
- via :meth:`.EnvironmentContext.begin_transaction`.
-
- """
- self.static_output("BEGIN" + self.command_terminator)
-
- def emit_commit(self):
- """Emit the string ``COMMIT``, or the backend-specific
- equivalent, on the current connection context.
-
- This is used in offline mode and typically
- via :meth:`.EnvironmentContext.begin_transaction`.
-
- """
- self.static_output("COMMIT" + self.command_terminator)
-
-class _literal_bindparam(_BindParamClause):
- pass
-
-@compiles(_literal_bindparam)
-def _render_literal_bindparam(element, compiler, **kw):
- return compiler.render_literal_bindparam(element, **kw)
-
-
-def _string_compare(t1, t2):
- return \
- t1.length is not None and \
- t1.length != t2.length
-
-def _numeric_compare(t1, t2):
- return \
- (
- t1.precision is not None and \
- t1.precision != t2.precision
- ) or \
- (
- t1.scale is not None and \
- t1.scale != t2.scale
- )
-_type_comparators = {
- sqltypes.String:_string_compare,
- sqltypes.Numeric:_numeric_compare
-}
-
-
-
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/ddl/mssql.py b/Darwin/lib/python2.7/site-packages/alembic/ddl/mssql.py
deleted file mode 100644
index fece08b..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/ddl/mssql.py
+++ /dev/null
@@ -1,217 +0,0 @@
-from sqlalchemy.ext.compiler import compiles
-
-from .. import util
-from .impl import DefaultImpl
-from .base import alter_table, AddColumn, ColumnName, \
- format_table_name, format_column_name, ColumnNullable, alter_column,\
- format_server_default,ColumnDefault, format_type, ColumnType
-from sqlalchemy.sql.expression import ClauseElement, Executable
-
-class MSSQLImpl(DefaultImpl):
- __dialect__ = 'mssql'
- transactional_ddl = True
- batch_separator = "GO"
-
- def __init__(self, *arg, **kw):
- super(MSSQLImpl, self).__init__(*arg, **kw)
- self.batch_separator = self.context_opts.get(
- "mssql_batch_separator",
- self.batch_separator)
-
- def _exec(self, construct, *args, **kw):
- super(MSSQLImpl, self)._exec(construct, *args, **kw)
- if self.as_sql and self.batch_separator:
- self.static_output(self.batch_separator)
-
- def emit_begin(self):
- self.static_output("BEGIN TRANSACTION" + self.command_terminator)
-
- def emit_commit(self):
- super(MSSQLImpl, self).emit_commit()
- if self.as_sql and self.batch_separator:
- self.static_output(self.batch_separator)
-
- def alter_column(self, table_name, column_name,
- nullable=None,
- server_default=False,
- name=None,
- type_=None,
- schema=None,
- autoincrement=None,
- existing_type=None,
- existing_server_default=None,
- existing_nullable=None,
- existing_autoincrement=None
- ):
-
- if nullable is not None and existing_type is None:
- if type_ is not None:
- existing_type = type_
- # the NULL/NOT NULL alter will handle
- # the type alteration
- type_ = None
- else:
- raise util.CommandError(
- "MS-SQL ALTER COLUMN operations "
- "with NULL or NOT NULL require the "
- "existing_type or a new type_ be passed.")
-
- super(MSSQLImpl, self).alter_column(
- table_name, column_name,
- nullable=nullable,
- type_=type_,
- schema=schema,
- autoincrement=autoincrement,
- existing_type=existing_type,
- existing_nullable=existing_nullable,
- existing_autoincrement=existing_autoincrement
- )
-
- if server_default is not False:
- if existing_server_default is not False or \
- server_default is None:
- self._exec(
- _ExecDropConstraint(
- table_name, column_name,
- 'sys.default_constraints')
- )
- if server_default is not None:
- super(MSSQLImpl, self).alter_column(
- table_name, column_name,
- schema=schema,
- server_default=server_default)
-
- if name is not None:
- super(MSSQLImpl, self).alter_column(
- table_name, column_name,
- schema=schema,
- name=name)
-
- def bulk_insert(self, table, rows, **kw):
- if self.as_sql:
- self._exec(
- "SET IDENTITY_INSERT %s ON" %
- self.dialect.identifier_preparer.format_table(table)
- )
- super(MSSQLImpl, self).bulk_insert(table, rows, **kw)
- self._exec(
- "SET IDENTITY_INSERT %s OFF" %
- self.dialect.identifier_preparer.format_table(table)
- )
- else:
- super(MSSQLImpl, self).bulk_insert(table, rows, **kw)
-
-
- def drop_column(self, table_name, column, **kw):
- drop_default = kw.pop('mssql_drop_default', False)
- if drop_default:
- self._exec(
- _ExecDropConstraint(
- table_name, column,
- 'sys.default_constraints')
- )
- drop_check = kw.pop('mssql_drop_check', False)
- if drop_check:
- self._exec(
- _ExecDropConstraint(
- table_name, column,
- 'sys.check_constraints')
- )
- drop_fks = kw.pop('mssql_drop_foreign_key', False)
- if drop_fks:
- self._exec(
- _ExecDropFKConstraint(table_name, column)
- )
- super(MSSQLImpl, self).drop_column(table_name, column)
-
-class _ExecDropConstraint(Executable, ClauseElement):
- def __init__(self, tname, colname, type_):
- self.tname = tname
- self.colname = colname
- self.type_ = type_
-
-class _ExecDropFKConstraint(Executable, ClauseElement):
- def __init__(self, tname, colname):
- self.tname = tname
- self.colname = colname
-
-
-@compiles(_ExecDropConstraint, 'mssql')
-def _exec_drop_col_constraint(element, compiler, **kw):
- tname, colname, type_ = element.tname, element.colname, element.type_
- # from http://www.mssqltips.com/sqlservertip/1425/working-with-default-constraints-in-sql-server/
- # TODO: needs table formatting, etc.
- return """declare @const_name varchar(256)
-select @const_name = [name] from %(type)s
-where parent_object_id = object_id('%(tname)s')
-and col_name(parent_object_id, parent_column_id) = '%(colname)s'
-exec('alter table %(tname_quoted)s drop constraint ' + @const_name)""" % {
- 'type': type_,
- 'tname': tname,
- 'colname': colname,
- 'tname_quoted': format_table_name(compiler, tname, None),
- }
-
-@compiles(_ExecDropFKConstraint, 'mssql')
-def _exec_drop_col_fk_constraint(element, compiler, **kw):
- tname, colname = element.tname, element.colname
-
- return """declare @const_name varchar(256)
-select @const_name = [name] from
- sys.foreign_keys fk join sys.foreign_key_columns fkc
- on fk.object_id=fkc.constraint_object_id
-where fkc.parent_object_id = object_id('%(tname)s')
-and col_name(fkc.parent_object_id, fkc.parent_column_id) = '%(colname)s'
-exec('alter table %(tname_quoted)s drop constraint ' + @const_name)""" % {
- 'tname': tname,
- 'colname': colname,
- 'tname_quoted': format_table_name(compiler, tname, None),
- }
-
-
-
-@compiles(AddColumn, 'mssql')
-def visit_add_column(element, compiler, **kw):
- return "%s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- mssql_add_column(compiler, element.column, **kw)
- )
-
-def mssql_add_column(compiler, column, **kw):
- return "ADD %s" % compiler.get_column_specification(column, **kw)
-
-@compiles(ColumnNullable, 'mssql')
-def visit_column_nullable(element, compiler, **kw):
- return "%s %s %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- alter_column(compiler, element.column_name),
- format_type(compiler, element.existing_type),
- "NULL" if element.nullable else "NOT NULL"
- )
-
-@compiles(ColumnDefault, 'mssql')
-def visit_column_default(element, compiler, **kw):
- # TODO: there can also be a named constraint
- # with ADD CONSTRAINT here
- return "%s ADD DEFAULT %s FOR %s" % (
- alter_table(compiler, element.table_name, element.schema),
- format_server_default(compiler, element.default),
- format_column_name(compiler, element.column_name)
- )
-
-@compiles(ColumnName, 'mssql')
-def visit_rename_column(element, compiler, **kw):
- return "EXEC sp_rename '%s.%s', %s, 'COLUMN'" % (
- format_table_name(compiler, element.table_name, element.schema),
- format_column_name(compiler, element.column_name),
- format_column_name(compiler, element.newname)
- )
-
-@compiles(ColumnType, 'mssql')
-def visit_column_type(element, compiler, **kw):
- return "%s %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- alter_column(compiler, element.column_name),
- format_type(compiler, element.type_)
- )
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/ddl/mysql.py b/Darwin/lib/python2.7/site-packages/alembic/ddl/mysql.py
deleted file mode 100644
index 96f42f3..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/ddl/mysql.py
+++ /dev/null
@@ -1,212 +0,0 @@
-from sqlalchemy.ext.compiler import compiles
-from sqlalchemy import types as sqltypes
-from sqlalchemy import schema
-
-from ..compat import string_types
-from .. import util
-from .impl import DefaultImpl
-from .base import ColumnNullable, ColumnName, ColumnDefault, \
- ColumnType, AlterColumn, format_column_name, \
- format_server_default
-from .base import alter_table
-
-class MySQLImpl(DefaultImpl):
- __dialect__ = 'mysql'
-
- transactional_ddl = False
-
- def alter_column(self, table_name, column_name,
- nullable=None,
- server_default=False,
- name=None,
- type_=None,
- schema=None,
- autoincrement=None,
- existing_type=None,
- existing_server_default=None,
- existing_nullable=None,
- existing_autoincrement=None
- ):
- if name is not None:
- self._exec(
- MySQLChangeColumn(
- table_name, column_name,
- schema=schema,
- newname=name,
- nullable=nullable if nullable is not None else
- existing_nullable
- if existing_nullable is not None
- else True,
- type_=type_ if type_ is not None else existing_type,
- default=server_default if server_default is not False
- else existing_server_default,
- autoincrement=autoincrement if autoincrement is not None
- else existing_autoincrement
- )
- )
- elif nullable is not None or \
- type_ is not None or \
- autoincrement is not None:
- self._exec(
- MySQLModifyColumn(
- table_name, column_name,
- schema=schema,
- newname=name if name is not None else column_name,
- nullable=nullable if nullable is not None else
- existing_nullable
- if existing_nullable is not None
- else True,
- type_=type_ if type_ is not None else existing_type,
- default=server_default if server_default is not False
- else existing_server_default,
- autoincrement=autoincrement if autoincrement is not None
- else existing_autoincrement
- )
- )
- elif server_default is not False:
- self._exec(
- MySQLAlterDefault(
- table_name, column_name, server_default,
- schema=schema,
- )
- )
-
- def correct_for_autogen_constraints(self, conn_unique_constraints,
- conn_indexes,
- metadata_unique_constraints,
- metadata_indexes):
- removed = set()
- for idx in list(conn_indexes):
- # MySQL puts implicit indexes on FK columns, even if
- # composite and even if MyISAM, so can't check this too easily
- if idx.name == idx.columns.keys()[0]:
- conn_indexes.remove(idx)
- removed.add(idx.name)
-
- # then remove indexes from the "metadata_indexes"
- # that we've removed from reflected, otherwise they come out
- # as adds (see #202)
- for idx in list(metadata_indexes):
- if idx.name in removed:
- metadata_indexes.remove(idx)
-
-class MySQLAlterDefault(AlterColumn):
- def __init__(self, name, column_name, default, schema=None):
- super(AlterColumn, self).__init__(name, schema=schema)
- self.column_name = column_name
- self.default = default
-
-
-class MySQLChangeColumn(AlterColumn):
- def __init__(self, name, column_name, schema=None,
- newname=None,
- type_=None,
- nullable=None,
- default=False,
- autoincrement=None):
- super(AlterColumn, self).__init__(name, schema=schema)
- self.column_name = column_name
- self.nullable = nullable
- self.newname = newname
- self.default = default
- self.autoincrement = autoincrement
- if type_ is None:
- raise util.CommandError(
- "All MySQL CHANGE/MODIFY COLUMN operations "
- "require the existing type."
- )
-
- self.type_ = sqltypes.to_instance(type_)
-
-class MySQLModifyColumn(MySQLChangeColumn):
- pass
-
-
-@compiles(ColumnNullable, 'mysql')
-@compiles(ColumnName, 'mysql')
-@compiles(ColumnDefault, 'mysql')
-@compiles(ColumnType, 'mysql')
-def _mysql_doesnt_support_individual(element, compiler, **kw):
- raise NotImplementedError(
- "Individual alter column constructs not supported by MySQL"
- )
-
-
-@compiles(MySQLAlterDefault, "mysql")
-def _mysql_alter_default(element, compiler, **kw):
- return "%s ALTER COLUMN %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- format_column_name(compiler, element.column_name),
- "SET DEFAULT %s" % format_server_default(compiler, element.default)
- if element.default is not None
- else "DROP DEFAULT"
- )
-
-@compiles(MySQLModifyColumn, "mysql")
-def _mysql_modify_column(element, compiler, **kw):
- return "%s MODIFY %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- format_column_name(compiler, element.column_name),
- _mysql_colspec(
- compiler,
- nullable=element.nullable,
- server_default=element.default,
- type_=element.type_,
- autoincrement=element.autoincrement
- ),
- )
-
-
-@compiles(MySQLChangeColumn, "mysql")
-def _mysql_change_column(element, compiler, **kw):
- return "%s CHANGE %s %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- format_column_name(compiler, element.column_name),
- format_column_name(compiler, element.newname),
- _mysql_colspec(
- compiler,
- nullable=element.nullable,
- server_default=element.default,
- type_=element.type_,
- autoincrement=element.autoincrement
- ),
- )
-
-def _render_value(compiler, expr):
- if isinstance(expr, string_types):
- return "'%s'" % expr
- else:
- return compiler.sql_compiler.process(expr)
-
-def _mysql_colspec(compiler, nullable, server_default, type_,
- autoincrement):
- spec = "%s %s" % (
- compiler.dialect.type_compiler.process(type_),
- "NULL" if nullable else "NOT NULL"
- )
- if autoincrement:
- spec += " AUTO_INCREMENT"
- if server_default is not False and server_default is not None:
- spec += " DEFAULT %s" % _render_value(compiler, server_default)
-
- return spec
-
-@compiles(schema.DropConstraint, "mysql")
-def _mysql_drop_constraint(element, compiler, **kw):
- """Redefine SQLAlchemy's drop constraint to
- raise errors for invalid constraint type."""
-
- constraint = element.element
- if isinstance(constraint, (schema.ForeignKeyConstraint,
- schema.PrimaryKeyConstraint,
- schema.UniqueConstraint)
- ):
- return compiler.visit_drop_constraint(element, **kw)
- elif isinstance(constraint, schema.CheckConstraint):
- raise NotImplementedError(
- "MySQL does not support CHECK constraints.")
- else:
- raise NotImplementedError(
- "No generic 'DROP CONSTRAINT' in MySQL - "
- "please specify constraint type")
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/ddl/oracle.py b/Darwin/lib/python2.7/site-packages/alembic/ddl/oracle.py
deleted file mode 100644
index 28eb246..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/ddl/oracle.py
+++ /dev/null
@@ -1,77 +0,0 @@
-from sqlalchemy.ext.compiler import compiles
-
-from .impl import DefaultImpl
-from .base import alter_table, AddColumn, ColumnName, \
- format_column_name, ColumnNullable, \
- format_server_default,ColumnDefault, format_type, ColumnType
-
-class OracleImpl(DefaultImpl):
- __dialect__ = 'oracle'
- transactional_ddl = True
- batch_separator = "/"
- command_terminator = ""
-
- def __init__(self, *arg, **kw):
- super(OracleImpl, self).__init__(*arg, **kw)
- self.batch_separator = self.context_opts.get(
- "oracle_batch_separator",
- self.batch_separator)
-
- def _exec(self, construct, *args, **kw):
- super(OracleImpl, self)._exec(construct, *args, **kw)
- if self.as_sql and self.batch_separator:
- self.static_output(self.batch_separator)
-
- def emit_begin(self):
- self._exec("SET TRANSACTION READ WRITE")
-
- def emit_commit(self):
- self._exec("COMMIT")
-
-@compiles(AddColumn, 'oracle')
-def visit_add_column(element, compiler, **kw):
- return "%s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- add_column(compiler, element.column, **kw),
- )
-
-@compiles(ColumnNullable, 'oracle')
-def visit_column_nullable(element, compiler, **kw):
- return "%s %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- alter_column(compiler, element.column_name),
- "NULL" if element.nullable else "NOT NULL"
- )
-
-@compiles(ColumnType, 'oracle')
-def visit_column_type(element, compiler, **kw):
- return "%s %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- alter_column(compiler, element.column_name),
- "%s" % format_type(compiler, element.type_)
- )
-
-@compiles(ColumnName, 'oracle')
-def visit_column_name(element, compiler, **kw):
- return "%s RENAME COLUMN %s TO %s" % (
- alter_table(compiler, element.table_name, element.schema),
- format_column_name(compiler, element.column_name),
- format_column_name(compiler, element.newname)
- )
-
-@compiles(ColumnDefault, 'oracle')
-def visit_column_default(element, compiler, **kw):
- return "%s %s %s" % (
- alter_table(compiler, element.table_name, element.schema),
- alter_column(compiler, element.column_name),
- "DEFAULT %s" %
- format_server_default(compiler, element.default)
- if element.default is not None
- else "DEFAULT NULL"
- )
-
-def alter_column(compiler, name):
- return 'MODIFY %s' % format_column_name(compiler, name)
-
-def add_column(compiler, column, **kw):
- return "ADD %s" % compiler.get_column_specification(column, **kw)
diff --git a/Darwin/lib/python2.7/site-packages/alembic/ddl/postgresql.py b/Darwin/lib/python2.7/site-packages/alembic/ddl/postgresql.py
deleted file mode 100644
index 5ca0d1f..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/ddl/postgresql.py
+++ /dev/null
@@ -1,43 +0,0 @@
-import re
-
-from sqlalchemy import types as sqltypes
-
-from .base import compiles, alter_table, format_table_name, RenameTable
-from .impl import DefaultImpl
-
-class PostgresqlImpl(DefaultImpl):
- __dialect__ = 'postgresql'
- transactional_ddl = True
-
- def compare_server_default(self, inspector_column,
- metadata_column,
- rendered_metadata_default,
- rendered_inspector_default):
-
- # don't do defaults for SERIAL columns
- if metadata_column.primary_key and \
- metadata_column is metadata_column.table._autoincrement_column:
- return False
-
- conn_col_default = rendered_inspector_default
-
- if None in (conn_col_default, rendered_metadata_default):
- return conn_col_default != rendered_metadata_default
-
- if metadata_column.type._type_affinity is not sqltypes.String:
- rendered_metadata_default = re.sub(r"^'|'$", "", rendered_metadata_default)
-
- return not self.connection.scalar(
- "SELECT %s = %s" % (
- conn_col_default,
- rendered_metadata_default
- )
- )
-
-
-@compiles(RenameTable, "postgresql")
-def visit_rename_table(element, compiler, **kw):
- return "%s RENAME TO %s" % (
- alter_table(compiler, element.table_name, element.schema),
- format_table_name(compiler, element.new_table_name, None)
- )
diff --git a/Darwin/lib/python2.7/site-packages/alembic/ddl/sqlite.py b/Darwin/lib/python2.7/site-packages/alembic/ddl/sqlite.py
deleted file mode 100644
index a3c73ce..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/ddl/sqlite.py
+++ /dev/null
@@ -1,73 +0,0 @@
-from .. import util
-from .impl import DefaultImpl
-
-#from sqlalchemy.ext.compiler import compiles
-#from .base import AddColumn, alter_table
-#from sqlalchemy.schema import AddConstraint
-
-class SQLiteImpl(DefaultImpl):
- __dialect__ = 'sqlite'
-
- transactional_ddl = False
- """SQLite supports transactional DDL, but pysqlite does not:
- see: http://bugs.python.org/issue10740
- """
-
- def add_constraint(self, const):
- # attempt to distinguish between an
- # auto-gen constraint and an explicit one
- if const._create_rule is None:
- raise NotImplementedError(
- "No support for ALTER of constraints in SQLite dialect")
- elif const._create_rule(self):
- util.warn("Skipping unsupported ALTER for "
- "creation of implicit constraint")
-
-
- def drop_constraint(self, const):
- if const._create_rule is None:
- raise NotImplementedError(
- "No support for ALTER of constraints in SQLite dialect")
-
- def correct_for_autogen_constraints(self, conn_unique_constraints, conn_indexes,
- metadata_unique_constraints,
- metadata_indexes):
-
- def uq_sig(uq):
- return tuple(sorted(uq.columns.keys()))
-
- conn_unique_sigs = set(
- uq_sig(uq)
- for uq in conn_unique_constraints
- )
-
- for idx in list(metadata_unique_constraints):
- # SQLite backend can't report on unnamed UNIQUE constraints,
- # so remove these, unless we see an exact signature match
- if idx.name is None and uq_sig(idx) not in conn_unique_sigs:
- metadata_unique_constraints.remove(idx)
-
- for idx in list(conn_unique_constraints):
- # just in case we fix the backend such that it does report
- # on them, blow them out of the reflected collection too otherwise
- # they will come up as removed. if the backend supports this now,
- # add a version check here for the dialect.
- if idx.name is None:
- conn_uniques.remove(idx)
-
-#@compiles(AddColumn, 'sqlite')
-#def visit_add_column(element, compiler, **kw):
-# return "%s %s" % (
-# alter_table(compiler, element.table_name, element.schema),
-# add_column(compiler, element.column, **kw)
-# )
-
-
-#def add_column(compiler, column, **kw):
-# text = "ADD COLUMN %s" % compiler.get_column_specification(column, **kw)
-# # need to modify SQLAlchemy so that the CHECK associated with a Boolean
-# # or Enum gets placed as part of the column constraints, not the Table
-# # see ticket 98
-# for const in column.constraints:
-# text += compiler.process(AddConstraint(const))
-# return text
diff --git a/Darwin/lib/python2.7/site-packages/alembic/environment.py b/Darwin/lib/python2.7/site-packages/alembic/environment.py
deleted file mode 100644
index f8875a2..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/environment.py
+++ /dev/null
@@ -1,791 +0,0 @@
-from .operations import Operations
-from .migration import MigrationContext
-from . import util
-
-class EnvironmentContext(object):
- """Represent the state made available to an ``env.py`` script.
-
- :class:`.EnvironmentContext` is normally instantiated
- by the commands present in the :mod:`alembic.command`
- module. From within an ``env.py`` script, the current
- :class:`.EnvironmentContext` is available via the
- ``alembic.context`` datamember.
-
- :class:`.EnvironmentContext` is also a Python context
- manager, that is, is intended to be used using the
- ``with:`` statement. A typical use of :class:`.EnvironmentContext`::
-
- from alembic.config import Config
- from alembic.script import ScriptDirectory
-
- config = Config()
- config.set_main_option("script_location", "myapp:migrations")
- script = ScriptDirectory.from_config(config)
-
- def my_function(rev, context):
- '''do something with revision "rev", which
- will be the current database revision,
- and "context", which is the MigrationContext
- that the env.py will create'''
-
- with EnvironmentContext(
- config,
- script,
- fn = my_function,
- as_sql = False,
- starting_rev = 'base',
- destination_rev = 'head',
- tag = "sometag"
- ):
- script.run_env()
-
- The above script will invoke the ``env.py`` script
- within the migration environment. If and when ``env.py``
- calls :meth:`.MigrationContext.run_migrations`, the
- ``my_function()`` function above will be called
- by the :class:`.MigrationContext`, given the context
- itself as well as the current revision in the database.
-
- .. note::
-
- For most API usages other than full blown
- invocation of migration scripts, the :class:`.MigrationContext`
- and :class:`.ScriptDirectory` objects can be created and
- used directly. The :class:`.EnvironmentContext` object
- is *only* needed when you need to actually invoke the
- ``env.py`` module present in the migration environment.
-
- """
-
- _migration_context = None
-
- config = None
- """An instance of :class:`.Config` representing the
- configuration file contents as well as other variables
- set programmatically within it."""
-
- script = None
- """An instance of :class:`.ScriptDirectory` which provides
- programmatic access to version files within the ``versions/``
- directory.
-
- """
-
- def __init__(self, config, script, **kw):
- """Construct a new :class:`.EnvironmentContext`.
-
- :param config: a :class:`.Config` instance.
- :param script: a :class:`.ScriptDirectory` instance.
- :param \**kw: keyword options that will be ultimately
- passed along to the :class:`.MigrationContext` when
- :meth:`.EnvironmentContext.configure` is called.
-
- """
- self.config = config
- self.script = script
- self.context_opts = kw
-
- def __enter__(self):
- """Establish a context which provides a
- :class:`.EnvironmentContext` object to
- env.py scripts.
-
- The :class:`.EnvironmentContext` will
- be made available as ``from alembic import context``.
-
- """
- from .context import _install_proxy
- _install_proxy(self)
- return self
-
- def __exit__(self, *arg, **kw):
- from . import context, op
- context._remove_proxy()
- op._remove_proxy()
-
- def is_offline_mode(self):
- """Return True if the current migrations environment
- is running in "offline mode".
-
- This is ``True`` or ``False`` depending
- on the the ``--sql`` flag passed.
-
- This function does not require that the :class:`.MigrationContext`
- has been configured.
-
- """
- return self.context_opts.get('as_sql', False)
-
- def is_transactional_ddl(self):
- """Return True if the context is configured to expect a
- transactional DDL capable backend.
-
- This defaults to the type of database in use, and
- can be overridden by the ``transactional_ddl`` argument
- to :meth:`.configure`
-
- This function requires that a :class:`.MigrationContext`
- has first been made available via :meth:`.configure`.
-
- """
- return self.get_context().impl.transactional_ddl
-
- def requires_connection(self):
- return not self.is_offline_mode()
-
- def get_head_revision(self):
- """Return the hex identifier of the 'head' revision.
-
- This function does not require that the :class:`.MigrationContext`
- has been configured.
-
- """
- return self.script._as_rev_number("head")
-
- def get_starting_revision_argument(self):
- """Return the 'starting revision' argument,
- if the revision was passed using ``start:end``.
-
- This is only meaningful in "offline" mode.
- Returns ``None`` if no value is available
- or was configured.
-
- This function does not require that the :class:`.MigrationContext`
- has been configured.
-
- """
- if self._migration_context is not None:
- return self.script._as_rev_number(
- self.get_context()._start_from_rev)
- elif 'starting_rev' in self.context_opts:
- return self.script._as_rev_number(
- self.context_opts['starting_rev'])
- else:
- raise util.CommandError(
- "No starting revision argument is available.")
-
- def get_revision_argument(self):
- """Get the 'destination' revision argument.
-
- This is typically the argument passed to the
- ``upgrade`` or ``downgrade`` command.
-
- If it was specified as ``head``, the actual
- version number is returned; if specified
- as ``base``, ``None`` is returned.
-
- This function does not require that the :class:`.MigrationContext`
- has been configured.
-
- """
- return self.script._as_rev_number(
- self.context_opts['destination_rev'])
-
- def get_tag_argument(self):
- """Return the value passed for the ``--tag`` argument, if any.
-
- The ``--tag`` argument is not used directly by Alembic,
- but is available for custom ``env.py`` configurations that
- wish to use it; particularly for offline generation scripts
- that wish to generate tagged filenames.
-
- This function does not require that the :class:`.MigrationContext`
- has been configured.
-
- .. seealso::
-
- :meth:`.EnvironmentContext.get_x_argument` - a newer and more
- open ended system of extending ``env.py`` scripts via the command
- line.
-
- """
- return self.context_opts.get('tag', None)
-
- def get_x_argument(self, as_dictionary=False):
- """Return the value(s) passed for the ``-x`` argument, if any.
-
- The ``-x`` argument is an open ended flag that allows any user-defined
- value or values to be passed on the command line, then available
- here for consumption by a custom ``env.py`` script.
-
- The return value is a list, returned directly from the ``argparse``
- structure. If ``as_dictionary=True`` is passed, the ``x`` arguments
- are parsed using ``key=value`` format into a dictionary that is
- then returned.
-
- For example, to support passing a database URL on the command line,
- the standard ``env.py`` script can be modified like this::
-
- cmd_line_url = context.get_x_argument(as_dictionary=True).get('dbname')
- if cmd_line_url:
- engine = create_engine(cmd_line_url)
- else:
- engine = engine_from_config(
- config.get_section(config.config_ini_section),
- prefix='sqlalchemy.',
- poolclass=pool.NullPool)
-
- This then takes effect by running the ``alembic`` script as::
-
- alembic -x dbname=postgresql://user:pass@host/dbname upgrade head
-
- This function does not require that the :class:`.MigrationContext`
- has been configured.
-
- .. versionadded:: 0.6.0
-
- .. seealso::
-
- :meth:`.EnvironmentContext.get_tag_argument`
-
- :attr:`.Config.cmd_opts`
-
- """
- if self.config.cmd_opts is not None:
- value = self.config.cmd_opts.x or []
- else:
- value = []
- if as_dictionary:
- value = dict(
- arg.split('=', 1) for arg in value
- )
- return value
-
- def configure(self,
- connection=None,
- url=None,
- dialect_name=None,
- transactional_ddl=None,
- transaction_per_migration=False,
- output_buffer=None,
- starting_rev=None,
- tag=None,
- template_args=None,
- target_metadata=None,
- include_symbol=None,
- include_object=None,
- include_schemas=False,
- compare_type=False,
- compare_server_default=False,
- render_item=None,
- upgrade_token="upgrades",
- downgrade_token="downgrades",
- alembic_module_prefix="op.",
- sqlalchemy_module_prefix="sa.",
- user_module_prefix=None,
- **kw
- ):
- """Configure a :class:`.MigrationContext` within this
- :class:`.EnvironmentContext` which will provide database
- connectivity and other configuration to a series of
- migration scripts.
-
- Many methods on :class:`.EnvironmentContext` require that
- this method has been called in order to function, as they
- ultimately need to have database access or at least access
- to the dialect in use. Those which do are documented as such.
-
- The important thing needed by :meth:`.configure` is a
- means to determine what kind of database dialect is in use.
- An actual connection to that database is needed only if
- the :class:`.MigrationContext` is to be used in
- "online" mode.
-
- If the :meth:`.is_offline_mode` function returns ``True``,
- then no connection is needed here. Otherwise, the
- ``connection`` parameter should be present as an
- instance of :class:`sqlalchemy.engine.Connection`.
-
- This function is typically called from the ``env.py``
- script within a migration environment. It can be called
- multiple times for an invocation. The most recent
- :class:`~sqlalchemy.engine.Connection`
- for which it was called is the one that will be operated upon
- by the next call to :meth:`.run_migrations`.
-
- General parameters:
-
- :param connection: a :class:`~sqlalchemy.engine.Connection`
- to use
- for SQL execution in "online" mode. When present, is also
- used to determine the type of dialect in use.
- :param url: a string database url, or a
- :class:`sqlalchemy.engine.url.URL` object.
- The type of dialect to be used will be derived from this if
- ``connection`` is not passed.
- :param dialect_name: string name of a dialect, such as
- "postgresql", "mssql", etc.
- The type of dialect to be used will be derived from this if
- ``connection`` and ``url`` are not passed.
- :param transactional_ddl: Force the usage of "transactional"
- DDL on or off;
- this otherwise defaults to whether or not the dialect in
- use supports it.
- :param transaction_per_migration: if True, nest each migration script
- in a transaction rather than the full series of migrations to
- run.
-
- .. versionadded:: 0.6.5
-
- :param output_buffer: a file-like object that will be used
- for textual output
- when the ``--sql`` option is used to generate SQL scripts.
- Defaults to
- ``sys.stdout`` if not passed here and also not present on
- the :class:`.Config`
- object. The value here overrides that of the :class:`.Config`
- object.
- :param output_encoding: when using ``--sql`` to generate SQL
- scripts, apply this encoding to the string output.
-
- .. versionadded:: 0.5.0
-
- :param starting_rev: Override the "starting revision" argument
- when using ``--sql`` mode.
- :param tag: a string tag for usage by custom ``env.py`` scripts.
- Set via the ``--tag`` option, can be overridden here.
- :param template_args: dictionary of template arguments which
- will be added to the template argument environment when
- running the "revision" command. Note that the script environment
- is only run within the "revision" command if the --autogenerate
- option is used, or if the option "revision_environment=true"
- is present in the alembic.ini file.
-
- .. versionadded:: 0.3.3
-
- :param version_table: The name of the Alembic version table.
- The default is ``'alembic_version'``.
- :param version_table_schema: Optional schema to place version
- table within.
-
- .. versionadded:: 0.5.0
-
- Parameters specific to the autogenerate feature, when
- ``alembic revision`` is run with the ``--autogenerate`` feature:
-
- :param target_metadata: a :class:`sqlalchemy.schema.MetaData`
- object that
- will be consulted during autogeneration. The tables present
- will be compared against
- what is locally available on the target
- :class:`~sqlalchemy.engine.Connection`
- to produce candidate upgrade/downgrade operations.
-
- :param compare_type: Indicates type comparison behavior during
- an autogenerate
- operation. Defaults to ``False`` which disables type
- comparison. Set to
- ``True`` to turn on default type comparison, which has varied
- accuracy depending on backend.
-
- To customize type comparison behavior, a callable may be
- specified which
- can filter type comparisons during an autogenerate operation.
- The format of this callable is::
-
- def my_compare_type(context, inspected_column,
- metadata_column, inspected_type, metadata_type):
- # return True if the types are different,
- # False if not, or None to allow the default implementation
- # to compare these types
- return None
-
- context.configure(
- # ...
- compare_type = my_compare_type
- )
-
-
- ``inspected_column`` is a :class:`sqlalchemy.schema.Column` as returned by
- :meth:`sqlalchemy.engine.reflection.Inspector.reflecttable`, whereas
- ``metadata_column`` is a :class:`sqlalchemy.schema.Column` from
- the local model environment.
-
- A return value of ``None`` indicates to allow default type
- comparison to proceed.
-
- .. seealso::
-
- :paramref:`.EnvironmentContext.configure.compare_server_default`
-
- :param compare_server_default: Indicates server default comparison
- behavior during
- an autogenerate operation. Defaults to ``False`` which disables
- server default
- comparison. Set to ``True`` to turn on server default comparison,
- which has
- varied accuracy depending on backend.
-
- To customize server default comparison behavior, a callable may
- be specified
- which can filter server default comparisons during an
- autogenerate operation.
- defaults during an autogenerate operation. The format of this
- callable is::
-
- def my_compare_server_default(context, inspected_column,
- metadata_column, inspected_default, metadata_default,
- rendered_metadata_default):
- # return True if the defaults are different,
- # False if not, or None to allow the default implementation
- # to compare these defaults
- return None
-
- context.configure(
- # ...
- compare_server_default = my_compare_server_default
- )
-
- ``inspected_column`` is a dictionary structure as returned by
- :meth:`sqlalchemy.engine.reflection.Inspector.get_columns`, whereas
- ``metadata_column`` is a :class:`sqlalchemy.schema.Column` from
- the local model environment.
-
- A return value of ``None`` indicates to allow default server default
- comparison
- to proceed. Note that some backends such as Postgresql actually
- execute
- the two defaults on the database side to compare for equivalence.
-
- .. seealso::
-
- :paramref:`.EnvironmentContext.configure.compare_type`
-
- :param include_object: A callable function which is given
- the chance to return ``True`` or ``False`` for any object,
- indicating if the given object should be considered in the
- autogenerate sweep.
-
- The function accepts the following positional arguments:
-
- * ``object``: a :class:`~sqlalchemy.schema.SchemaItem` object such as a
- :class:`~sqlalchemy.schema.Table` or :class:`~sqlalchemy.schema.Column`
- object
- * ``name``: the name of the object. This is typically available
- via ``object.name``.
- * ``type``: a string describing the type of object; currently
- ``"table"`` or ``"column"``
- * ``reflected``: ``True`` if the given object was produced based on
- table reflection, ``False`` if it's from a local :class:`.MetaData`
- object.
- * ``compare_to``: the object being compared against, if available,
- else ``None``.
-
- E.g.::
-
- def include_object(object, name, type_, reflected, compare_to):
- if (type_ == "column" and
- not reflected and
- object.info.get("skip_autogenerate", False)):
- return False
- else:
- return True
-
- context.configure(
- # ...
- include_object = include_object
- )
-
- :paramref:`.EnvironmentContext.configure.include_object` can also
- be used to filter on specific schemas to include or omit, when
- the :paramref:`.EnvironmentContext.configure.include_schemas`
- flag is set to ``True``. The :attr:`.Table.schema` attribute
- on each :class:`.Table` object reflected will indicate the name of the
- schema from which the :class:`.Table` originates.
-
- .. versionadded:: 0.6.0
-
- .. seealso::
-
- :paramref:`.EnvironmentContext.configure.include_schemas`
-
- :param include_symbol: A callable function which, given a table name
- and schema name (may be ``None``), returns ``True`` or ``False``, indicating
- if the given table should be considered in the autogenerate sweep.
-
- .. deprecated:: 0.6.0 :paramref:`.EnvironmentContext.configure.include_symbol`
- is superceded by the more generic
- :paramref:`.EnvironmentContext.configure.include_object`
- parameter.
-
- E.g.::
-
- def include_symbol(tablename, schema):
- return tablename not in ("skip_table_one", "skip_table_two")
-
- context.configure(
- # ...
- include_symbol = include_symbol
- )
-
- .. seealso::
-
- :paramref:`.EnvironmentContext.configure.include_schemas`
-
- :paramref:`.EnvironmentContext.configure.include_object`
-
- :param include_schemas: If True, autogenerate will scan across
- all schemas located by the SQLAlchemy
- :meth:`~sqlalchemy.engine.reflection.Inspector.get_schema_names`
- method, and include all differences in tables found across all
- those schemas. When using this option, you may want to also
- use the :paramref:`.EnvironmentContext.configure.include_object`
- option to specify a callable which
- can filter the tables/schemas that get included.
-
- .. versionadded :: 0.4.0
-
- .. seealso::
-
- :paramref:`.EnvironmentContext.configure.include_object`
-
- :param render_item: Callable that can be used to override how
- any schema item, i.e. column, constraint, type,
- etc., is rendered for autogenerate. The callable receives a
- string describing the type of object, the object, and
- the autogen context. If it returns False, the
- default rendering method will be used. If it returns None,
- the item will not be rendered in the context of a Table
- construct, that is, can be used to skip columns or constraints
- within op.create_table()::
-
- def my_render_column(type_, col, autogen_context):
- if type_ == "column" and isinstance(col, MySpecialCol):
- return repr(col)
- else:
- return False
-
- context.configure(
- # ...
- render_item = my_render_column
- )
-
- Available values for the type string include: ``"column"``,
- ``"primary_key"``, ``"foreign_key"``, ``"unique"``, ``"check"``,
- ``"type"``, ``"server_default"``.
-
- .. versionadded:: 0.5.0
-
- .. seealso::
-
- :ref:`autogen_render_types`
-
- :param upgrade_token: When autogenerate completes, the text of the
- candidate upgrade operations will be present in this template
- variable when ``script.py.mako`` is rendered. Defaults to
- ``upgrades``.
- :param downgrade_token: When autogenerate completes, the text of the
- candidate downgrade operations will be present in this
- template variable when ``script.py.mako`` is rendered. Defaults to
- ``downgrades``.
-
- :param alembic_module_prefix: When autogenerate refers to Alembic
- :mod:`alembic.operations` constructs, this prefix will be used
- (i.e. ``op.create_table``) Defaults to "``op.``".
- Can be ``None`` to indicate no prefix.
-
- :param sqlalchemy_module_prefix: When autogenerate refers to
- SQLAlchemy
- :class:`~sqlalchemy.schema.Column` or type classes, this prefix
- will be used
- (i.e. ``sa.Column("somename", sa.Integer)``) Defaults to "``sa.``".
- Can be ``None`` to indicate no prefix.
- Note that when dialect-specific types are rendered, autogenerate
- will render them using the dialect module name, i.e. ``mssql.BIT()``,
- ``postgresql.UUID()``.
-
- :param user_module_prefix: When autogenerate refers to a SQLAlchemy
- type (e.g. :class:`.TypeEngine`) where the module name is not
- under the ``sqlalchemy`` namespace, this prefix will be used
- within autogenerate, if non-``None``; if left at its default of
- ``None``, the
- :paramref:`.EnvironmentContext.configure.sqlalchemy_module_prefix`
- is used instead.
-
- .. versionadded:: 0.6.3 added
- :paramref:`.EnvironmentContext.configure.user_module_prefix`
-
- .. seealso::
-
- :ref:`autogen_module_prefix`
-
- Parameters specific to individual backends:
-
- :param mssql_batch_separator: The "batch separator" which will
- be placed between each statement when generating offline SQL Server
- migrations. Defaults to ``GO``. Note this is in addition to the
- customary semicolon ``;`` at the end of each statement; SQL Server
- considers the "batch separator" to denote the end of an
- individual statement execution, and cannot group certain
- dependent operations in one step.
- :param oracle_batch_separator: The "batch separator" which will
- be placed between each statement when generating offline
- Oracle migrations. Defaults to ``/``. Oracle doesn't add a
- semicolon between statements like most other backends.
-
- """
- opts = self.context_opts
- if transactional_ddl is not None:
- opts["transactional_ddl"] = transactional_ddl
- if output_buffer is not None:
- opts["output_buffer"] = output_buffer
- elif self.config.output_buffer is not None:
- opts["output_buffer"] = self.config.output_buffer
- if starting_rev:
- opts['starting_rev'] = starting_rev
- if tag:
- opts['tag'] = tag
- if template_args and 'template_args' in opts:
- opts['template_args'].update(template_args)
- opts["transaction_per_migration"] = transaction_per_migration
- opts['target_metadata'] = target_metadata
- opts['include_symbol'] = include_symbol
- opts['include_object'] = include_object
- opts['include_schemas'] = include_schemas
- opts['upgrade_token'] = upgrade_token
- opts['downgrade_token'] = downgrade_token
- opts['sqlalchemy_module_prefix'] = sqlalchemy_module_prefix
- opts['alembic_module_prefix'] = alembic_module_prefix
- opts['user_module_prefix'] = user_module_prefix
- if render_item is not None:
- opts['render_item'] = render_item
- if compare_type is not None:
- opts['compare_type'] = compare_type
- if compare_server_default is not None:
- opts['compare_server_default'] = compare_server_default
- opts['script'] = self.script
-
- opts.update(kw)
-
- self._migration_context = MigrationContext.configure(
- connection=connection,
- url=url,
- dialect_name=dialect_name,
- opts=opts
- )
-
- def run_migrations(self, **kw):
- """Run migrations as determined by the current command line
- configuration
- as well as versioning information present (or not) in the current
- database connection (if one is present).
-
- The function accepts optional ``**kw`` arguments. If these are
- passed, they are sent directly to the ``upgrade()`` and
- ``downgrade()``
- functions within each target revision file. By modifying the
- ``script.py.mako`` file so that the ``upgrade()`` and ``downgrade()``
- functions accept arguments, parameters can be passed here so that
- contextual information, usually information to identify a particular
- database in use, can be passed from a custom ``env.py`` script
- to the migration functions.
-
- This function requires that a :class:`.MigrationContext` has
- first been made available via :meth:`.configure`.
-
- """
- with Operations.context(self._migration_context):
- self.get_context().run_migrations(**kw)
-
- def execute(self, sql, execution_options=None):
- """Execute the given SQL using the current change context.
-
- The behavior of :meth:`.execute` is the same
- as that of :meth:`.Operations.execute`. Please see that
- function's documentation for full detail including
- caveats and limitations.
-
- This function requires that a :class:`.MigrationContext` has
- first been made available via :meth:`.configure`.
-
- """
- self.get_context().execute(sql,
- execution_options=execution_options)
-
- def static_output(self, text):
- """Emit text directly to the "offline" SQL stream.
-
- Typically this is for emitting comments that
- start with --. The statement is not treated
- as a SQL execution, no ; or batch separator
- is added, etc.
-
- """
- self.get_context().impl.static_output(text)
-
-
- def begin_transaction(self):
- """Return a context manager that will
- enclose an operation within a "transaction",
- as defined by the environment's offline
- and transactional DDL settings.
-
- e.g.::
-
- with context.begin_transaction():
- context.run_migrations()
-
- :meth:`.begin_transaction` is intended to
- "do the right thing" regardless of
- calling context:
-
- * If :meth:`.is_transactional_ddl` is ``False``,
- returns a "do nothing" context manager
- which otherwise produces no transactional
- state or directives.
- * If :meth:`.is_offline_mode` is ``True``,
- returns a context manager that will
- invoke the :meth:`.DefaultImpl.emit_begin`
- and :meth:`.DefaultImpl.emit_commit`
- methods, which will produce the string
- directives ``BEGIN`` and ``COMMIT`` on
- the output stream, as rendered by the
- target backend (e.g. SQL Server would
- emit ``BEGIN TRANSACTION``).
- * Otherwise, calls :meth:`sqlalchemy.engine.Connection.begin`
- on the current online connection, which
- returns a :class:`sqlalchemy.engine.Transaction`
- object. This object demarcates a real
- transaction and is itself a context manager,
- which will roll back if an exception
- is raised.
-
- Note that a custom ``env.py`` script which
- has more specific transactional needs can of course
- manipulate the :class:`~sqlalchemy.engine.Connection`
- directly to produce transactional state in "online"
- mode.
-
- """
-
- return self.get_context().begin_transaction()
-
-
- def get_context(self):
- """Return the current :class:`.MigrationContext` object.
-
- If :meth:`.EnvironmentContext.configure` has not been
- called yet, raises an exception.
-
- """
-
- if self._migration_context is None:
- raise Exception("No context has been configured yet.")
- return self._migration_context
-
- def get_bind(self):
- """Return the current 'bind'.
-
- In "online" mode, this is the
- :class:`sqlalchemy.engine.Connection` currently being used
- to emit SQL to the database.
-
- This function requires that a :class:`.MigrationContext`
- has first been made available via :meth:`.configure`.
-
- """
- return self.get_context().bind
-
- def get_impl(self):
- return self.get_context().impl
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/migration.py b/Darwin/lib/python2.7/site-packages/alembic/migration.py
deleted file mode 100644
index e554515..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/migration.py
+++ /dev/null
@@ -1,352 +0,0 @@
-import io
-import logging
-import sys
-from contextlib import contextmanager
-
-
-from sqlalchemy import MetaData, Table, Column, String, literal_column
-from sqlalchemy import create_engine
-from sqlalchemy.engine import url as sqla_url
-
-from .compat import callable, EncodedIO
-from . import ddl, util
-
-log = logging.getLogger(__name__)
-
-class MigrationContext(object):
- """Represent the database state made available to a migration
- script.
-
- :class:`.MigrationContext` is the front end to an actual
- database connection, or alternatively a string output
- stream given a particular database dialect,
- from an Alembic perspective.
-
- When inside the ``env.py`` script, the :class:`.MigrationContext`
- is available via the
- :meth:`.EnvironmentContext.get_context` method,
- which is available at ``alembic.context``::
-
- # from within env.py script
- from alembic import context
- migration_context = context.get_context()
-
- For usage outside of an ``env.py`` script, such as for
- utility routines that want to check the current version
- in the database, the :meth:`.MigrationContext.configure`
- method to create new :class:`.MigrationContext` objects.
- For example, to get at the current revision in the
- database using :meth:`.MigrationContext.get_current_revision`::
-
- # in any application, outside of an env.py script
- from alembic.migration import MigrationContext
- from sqlalchemy import create_engine
-
- engine = create_engine("postgresql://mydatabase")
- conn = engine.connect()
-
- context = MigrationContext.configure(conn)
- current_rev = context.get_current_revision()
-
- The above context can also be used to produce
- Alembic migration operations with an :class:`.Operations`
- instance::
-
- # in any application, outside of the normal Alembic environment
- from alembic.operations import Operations
- op = Operations(context)
- op.alter_column("mytable", "somecolumn", nullable=True)
-
- """
- def __init__(self, dialect, connection, opts):
- self.opts = opts
- self.dialect = dialect
- self.script = opts.get('script')
-
- as_sql = opts.get('as_sql', False)
- transactional_ddl = opts.get("transactional_ddl")
-
- self._transaction_per_migration = opts.get(
- "transaction_per_migration", False)
-
- if as_sql:
- self.connection = self._stdout_connection(connection)
- assert self.connection is not None
- else:
- self.connection = connection
- self._migrations_fn = opts.get('fn')
- self.as_sql = as_sql
-
- if "output_encoding" in opts:
- self.output_buffer = EncodedIO(
- opts.get("output_buffer") or sys.stdout,
- opts['output_encoding']
- )
- else:
- self.output_buffer = opts.get("output_buffer", sys.stdout)
-
- self._user_compare_type = opts.get('compare_type', False)
- self._user_compare_server_default = opts.get(
- 'compare_server_default',
- False)
- version_table = opts.get('version_table', 'alembic_version')
- version_table_schema = opts.get('version_table_schema', None)
- self._version = Table(
- version_table, MetaData(),
- Column('version_num', String(32), nullable=False),
- schema=version_table_schema)
-
- self._start_from_rev = opts.get("starting_rev")
- self.impl = ddl.DefaultImpl.get_by_dialect(dialect)(
- dialect, self.connection, self.as_sql,
- transactional_ddl,
- self.output_buffer,
- opts
- )
- log.info("Context impl %s.", self.impl.__class__.__name__)
- if self.as_sql:
- log.info("Generating static SQL")
- log.info("Will assume %s DDL.",
- "transactional" if self.impl.transactional_ddl
- else "non-transactional")
-
- @classmethod
- def configure(cls,
- connection=None,
- url=None,
- dialect_name=None,
- opts={},
- ):
- """Create a new :class:`.MigrationContext`.
-
- This is a factory method usually called
- by :meth:`.EnvironmentContext.configure`.
-
- :param connection: a :class:`~sqlalchemy.engine.Connection`
- to use for SQL execution in "online" mode. When present,
- is also used to determine the type of dialect in use.
- :param url: a string database url, or a
- :class:`sqlalchemy.engine.url.URL` object.
- The type of dialect to be used will be derived from this if
- ``connection`` is not passed.
- :param dialect_name: string name of a dialect, such as
- "postgresql", "mssql", etc. The type of dialect to be used will be
- derived from this if ``connection`` and ``url`` are not passed.
- :param opts: dictionary of options. Most other options
- accepted by :meth:`.EnvironmentContext.configure` are passed via
- this dictionary.
-
- """
- if connection:
- dialect = connection.dialect
- elif url:
- url = sqla_url.make_url(url)
- dialect = url.get_dialect()()
- elif dialect_name:
- url = sqla_url.make_url("%s://" % dialect_name)
- dialect = url.get_dialect()()
- else:
- raise Exception("Connection, url, or dialect_name is required.")
-
- return MigrationContext(dialect, connection, opts)
-
-
- def begin_transaction(self, _per_migration=False):
- transaction_now = _per_migration == self._transaction_per_migration
-
- if not transaction_now:
- @contextmanager
- def do_nothing():
- yield
- return do_nothing()
-
- elif not self.impl.transactional_ddl:
- @contextmanager
- def do_nothing():
- yield
- return do_nothing()
- elif self.as_sql:
- @contextmanager
- def begin_commit():
- self.impl.emit_begin()
- yield
- self.impl.emit_commit()
- return begin_commit()
- else:
- return self.bind.begin()
-
- def get_current_revision(self):
- """Return the current revision, usually that which is present
- in the ``alembic_version`` table in the database.
-
- If this :class:`.MigrationContext` was configured in "offline"
- mode, that is with ``as_sql=True``, the ``starting_rev``
- parameter is returned instead, if any.
-
- """
- if self.as_sql:
- return self._start_from_rev
- else:
- if self._start_from_rev:
- raise util.CommandError(
- "Can't specify current_rev to context "
- "when using a database connection")
- self._version.create(self.connection, checkfirst=True)
- return self.connection.scalar(self._version.select())
-
- _current_rev = get_current_revision
- """The 0.2 method name, for backwards compat."""
-
- def _update_current_rev(self, old, new):
- if old == new:
- return
- if new is None:
- self.impl._exec(self._version.delete())
- elif old is None:
- self.impl._exec(self._version.insert().
- values(version_num=literal_column("'%s'" % new))
- )
- else:
- self.impl._exec(self._version.update().
- values(version_num=literal_column("'%s'" % new))
- )
-
- def run_migrations(self, **kw):
- """Run the migration scripts established for this :class:`.MigrationContext`,
- if any.
-
- The commands in :mod:`alembic.command` will set up a function
- that is ultimately passed to the :class:`.MigrationContext`
- as the ``fn`` argument. This function represents the "work"
- that will be done when :meth:`.MigrationContext.run_migrations`
- is called, typically from within the ``env.py`` script of the
- migration environment. The "work function" then provides an iterable
- of version callables and other version information which
- in the case of the ``upgrade`` or ``downgrade`` commands are the
- list of version scripts to invoke. Other commands yield nothing,
- in the case that a command wants to run some other operation
- against the database such as the ``current`` or ``stamp`` commands.
-
- :param \**kw: keyword arguments here will be passed to each
- migration callable, that is the ``upgrade()`` or ``downgrade()``
- method within revision scripts.
-
- """
- current_rev = rev = False
- stamp_per_migration = not self.impl.transactional_ddl or \
- self._transaction_per_migration
-
- self.impl.start_migrations()
- for change, prev_rev, rev, doc in self._migrations_fn(
- self.get_current_revision(),
- self):
- with self.begin_transaction(_per_migration=True):
- if current_rev is False:
- current_rev = prev_rev
- if self.as_sql and not current_rev:
- self._version.create(self.connection)
- if doc:
- log.info("Running %s %s -> %s, %s", change.__name__, prev_rev,
- rev, doc)
- else:
- log.info("Running %s %s -> %s", change.__name__, prev_rev, rev)
- if self.as_sql:
- self.impl.static_output(
- "-- Running %s %s -> %s" %
- (change.__name__, prev_rev, rev)
- )
- change(**kw)
- if stamp_per_migration:
- self._update_current_rev(prev_rev, rev)
- prev_rev = rev
-
- if rev is not False:
- if not stamp_per_migration:
- self._update_current_rev(current_rev, rev)
-
- if self.as_sql and not rev:
- self._version.drop(self.connection)
-
- def execute(self, sql, execution_options=None):
- """Execute a SQL construct or string statement.
-
- The underlying execution mechanics are used, that is
- if this is "offline mode" the SQL is written to the
- output buffer, otherwise the SQL is emitted on
- the current SQLAlchemy connection.
-
- """
- self.impl._exec(sql, execution_options)
-
- def _stdout_connection(self, connection):
- def dump(construct, *multiparams, **params):
- self.impl._exec(construct)
-
- return create_engine("%s://" % self.dialect.name,
- strategy="mock", executor=dump)
-
- @property
- def bind(self):
- """Return the current "bind".
-
- In online mode, this is an instance of
- :class:`sqlalchemy.engine.Connection`, and is suitable
- for ad-hoc execution of any kind of usage described
- in :ref:`sqlexpression_toplevel` as well as
- for usage with the :meth:`sqlalchemy.schema.Table.create`
- and :meth:`sqlalchemy.schema.MetaData.create_all` methods
- of :class:`~sqlalchemy.schema.Table`, :class:`~sqlalchemy.schema.MetaData`.
-
- Note that when "standard output" mode is enabled,
- this bind will be a "mock" connection handler that cannot
- return results and is only appropriate for a very limited
- subset of commands.
-
- """
- return self.connection
-
- def _compare_type(self, inspector_column, metadata_column):
- if self._user_compare_type is False:
- return False
-
- if callable(self._user_compare_type):
- user_value = self._user_compare_type(
- self,
- inspector_column,
- metadata_column,
- inspector_column.type,
- metadata_column.type
- )
- if user_value is not None:
- return user_value
-
- return self.impl.compare_type(
- inspector_column,
- metadata_column)
-
- def _compare_server_default(self, inspector_column,
- metadata_column,
- rendered_metadata_default,
- rendered_column_default):
-
- if self._user_compare_server_default is False:
- return False
-
- if callable(self._user_compare_server_default):
- user_value = self._user_compare_server_default(
- self,
- inspector_column,
- metadata_column,
- rendered_column_default,
- metadata_column.server_default,
- rendered_metadata_default
- )
- if user_value is not None:
- return user_value
-
- return self.impl.compare_server_default(
- inspector_column,
- metadata_column,
- rendered_metadata_default,
- rendered_column_default)
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/op.py b/Darwin/lib/python2.7/site-packages/alembic/op.py
deleted file mode 100644
index 8e5f777..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/op.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from .operations import Operations
-from . import util
-
-# create proxy functions for
-# each method on the Operations class.
-util.create_module_class_proxy(Operations, globals(), locals())
diff --git a/Darwin/lib/python2.7/site-packages/alembic/operations.py b/Darwin/lib/python2.7/site-packages/alembic/operations.py
deleted file mode 100644
index f1d06a5..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/operations.py
+++ /dev/null
@@ -1,1037 +0,0 @@
-from contextlib import contextmanager
-
-from sqlalchemy.types import NULLTYPE, Integer
-from sqlalchemy import schema as sa_schema
-
-from . import util
-from .compat import string_types
-from .ddl import impl
-
-__all__ = ('Operations',)
-
-try:
- from sqlalchemy.sql.naming import conv
-except:
- conv = None
-
-class Operations(object):
- """Define high level migration operations.
-
- Each operation corresponds to some schema migration operation,
- executed against a particular :class:`.MigrationContext`
- which in turn represents connectivity to a database,
- or a file output stream.
-
- While :class:`.Operations` is normally configured as
- part of the :meth:`.EnvironmentContext.run_migrations`
- method called from an ``env.py`` script, a standalone
- :class:`.Operations` instance can be
- made for use cases external to regular Alembic
- migrations by passing in a :class:`.MigrationContext`::
-
- from alembic.migration import MigrationContext
- from alembic.operations import Operations
-
- conn = myengine.connect()
- ctx = MigrationContext.configure(conn)
- op = Operations(ctx)
-
- op.alter_column("t", "c", nullable=True)
-
- """
- def __init__(self, migration_context):
- """Construct a new :class:`.Operations`
-
- :param migration_context: a :class:`.MigrationContext`
- instance.
-
- """
- self.migration_context = migration_context
- self.impl = migration_context.impl
-
- @classmethod
- @contextmanager
- def context(cls, migration_context):
- from .op import _install_proxy, _remove_proxy
- op = Operations(migration_context)
- _install_proxy(op)
- yield op
- _remove_proxy()
-
-
- def _primary_key_constraint(self, name, table_name, cols, schema=None):
- m = self._metadata()
- columns = [sa_schema.Column(n, NULLTYPE) for n in cols]
- t1 = sa_schema.Table(table_name, m,
- *columns,
- schema=schema)
- p = sa_schema.PrimaryKeyConstraint(*columns, name=name)
- t1.append_constraint(p)
- return p
-
- def _foreign_key_constraint(self, name, source, referent,
- local_cols, remote_cols,
- onupdate=None, ondelete=None,
- deferrable=None, source_schema=None,
- referent_schema=None, initially=None,
- match=None, **dialect_kw):
- m = self._metadata()
- if source == referent:
- t1_cols = local_cols + remote_cols
- else:
- t1_cols = local_cols
- sa_schema.Table(referent, m,
- *[sa_schema.Column(n, NULLTYPE) for n in remote_cols],
- schema=referent_schema)
-
- t1 = sa_schema.Table(source, m,
- *[sa_schema.Column(n, NULLTYPE) for n in t1_cols],
- schema=source_schema)
-
- tname = "%s.%s" % (referent_schema, referent) if referent_schema \
- else referent
- f = sa_schema.ForeignKeyConstraint(local_cols,
- ["%s.%s" % (tname, n)
- for n in remote_cols],
- name=name,
- onupdate=onupdate,
- ondelete=ondelete,
- deferrable=deferrable,
- initially=initially,
- match=match,
- **dialect_kw
- )
- t1.append_constraint(f)
-
- return f
-
- def _unique_constraint(self, name, source, local_cols, schema=None, **kw):
- t = sa_schema.Table(source, self._metadata(),
- *[sa_schema.Column(n, NULLTYPE) for n in local_cols],
- schema=schema)
- kw['name'] = name
- uq = sa_schema.UniqueConstraint(*[t.c[n] for n in local_cols], **kw)
- # TODO: need event tests to ensure the event
- # is fired off here
- t.append_constraint(uq)
- return uq
-
- def _check_constraint(self, name, source, condition, schema=None, **kw):
- t = sa_schema.Table(source, self._metadata(),
- sa_schema.Column('x', Integer), schema=schema)
- ck = sa_schema.CheckConstraint(condition, name=name, **kw)
- t.append_constraint(ck)
- return ck
-
- def _metadata(self):
- kw = {}
- if 'target_metadata' in self.migration_context.opts:
- mt = self.migration_context.opts['target_metadata']
- if hasattr(mt, 'naming_convention'):
- kw['naming_convention'] = mt.naming_convention
- return sa_schema.MetaData(**kw)
-
- def _table(self, name, *columns, **kw):
- m = self._metadata()
- t = sa_schema.Table(name, m, *columns, **kw)
- for f in t.foreign_keys:
- self._ensure_table_for_fk(m, f)
- return t
-
- def _column(self, name, type_, **kw):
- return sa_schema.Column(name, type_, **kw)
-
- def _index(self, name, tablename, columns, schema=None, **kw):
- t = sa_schema.Table(tablename or 'no_table', self._metadata(),
- *[sa_schema.Column(n, NULLTYPE) for n in columns],
- schema=schema
- )
- return sa_schema.Index(name, *[t.c[n] for n in columns], **kw)
-
- def _parse_table_key(self, table_key):
- if '.' in table_key:
- tokens = table_key.split('.')
- sname = ".".join(tokens[0:-1])
- tname = tokens[-1]
- else:
- tname = table_key
- sname = None
- return (sname, tname)
-
- def _ensure_table_for_fk(self, metadata, fk):
- """create a placeholder Table object for the referent of a
- ForeignKey.
-
- """
- if isinstance(fk._colspec, string_types):
- table_key, cname = fk._colspec.rsplit('.', 1)
- sname, tname = self._parse_table_key(table_key)
- if table_key not in metadata.tables:
- rel_t = sa_schema.Table(tname, metadata, schema=sname)
- else:
- rel_t = metadata.tables[table_key]
- if cname not in rel_t.c:
- rel_t.append_column(sa_schema.Column(cname, NULLTYPE))
-
- def get_context(self):
- """Return the :class:`.MigrationContext` object that's
- currently in use.
-
- """
-
- return self.migration_context
-
- def rename_table(self, old_table_name, new_table_name, schema=None):
- """Emit an ALTER TABLE to rename a table.
-
- :param old_table_name: old name.
- :param new_table_name: new name.
- :param schema: Optional schema name to operate within.
-
- """
- self.impl.rename_table(
- old_table_name,
- new_table_name,
- schema=schema
- )
-
- @util._with_legacy_names([('name', 'new_column_name')])
- def alter_column(self, table_name, column_name,
- nullable=None,
- server_default=False,
- new_column_name=None,
- type_=None,
- autoincrement=None,
- existing_type=None,
- existing_server_default=False,
- existing_nullable=None,
- existing_autoincrement=None,
- schema=None
- ):
- """Issue an "alter column" instruction using the
- current migration context.
-
- Generally, only that aspect of the column which
- is being changed, i.e. name, type, nullability,
- default, needs to be specified. Multiple changes
- can also be specified at once and the backend should
- "do the right thing", emitting each change either
- separately or together as the backend allows.
-
- MySQL has special requirements here, since MySQL
- cannot ALTER a column without a full specification.
- When producing MySQL-compatible migration files,
- it is recommended that the ``existing_type``,
- ``existing_server_default``, and ``existing_nullable``
- parameters be present, if not being altered.
-
- Type changes which are against the SQLAlchemy
- "schema" types :class:`~sqlalchemy.types.Boolean`
- and :class:`~sqlalchemy.types.Enum` may also
- add or drop constraints which accompany those
- types on backends that don't support them natively.
- The ``existing_server_default`` argument is
- used in this case as well to remove a previous
- constraint.
-
- :param table_name: string name of the target table.
- :param column_name: string name of the target column,
- as it exists before the operation begins.
- :param nullable: Optional; specify ``True`` or ``False``
- to alter the column's nullability.
- :param server_default: Optional; specify a string
- SQL expression, :func:`~sqlalchemy.sql.expression.text`,
- or :class:`~sqlalchemy.schema.DefaultClause` to indicate
- an alteration to the column's default value.
- Set to ``None`` to have the default removed.
- :param new_column_name: Optional; specify a string name here to
- indicate the new name within a column rename operation.
-
- .. versionchanged:: 0.5.0
- The ``name`` parameter is now named ``new_column_name``.
- The old name will continue to function for backwards
- compatibility.
-
- :param ``type_``: Optional; a :class:`~sqlalchemy.types.TypeEngine`
- type object to specify a change to the column's type.
- For SQLAlchemy types that also indicate a constraint (i.e.
- :class:`~sqlalchemy.types.Boolean`, :class:`~sqlalchemy.types.Enum`),
- the constraint is also generated.
- :param autoincrement: set the ``AUTO_INCREMENT`` flag of the column;
- currently understood by the MySQL dialect.
- :param existing_type: Optional; a
- :class:`~sqlalchemy.types.TypeEngine`
- type object to specify the previous type. This
- is required for all MySQL column alter operations that
- don't otherwise specify a new type, as well as for
- when nullability is being changed on a SQL Server
- column. It is also used if the type is a so-called
- SQLlchemy "schema" type which may define a constraint (i.e.
- :class:`~sqlalchemy.types.Boolean`,
- :class:`~sqlalchemy.types.Enum`),
- so that the constraint can be dropped.
- :param existing_server_default: Optional; The existing
- default value of the column. Required on MySQL if
- an existing default is not being changed; else MySQL
- removes the default.
- :param existing_nullable: Optional; the existing nullability
- of the column. Required on MySQL if the existing nullability
- is not being changed; else MySQL sets this to NULL.
- :param existing_autoincrement: Optional; the existing autoincrement
- of the column. Used for MySQL's system of altering a column
- that specifies ``AUTO_INCREMENT``.
- :param schema: Optional schema name to operate within.
-
- .. versionadded:: 0.4.0
-
- """
-
- compiler = self.impl.dialect.statement_compiler(
- self.impl.dialect,
- None
- )
- def _count_constraint(constraint):
- return not isinstance(constraint, sa_schema.PrimaryKeyConstraint) and \
- (not constraint._create_rule or
- constraint._create_rule(compiler))
-
- if existing_type and type_:
- t = self._table(table_name,
- sa_schema.Column(column_name, existing_type),
- schema=schema
- )
- for constraint in t.constraints:
- if _count_constraint(constraint):
- self.impl.drop_constraint(constraint)
-
- self.impl.alter_column(table_name, column_name,
- nullable=nullable,
- server_default=server_default,
- name=new_column_name,
- type_=type_,
- schema=schema,
- autoincrement=autoincrement,
- existing_type=existing_type,
- existing_server_default=existing_server_default,
- existing_nullable=existing_nullable,
- existing_autoincrement=existing_autoincrement
- )
-
- if type_:
- t = self._table(table_name,
- sa_schema.Column(column_name, type_),
- schema=schema
- )
- for constraint in t.constraints:
- if _count_constraint(constraint):
- self.impl.add_constraint(constraint)
-
- def f(self, name):
- """Indicate a string name that has already had a naming convention
- applied to it.
-
- This feature combines with the SQLAlchemy ``naming_convention`` feature
- to disambiguate constraint names that have already had naming
- conventions applied to them, versus those that have not. This is
- necessary in the case that the ``"%(constraint_name)s"`` token
- is used within a naming convention, so that it can be identified
- that this particular name should remain fixed.
-
- If the :meth:`.Operations.f` is used on a constraint, the naming
- convention will not take effect::
-
- op.add_column('t', 'x', Boolean(name=op.f('ck_bool_t_x')))
-
- Above, the CHECK constraint generated will have the name ``ck_bool_t_x``
- regardless of whether or not a naming convention is in use.
-
- Alternatively, if a naming convention is in use, and 'f' is not used,
- names will be converted along conventions. If the ``target_metadata``
- contains the naming convention
- ``{"ck": "ck_bool_%(table_name)s_%(constraint_name)s"}``, then the
- output of the following:
-
- op.add_column('t', 'x', Boolean(name='x'))
-
- will be::
-
- CONSTRAINT ck_bool_t_x CHECK (x in (1, 0)))
-
- The function is rendered in the output of autogenerate when
- a particular constraint name is already converted, for SQLAlchemy
- version **0.9.4 and greater only**. Even though ``naming_convention``
- was introduced in 0.9.2, the string disambiguation service is new
- as of 0.9.4.
-
- .. versionadded:: 0.6.4
-
- """
- if conv:
- return conv(name)
- else:
- raise NotImplementedError(
- "op.f() feature requires SQLAlchemy 0.9.4 or greater.")
-
- def add_column(self, table_name, column, schema=None):
- """Issue an "add column" instruction using the current
- migration context.
-
- e.g.::
-
- from alembic import op
- from sqlalchemy import Column, String
-
- op.add_column('organization',
- Column('name', String())
- )
-
- The provided :class:`~sqlalchemy.schema.Column` object can also
- specify a :class:`~sqlalchemy.schema.ForeignKey`, referencing
- a remote table name. Alembic will automatically generate a stub
- "referenced" table and emit a second ALTER statement in order
- to add the constraint separately::
-
- from alembic import op
- from sqlalchemy import Column, INTEGER, ForeignKey
-
- op.add_column('organization',
- Column('account_id', INTEGER, ForeignKey('accounts.id'))
- )
-
- Note that this statement uses the :class:`~sqlalchemy.schema.Column`
- construct as is from the SQLAlchemy library. In particular,
- default values to be created on the database side are
- specified using the ``server_default`` parameter, and not
- ``default`` which only specifies Python-side defaults::
-
- from alembic import op
- from sqlalchemy import Column, TIMESTAMP, func
-
- # specify "DEFAULT NOW" along with the column add
- op.add_column('account',
- Column('timestamp', TIMESTAMP, server_default=func.now())
- )
-
- :param table_name: String name of the parent table.
- :param column: a :class:`sqlalchemy.schema.Column` object
- representing the new column.
- :param schema: Optional schema name to operate within.
-
- .. versionadded:: 0.4.0
-
- """
-
- t = self._table(table_name, column, schema=schema)
- self.impl.add_column(
- table_name,
- column,
- schema=schema
- )
- for constraint in t.constraints:
- if not isinstance(constraint, sa_schema.PrimaryKeyConstraint):
- self.impl.add_constraint(constraint)
-
- def drop_column(self, table_name, column_name, **kw):
- """Issue a "drop column" instruction using the current
- migration context.
-
- e.g.::
-
- drop_column('organization', 'account_id')
-
- :param table_name: name of table
- :param column_name: name of column
- :param schema: Optional schema name to operate within.
-
- .. versionadded:: 0.4.0
-
- :param mssql_drop_check: Optional boolean. When ``True``, on
- Microsoft SQL Server only, first
- drop the CHECK constraint on the column using a
- SQL-script-compatible
- block that selects into a @variable from sys.check_constraints,
- then exec's a separate DROP CONSTRAINT for that constraint.
- :param mssql_drop_default: Optional boolean. When ``True``, on
- Microsoft SQL Server only, first
- drop the DEFAULT constraint on the column using a
- SQL-script-compatible
- block that selects into a @variable from sys.default_constraints,
- then exec's a separate DROP CONSTRAINT for that default.
- :param mssql_drop_foreign_key: Optional boolean. When ``True``, on
- Microsoft SQL Server only, first
- drop a single FOREIGN KEY constraint on the column using a
- SQL-script-compatible
- block that selects into a @variable from
- sys.foreign_keys/sys.foreign_key_columns,
- then exec's a separate DROP CONSTRAINT for that default. Only
- works if the column has exactly one FK constraint which refers to
- it, at the moment.
-
- .. versionadded:: 0.6.2
-
- """
-
- self.impl.drop_column(
- table_name,
- self._column(column_name, NULLTYPE),
- **kw
- )
-
-
- def create_primary_key(self, name, table_name, cols, schema=None):
- """Issue a "create primary key" instruction using the current
- migration context.
-
- e.g.::
-
- from alembic import op
- op.create_primary_key(
- "pk_my_table", "my_table",
- ["id", "version"]
- )
-
- This internally generates a :class:`~sqlalchemy.schema.Table` object
- containing the necessary columns, then generates a new
- :class:`~sqlalchemy.schema.PrimaryKeyConstraint`
- object which it then associates with the :class:`~sqlalchemy.schema.Table`.
- Any event listeners associated with this action will be fired
- off normally. The :class:`~sqlalchemy.schema.AddConstraint`
- construct is ultimately used to generate the ALTER statement.
-
- .. versionadded:: 0.5.0
-
- :param name: Name of the primary key constraint. The name is necessary
- so that an ALTER statement can be emitted. For setups that
- use an automated naming scheme such as that described at
- `NamingConventions `_,
- ``name`` here can be ``None``, as the event listener will
- apply the name to the constraint object when it is associated
- with the table.
- :param table_name: String name of the target table.
- :param cols: a list of string column names to be applied to the
- primary key constraint.
- :param schema: Optional schema name of the table.
-
- """
- self.impl.add_constraint(
- self._primary_key_constraint(name, table_name, cols,
- schema)
- )
-
-
- def create_foreign_key(self, name, source, referent, local_cols,
- remote_cols, onupdate=None, ondelete=None,
- deferrable=None, initially=None, match=None,
- source_schema=None, referent_schema=None,
- **dialect_kw):
- """Issue a "create foreign key" instruction using the
- current migration context.
-
- e.g.::
-
- from alembic import op
- op.create_foreign_key(
- "fk_user_address", "address",
- "user", ["user_id"], ["id"])
-
- This internally generates a :class:`~sqlalchemy.schema.Table` object
- containing the necessary columns, then generates a new
- :class:`~sqlalchemy.schema.ForeignKeyConstraint`
- object which it then associates with the :class:`~sqlalchemy.schema.Table`.
- Any event listeners associated with this action will be fired
- off normally. The :class:`~sqlalchemy.schema.AddConstraint`
- construct is ultimately used to generate the ALTER statement.
-
- :param name: Name of the foreign key constraint. The name is necessary
- so that an ALTER statement can be emitted. For setups that
- use an automated naming scheme such as that described at
- `NamingConventions `_,
- ``name`` here can be ``None``, as the event listener will
- apply the name to the constraint object when it is associated
- with the table.
- :param source: String name of the source table.
- :param referent: String name of the destination table.
- :param local_cols: a list of string column names in the
- source table.
- :param remote_cols: a list of string column names in the
- remote table.
- :param onupdate: Optional string. If set, emit ON UPDATE when
- issuing DDL for this constraint. Typical values include CASCADE,
- DELETE and RESTRICT.
- :param ondelete: Optional string. If set, emit ON DELETE when
- issuing DDL for this constraint. Typical values include CASCADE,
- DELETE and RESTRICT.
- :param deferrable: optional bool. If set, emit DEFERRABLE or NOT
- DEFERRABLE when issuing DDL for this constraint.
- :param source_schema: Optional schema name of the source table.
- :param referent_schema: Optional schema name of the destination table.
-
- """
-
- self.impl.add_constraint(
- self._foreign_key_constraint(name, source, referent,
- local_cols, remote_cols,
- onupdate=onupdate, ondelete=ondelete,
- deferrable=deferrable, source_schema=source_schema,
- referent_schema=referent_schema,
- initially=initially, match=match, **dialect_kw)
- )
-
- def create_unique_constraint(self, name, source, local_cols,
- schema=None, **kw):
- """Issue a "create unique constraint" instruction using the
- current migration context.
-
- e.g.::
-
- from alembic import op
- op.create_unique_constraint("uq_user_name", "user", ["name"])
-
- This internally generates a :class:`~sqlalchemy.schema.Table` object
- containing the necessary columns, then generates a new
- :class:`~sqlalchemy.schema.UniqueConstraint`
- object which it then associates with the :class:`~sqlalchemy.schema.Table`.
- Any event listeners associated with this action will be fired
- off normally. The :class:`~sqlalchemy.schema.AddConstraint`
- construct is ultimately used to generate the ALTER statement.
-
- :param name: Name of the unique constraint. The name is necessary
- so that an ALTER statement can be emitted. For setups that
- use an automated naming scheme such as that described at
- `NamingConventions `_,
- ``name`` here can be ``None``, as the event listener will
- apply the name to the constraint object when it is associated
- with the table.
- :param source: String name of the source table. Dotted schema names are
- supported.
- :param local_cols: a list of string column names in the
- source table.
- :param deferrable: optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
- issuing DDL for this constraint.
- :param initially: optional string. If set, emit INITIALLY when issuing DDL
- for this constraint.
- :param schema: Optional schema name to operate within.
-
- .. versionadded:: 0.4.0
-
- """
-
- self.impl.add_constraint(
- self._unique_constraint(name, source, local_cols,
- schema=schema, **kw)
- )
-
- def create_check_constraint(self, name, source, condition,
- schema=None, **kw):
- """Issue a "create check constraint" instruction using the
- current migration context.
-
- e.g.::
-
- from alembic import op
- from sqlalchemy.sql import column, func
-
- op.create_check_constraint(
- "ck_user_name_len",
- "user",
- func.len(column('name')) > 5
- )
-
- CHECK constraints are usually against a SQL expression, so ad-hoc
- table metadata is usually needed. The function will convert the given
- arguments into a :class:`sqlalchemy.schema.CheckConstraint` bound
- to an anonymous table in order to emit the CREATE statement.
-
- :param name: Name of the check constraint. The name is necessary
- so that an ALTER statement can be emitted. For setups that
- use an automated naming scheme such as that described at
- `NamingConventions `_,
- ``name`` here can be ``None``, as the event listener will
- apply the name to the constraint object when it is associated
- with the table.
- :param source: String name of the source table.
- :param condition: SQL expression that's the condition of the constraint.
- Can be a string or SQLAlchemy expression language structure.
- :param deferrable: optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
- issuing DDL for this constraint.
- :param initially: optional string. If set, emit INITIALLY when issuing DDL
- for this constraint.
- :param schema: Optional schema name to operate within.
-
- ..versionadded:: 0.4.0
-
- """
- self.impl.add_constraint(
- self._check_constraint(name, source, condition, schema=schema, **kw)
- )
-
- def create_table(self, name, *columns, **kw):
- """Issue a "create table" instruction using the current migration context.
-
- This directive receives an argument list similar to that of the
- traditional :class:`sqlalchemy.schema.Table` construct, but without the
- metadata::
-
- from sqlalchemy import INTEGER, VARCHAR, NVARCHAR, Column
- from alembic import op
-
- op.create_table(
- 'account',
- Column('id', INTEGER, primary_key=True),
- Column('name', VARCHAR(50), nullable=False),
- Column('description', NVARCHAR(200))
- Column('timestamp', TIMESTAMP, server_default=func.now())
- )
-
- Note that :meth:`.create_table` accepts :class:`~sqlalchemy.schema.Column`
- constructs directly from the SQLAlchemy library. In particular,
- default values to be created on the database side are
- specified using the ``server_default`` parameter, and not
- ``default`` which only specifies Python-side defaults::
-
- from alembic import op
- from sqlalchemy import Column, TIMESTAMP, func
-
- # specify "DEFAULT NOW" along with the "timestamp" column
- op.create_table('account',
- Column('id', INTEGER, primary_key=True),
- Column('timestamp', TIMESTAMP, server_default=func.now())
- )
-
- :param name: Name of the table
- :param \*columns: collection of :class:`~sqlalchemy.schema.Column`
- objects within
- the table, as well as optional :class:`~sqlalchemy.schema.Constraint`
- objects
- and :class:`~.sqlalchemy.schema.Index` objects.
- :param schema: Optional schema name to operate within.
- :param \**kw: Other keyword arguments are passed to the underlying
- :class:`sqlalchemy.schema.Table` object created for the command.
-
- """
- self.impl.create_table(
- self._table(name, *columns, **kw)
- )
-
- def drop_table(self, name, **kw):
- """Issue a "drop table" instruction using the current
- migration context.
-
-
- e.g.::
-
- drop_table("accounts")
-
- :param name: Name of the table
- :param schema: Optional schema name to operate within.
-
- .. versionadded:: 0.4.0
-
- :param \**kw: Other keyword arguments are passed to the underlying
- :class:`sqlalchemy.schema.Table` object created for the command.
-
- """
- self.impl.drop_table(
- self._table(name, **kw)
- )
-
- def create_index(self, name, table_name, columns, schema=None, **kw):
- """Issue a "create index" instruction using the current
- migration context.
-
- e.g.::
-
- from alembic import op
- op.create_index('ik_test', 't1', ['foo', 'bar'])
-
- :param name: name of the index.
- :param table_name: name of the owning table.
-
- .. versionchanged:: 0.5.0
- The ``tablename`` parameter is now named ``table_name``.
- As this is a positional argument, the old name is no
- longer present.
-
- :param columns: a list of string column names in the
- table.
- :param schema: Optional schema name to operate within.
-
- .. versionadded:: 0.4.0
-
- """
-
- self.impl.create_index(
- self._index(name, table_name, columns, schema=schema, **kw)
- )
-
- @util._with_legacy_names([('tablename', 'table_name')])
- def drop_index(self, name, table_name=None, schema=None):
- """Issue a "drop index" instruction using the current
- migration context.
-
- e.g.::
-
- drop_index("accounts")
-
- :param name: name of the index.
- :param table_name: name of the owning table. Some
- backends such as Microsoft SQL Server require this.
-
- .. versionchanged:: 0.5.0
- The ``tablename`` parameter is now named ``table_name``.
- The old name will continue to function for backwards
- compatibility.
-
- :param schema: Optional schema name to operate within.
-
- .. versionadded:: 0.4.0
-
- """
- # need a dummy column name here since SQLAlchemy
- # 0.7.6 and further raises on Index with no columns
- self.impl.drop_index(
- self._index(name, table_name, ['x'], schema=schema)
- )
-
- @util._with_legacy_names([("type", "type_")])
- def drop_constraint(self, name, table_name, type_=None, schema=None):
- """Drop a constraint of the given name, typically via DROP CONSTRAINT.
-
- :param name: name of the constraint.
- :param table_name: table name.
-
- .. versionchanged:: 0.5.0
- The ``tablename`` parameter is now named ``table_name``.
- As this is a positional argument, the old name is no
- longer present.
-
- :param ``type_``: optional, required on MySQL. can be
- 'foreignkey', 'primary', 'unique', or 'check'.
-
- .. versionchanged:: 0.5.0
- The ``type`` parameter is now named ``type_``. The old name
- ``type`` will remain for backwards compatibility.
-
- .. versionadded:: 0.3.6 'primary' qualfier to enable
- dropping of MySQL primary key constraints.
-
- :param schema: Optional schema name to operate within.
-
- .. versionadded:: 0.4.0
-
- """
-
- t = self._table(table_name, schema=schema)
- types = {
- 'foreignkey': lambda name: sa_schema.ForeignKeyConstraint(
- [], [], name=name),
- 'primary': sa_schema.PrimaryKeyConstraint,
- 'unique': sa_schema.UniqueConstraint,
- 'check': lambda name: sa_schema.CheckConstraint("", name=name),
- None: sa_schema.Constraint
- }
- try:
- const = types[type_]
- except KeyError:
- raise TypeError("'type' can be one of %s" %
- ", ".join(sorted(repr(x) for x in types)))
-
- const = const(name=name)
- t.append_constraint(const)
- self.impl.drop_constraint(const)
-
- def bulk_insert(self, table, rows, multiinsert=True):
- """Issue a "bulk insert" operation using the current
- migration context.
-
- This provides a means of representing an INSERT of multiple rows
- which works equally well in the context of executing on a live
- connection as well as that of generating a SQL script. In the
- case of a SQL script, the values are rendered inline into the
- statement.
-
- e.g.::
-
- from alembic import op
- from datetime import date
- from sqlalchemy.sql import table, column
- from sqlalchemy import String, Integer, Date
-
- # Create an ad-hoc table to use for the insert statement.
- accounts_table = table('account',
- column('id', Integer),
- column('name', String),
- column('create_date', Date)
- )
-
- op.bulk_insert(accounts_table,
- [
- {'id':1, 'name':'John Smith',
- 'create_date':date(2010, 10, 5)},
- {'id':2, 'name':'Ed Williams',
- 'create_date':date(2007, 5, 27)},
- {'id':3, 'name':'Wendy Jones',
- 'create_date':date(2008, 8, 15)},
- ]
- )
-
- When using --sql mode, some datatypes may not render inline automatically,
- such as dates and other special types. When this issue is present,
- :meth:`.Operations.inline_literal` may be used::
-
- op.bulk_insert(accounts_table,
- [
- {'id':1, 'name':'John Smith',
- 'create_date':op.inline_literal("2010-10-05")},
- {'id':2, 'name':'Ed Williams',
- 'create_date':op.inline_literal("2007-05-27")},
- {'id':3, 'name':'Wendy Jones',
- 'create_date':op.inline_literal("2008-08-15")},
- ],
- multiinsert=False
- )
-
- When using :meth:`.Operations.inline_literal` in conjunction with
- :meth:`.Operations.bulk_insert`, in order for the statement to work
- in "online" (e.g. non --sql) mode, the
- :paramref:`~.Operations.bulk_insert.multiinsert`
- flag should be set to ``False``, which will have the effect of
- individual INSERT statements being emitted to the database, each
- with a distinct VALUES clause, so that the "inline" values can
- still be rendered, rather than attempting to pass the values
- as bound parameters.
-
- .. versionadded:: 0.6.4 :meth:`.Operations.inline_literal` can now
- be used with :meth:`.Operations.bulk_insert`, and the
- :paramref:`~.Operations.bulk_insert.multiinsert` flag has
- been added to assist in this usage when running in "online"
- mode.
-
- :param table: a table object which represents the target of the INSERT.
-
- :param rows: a list of dictionaries indicating rows.
-
- :param multiinsert: when at its default of True and --sql mode is not
- enabled, the INSERT statement will be executed using
- "executemany()" style, where all elements in the list of dictionaries
- are passed as bound parameters in a single list. Setting this
- to False results in individual INSERT statements being emitted
- per parameter set, and is needed in those cases where non-literal
- values are present in the parameter sets.
-
- .. versionadded:: 0.6.4
-
- """
- self.impl.bulk_insert(table, rows, multiinsert=multiinsert)
-
- def inline_literal(self, value, type_=None):
- """Produce an 'inline literal' expression, suitable for
- using in an INSERT, UPDATE, or DELETE statement.
-
- When using Alembic in "offline" mode, CRUD operations
- aren't compatible with SQLAlchemy's default behavior surrounding
- literal values,
- which is that they are converted into bound values and passed
- separately into the ``execute()`` method of the DBAPI cursor.
- An offline SQL
- script needs to have these rendered inline. While it should
- always be noted that inline literal values are an **enormous**
- security hole in an application that handles untrusted input,
- a schema migration is not run in this context, so
- literals are safe to render inline, with the caveat that
- advanced types like dates may not be supported directly
- by SQLAlchemy.
-
- See :meth:`.execute` for an example usage of
- :meth:`.inline_literal`.
-
- :param value: The value to render. Strings, integers, and simple
- numerics should be supported. Other types like boolean,
- dates, etc. may or may not be supported yet by various
- backends.
- :param ``type_``: optional - a :class:`sqlalchemy.types.TypeEngine`
- subclass stating the type of this value. In SQLAlchemy
- expressions, this is usually derived automatically
- from the Python type of the value itself, as well as
- based on the context in which the value is used.
-
- """
- return impl._literal_bindparam(None, value, type_=type_)
-
- def execute(self, sql, execution_options=None):
- """Execute the given SQL using the current migration context.
-
- In a SQL script context, the statement is emitted directly to the
- output stream. There is *no* return result, however, as this
- function is oriented towards generating a change script
- that can run in "offline" mode. For full interaction
- with a connected database, use the "bind" available
- from the context::
-
- from alembic import op
- connection = op.get_bind()
-
- Also note that any parameterized statement here *will not work*
- in offline mode - INSERT, UPDATE and DELETE statements which refer
- to literal values would need to render
- inline expressions. For simple use cases, the
- :meth:`.inline_literal` function can be used for **rudimentary**
- quoting of string values. For "bulk" inserts, consider using
- :meth:`.bulk_insert`.
-
- For example, to emit an UPDATE statement which is equally
- compatible with both online and offline mode::
-
- from sqlalchemy.sql import table, column
- from sqlalchemy import String
- from alembic import op
-
- account = table('account',
- column('name', String)
- )
- op.execute(
- account.update().\\
- where(account.c.name==op.inline_literal('account 1')).\\
- values({'name':op.inline_literal('account 2')})
- )
-
- Note above we also used the SQLAlchemy
- :func:`sqlalchemy.sql.expression.table`
- and :func:`sqlalchemy.sql.expression.column` constructs to make a brief,
- ad-hoc table construct just for our UPDATE statement. A full
- :class:`~sqlalchemy.schema.Table` construct of course works perfectly
- fine as well, though note it's a recommended practice to at least ensure
- the definition of a table is self-contained within the migration script,
- rather than imported from a module that may break compatibility with
- older migrations.
-
- :param sql: Any legal SQLAlchemy expression, including:
-
- * a string
- * a :func:`sqlalchemy.sql.expression.text` construct.
- * a :func:`sqlalchemy.sql.expression.insert` construct.
- * a :func:`sqlalchemy.sql.expression.update`,
- :func:`sqlalchemy.sql.expression.insert`,
- or :func:`sqlalchemy.sql.expression.delete` construct.
- * Pretty much anything that's "executable" as described
- in :ref:`sqlexpression_toplevel`.
-
- :param execution_options: Optional dictionary of
- execution options, will be passed to
- :meth:`sqlalchemy.engine.Connection.execution_options`.
- """
- self.migration_context.impl.execute(sql,
- execution_options=execution_options)
-
- def get_bind(self):
- """Return the current 'bind'.
-
- Under normal circumstances, this is the
- :class:`~sqlalchemy.engine.Connection` currently being used
- to emit SQL to the database.
-
- In a SQL script context, this value is ``None``. [TODO: verify this]
-
- """
- return self.migration_context.impl.bind
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/script.py b/Darwin/lib/python2.7/site-packages/alembic/script.py
deleted file mode 100644
index 3294366..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/script.py
+++ /dev/null
@@ -1,513 +0,0 @@
-import datetime
-import os
-import re
-import shutil
-from . import util
-
-_sourceless_rev_file = re.compile(r'(.*\.py)(c|o)?$')
-_only_source_rev_file = re.compile(r'(.*\.py)$')
-_legacy_rev = re.compile(r'([a-f0-9]+)\.py$')
-_mod_def_re = re.compile(r'(upgrade|downgrade)_([a-z0-9]+)')
-_slug_re = re.compile(r'\w+')
-_default_file_template = "%(rev)s_%(slug)s"
-_relative_destination = re.compile(r'(?:\+|-)\d+')
-
-class ScriptDirectory(object):
- """Provides operations upon an Alembic script directory.
-
- This object is useful to get information as to current revisions,
- most notably being able to get at the "head" revision, for schemes
- that want to test if the current revision in the database is the most
- recent::
-
- from alembic.script import ScriptDirectory
- from alembic.config import Config
- config = Config()
- config.set_main_option("script_location", "myapp:migrations")
- script = ScriptDirectory.from_config(config)
-
- head_revision = script.get_current_head()
-
-
-
- """
- def __init__(self, dir, file_template=_default_file_template,
- truncate_slug_length=40,
- sourceless=False):
- self.dir = dir
- self.versions = os.path.join(self.dir, 'versions')
- self.file_template = file_template
- self.truncate_slug_length = truncate_slug_length or 40
- self.sourceless = sourceless
-
- if not os.access(dir, os.F_OK):
- raise util.CommandError("Path doesn't exist: %r. Please use "
- "the 'init' command to create a new "
- "scripts folder." % dir)
-
- @classmethod
- def from_config(cls, config):
- """Produce a new :class:`.ScriptDirectory` given a :class:`.Config`
- instance.
-
- The :class:`.Config` need only have the ``script_location`` key
- present.
-
- """
- script_location = config.get_main_option('script_location')
- if script_location is None:
- raise util.CommandError("No 'script_location' key "
- "found in configuration.")
- truncate_slug_length = config.get_main_option("truncate_slug_length")
- if truncate_slug_length is not None:
- truncate_slug_length = int(truncate_slug_length)
- return ScriptDirectory(
- util.coerce_resource_to_filename(script_location),
- file_template=config.get_main_option(
- 'file_template',
- _default_file_template),
- truncate_slug_length=truncate_slug_length,
- sourceless=config.get_main_option("sourceless") == "true"
- )
-
- def walk_revisions(self, base="base", head="head"):
- """Iterate through all revisions.
-
- This is actually a breadth-first tree traversal,
- with leaf nodes being heads.
-
- """
- if head == "head":
- heads = set(self.get_heads())
- else:
- heads = set([head])
- while heads:
- todo = set(heads)
- heads = set()
- for head in todo:
- if head in heads:
- break
- for sc in self.iterate_revisions(head, base):
- if sc.is_branch_point and sc.revision not in todo:
- heads.add(sc.revision)
- break
- else:
- yield sc
-
- def get_revision(self, id_):
- """Return the :class:`.Script` instance with the given rev id."""
-
- id_ = self.as_revision_number(id_)
- try:
- return self._revision_map[id_]
- except KeyError:
- # do a partial lookup
- revs = [x for x in self._revision_map
- if x is not None and x.startswith(id_)]
- if not revs:
- raise util.CommandError("No such revision '%s'" % id_)
- elif len(revs) > 1:
- raise util.CommandError(
- "Multiple revisions start "
- "with '%s', %s..." % (
- id_,
- ", ".join("'%s'" % r for r in revs[0:3])
- ))
- else:
- return self._revision_map[revs[0]]
-
- _get_rev = get_revision
-
- def as_revision_number(self, id_):
- """Convert a symbolic revision, i.e. 'head' or 'base', into
- an actual revision number."""
-
- if id_ == 'head':
- id_ = self.get_current_head()
- elif id_ == 'base':
- id_ = None
- return id_
-
- _as_rev_number = as_revision_number
-
- def iterate_revisions(self, upper, lower):
- """Iterate through script revisions, starting at the given
- upper revision identifier and ending at the lower.
-
- The traversal uses strictly the `down_revision`
- marker inside each migration script, so
- it is a requirement that upper >= lower,
- else you'll get nothing back.
-
- The iterator yields :class:`.Script` objects.
-
- """
- if upper is not None and _relative_destination.match(upper):
- relative = int(upper)
- revs = list(self._iterate_revisions("head", lower))
- revs = revs[-relative:]
- if len(revs) != abs(relative):
- raise util.CommandError("Relative revision %s didn't "
- "produce %d migrations" % (upper, abs(relative)))
- return iter(revs)
- elif lower is not None and _relative_destination.match(lower):
- relative = int(lower)
- revs = list(self._iterate_revisions(upper, "base"))
- revs = revs[0:-relative]
- if len(revs) != abs(relative):
- raise util.CommandError("Relative revision %s didn't "
- "produce %d migrations" % (lower, abs(relative)))
- return iter(revs)
- else:
- return self._iterate_revisions(upper, lower)
-
- def _iterate_revisions(self, upper, lower):
- lower = self.get_revision(lower)
- upper = self.get_revision(upper)
- orig = lower.revision if lower else 'base', \
- upper.revision if upper else 'base'
- script = upper
- while script != lower:
- if script is None and lower is not None:
- raise util.CommandError(
- "Revision %s is not an ancestor of %s" % orig)
- yield script
- downrev = script.down_revision
- script = self._revision_map[downrev]
-
- def _upgrade_revs(self, destination, current_rev):
- revs = self.iterate_revisions(destination, current_rev)
- return [
- (script.module.upgrade, script.down_revision, script.revision,
- script.doc)
- for script in reversed(list(revs))
- ]
-
- def _downgrade_revs(self, destination, current_rev):
- revs = self.iterate_revisions(current_rev, destination)
- return [
- (script.module.downgrade, script.revision, script.down_revision,
- script.doc)
- for script in revs
- ]
-
- def run_env(self):
- """Run the script environment.
-
- This basically runs the ``env.py`` script present
- in the migration environment. It is called exclusively
- by the command functions in :mod:`alembic.command`.
-
-
- """
- util.load_python_file(self.dir, 'env.py')
-
- @property
- def env_py_location(self):
- return os.path.abspath(os.path.join(self.dir, "env.py"))
-
- @util.memoized_property
- def _revision_map(self):
- map_ = {}
- for file_ in os.listdir(self.versions):
- script = Script._from_filename(self, self.versions, file_)
- if script is None:
- continue
- if script.revision in map_:
- util.warn("Revision %s is present more than once" %
- script.revision)
- map_[script.revision] = script
- for rev in map_.values():
- if rev.down_revision is None:
- continue
- if rev.down_revision not in map_:
- util.warn("Revision %s referenced from %s is not present"
- % (rev.down_revision, rev))
- rev.down_revision = None
- else:
- map_[rev.down_revision].add_nextrev(rev.revision)
- map_[None] = None
- return map_
-
- def _rev_path(self, rev_id, message, create_date):
- slug = "_".join(_slug_re.findall(message or "")).lower()
- if len(slug) > self.truncate_slug_length:
- slug = slug[:self.truncate_slug_length].rsplit('_', 1)[0] + '_'
- filename = "%s.py" % (
- self.file_template % {
- 'rev': rev_id,
- 'slug': slug,
- 'year': create_date.year,
- 'month': create_date.month,
- 'day': create_date.day,
- 'hour': create_date.hour,
- 'minute': create_date.minute,
- 'second': create_date.second
- }
- )
- return os.path.join(self.versions, filename)
-
- def get_current_head(self):
- """Return the current head revision.
-
- If the script directory has multiple heads
- due to branching, an error is raised.
-
- Returns a string revision number.
-
- """
- current_heads = self.get_heads()
- if len(current_heads) > 1:
- raise util.CommandError('Only a single head is supported. The '
- 'script directory has multiple heads (due to branching), which '
- 'must be resolved by manually editing the revision files to '
- 'form a linear sequence. Run `alembic branches` to see the '
- 'divergence(s).')
-
- if current_heads:
- return current_heads[0]
- else:
- return None
-
- _current_head = get_current_head
- """the 0.2 name, for backwards compat."""
-
- def get_heads(self):
- """Return all "head" revisions as strings.
-
- Returns a list of string revision numbers.
-
- This is normally a list of length one,
- unless branches are present. The
- :meth:`.ScriptDirectory.get_current_head()` method
- can be used normally when a script directory
- has only one head.
-
- """
- heads = []
- for script in self._revision_map.values():
- if script and script.is_head:
- heads.append(script.revision)
- return heads
-
- def get_base(self):
- """Return the "base" revision as a string.
-
- This is the revision number of the script that
- has a ``down_revision`` of None.
-
- Behavior is not defined if more than one script
- has a ``down_revision`` of None.
-
- """
- for script in self._revision_map.values():
- if script and script.down_revision is None \
- and script.revision in self._revision_map:
- return script.revision
- else:
- return None
-
- def _generate_template(self, src, dest, **kw):
- util.status("Generating %s" % os.path.abspath(dest),
- util.template_to_file,
- src,
- dest,
- **kw
- )
-
- def _copy_file(self, src, dest):
- util.status("Generating %s" % os.path.abspath(dest),
- shutil.copy,
- src, dest)
-
- def generate_revision(self, revid, message, refresh=False, **kw):
- """Generate a new revision file.
-
- This runs the ``script.py.mako`` template, given
- template arguments, and creates a new file.
-
- :param revid: String revision id. Typically this
- comes from ``alembic.util.rev_id()``.
- :param message: the revision message, the one passed
- by the -m argument to the ``revision`` command.
- :param refresh: when True, the in-memory state of this
- :class:`.ScriptDirectory` will be updated with a new
- :class:`.Script` instance representing the new revision;
- the :class:`.Script` instance is returned.
- If False, the file is created but the state of the
- :class:`.ScriptDirectory` is unmodified; ``None``
- is returned.
-
- """
- current_head = self.get_current_head()
- create_date = datetime.datetime.now()
- path = self._rev_path(revid, message, create_date)
- self._generate_template(
- os.path.join(self.dir, "script.py.mako"),
- path,
- up_revision=str(revid),
- down_revision=current_head,
- create_date=create_date,
- message=message if message is not None else ("empty message"),
- **kw
- )
- if refresh:
- script = Script._from_path(self, path)
- self._revision_map[script.revision] = script
- if script.down_revision:
- self._revision_map[script.down_revision].\
- add_nextrev(script.revision)
- return script
- else:
- return None
-
-
-class Script(object):
- """Represent a single revision file in a ``versions/`` directory.
-
- The :class:`.Script` instance is returned by methods
- such as :meth:`.ScriptDirectory.iterate_revisions`.
-
- """
-
- nextrev = frozenset()
-
- def __init__(self, module, rev_id, path):
- self.module = module
- self.revision = rev_id
- self.path = path
- self.down_revision = getattr(module, 'down_revision', None)
-
- revision = None
- """The string revision number for this :class:`.Script` instance."""
-
- module = None
- """The Python module representing the actual script itself."""
-
- path = None
- """Filesystem path of the script."""
-
- down_revision = None
- """The ``down_revision`` identifier within the migration script."""
-
- @property
- def doc(self):
- """Return the docstring given in the script."""
-
- return re.split("\n\n", self.longdoc)[0]
-
- @property
- def longdoc(self):
- """Return the docstring given in the script."""
-
- doc = self.module.__doc__
- if doc:
- if hasattr(self.module, "_alembic_source_encoding"):
- doc = doc.decode(self.module._alembic_source_encoding)
- return doc.strip()
- else:
- return ""
-
- def add_nextrev(self, rev):
- self.nextrev = self.nextrev.union([rev])
-
- @property
- def is_head(self):
- """Return True if this :class:`.Script` is a 'head' revision.
-
- This is determined based on whether any other :class:`.Script`
- within the :class:`.ScriptDirectory` refers to this
- :class:`.Script`. Multiple heads can be present.
-
- """
- return not bool(self.nextrev)
-
- @property
- def is_branch_point(self):
- """Return True if this :class:`.Script` is a branch point.
-
- A branchpoint is defined as a :class:`.Script` which is referred
- to by more than one succeeding :class:`.Script`, that is more
- than one :class:`.Script` has a `down_revision` identifier pointing
- here.
-
- """
- return len(self.nextrev) > 1
-
- @property
- def log_entry(self):
- return \
- "Rev: %s%s%s\n" \
- "Parent: %s\n" \
- "Path: %s\n" \
- "\n%s\n" % (
- self.revision,
- " (head)" if self.is_head else "",
- " (branchpoint)" if self.is_branch_point else "",
- self.down_revision,
- self.path,
- "\n".join(
- " %s" % para
- for para in self.longdoc.splitlines()
- )
- )
-
- def __str__(self):
- return "%s -> %s%s%s, %s" % (
- self.down_revision,
- self.revision,
- " (head)" if self.is_head else "",
- " (branchpoint)" if self.is_branch_point else "",
- self.doc)
-
- @classmethod
- def _from_path(cls, scriptdir, path):
- dir_, filename = os.path.split(path)
- return cls._from_filename(scriptdir, dir_, filename)
-
- @classmethod
- def _from_filename(cls, scriptdir, dir_, filename):
- if scriptdir.sourceless:
- py_match = _sourceless_rev_file.match(filename)
- else:
- py_match = _only_source_rev_file.match(filename)
-
- if not py_match:
- return None
-
- py_filename = py_match.group(1)
-
- if scriptdir.sourceless:
- is_c = py_match.group(2) == 'c'
- is_o = py_match.group(2) == 'o'
- else:
- is_c = is_o = False
-
- if is_o or is_c:
- py_exists = os.path.exists(os.path.join(dir_, py_filename))
- pyc_exists = os.path.exists(os.path.join(dir_, py_filename + "c"))
-
- # prefer .py over .pyc because we'd like to get the
- # source encoding; prefer .pyc over .pyo because we'd like to
- # have the docstrings which a -OO file would not have
- if py_exists or is_o and pyc_exists:
- return None
-
- module = util.load_python_file(dir_, filename)
-
- if not hasattr(module, "revision"):
- # attempt to get the revision id from the script name,
- # this for legacy only
- m = _legacy_rev.match(filename)
- if not m:
- raise util.CommandError(
- "Could not determine revision id from filename %s. "
- "Be sure the 'revision' variable is "
- "declared inside the script (please see 'Upgrading "
- "from Alembic 0.1 to 0.2' in the documentation)."
- % filename)
- else:
- revision = m.group(1)
- else:
- revision = module.revision
- return Script(module, revision, os.path.join(dir_, filename))
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/generic/README b/Darwin/lib/python2.7/site-packages/alembic/templates/generic/README
deleted file mode 100644
index 98e4f9c..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/generic/README
+++ /dev/null
@@ -1 +0,0 @@
-Generic single-database configuration.
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/generic/alembic.ini.mako b/Darwin/lib/python2.7/site-packages/alembic/templates/generic/alembic.ini.mako
deleted file mode 100644
index a738a24..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/generic/alembic.ini.mako
+++ /dev/null
@@ -1,59 +0,0 @@
-# A generic, single database configuration.
-
-[alembic]
-# path to migration scripts
-script_location = ${script_location}
-
-# template used to generate migration files
-# file_template = %%(rev)s_%%(slug)s
-
-# max length of characters to apply to the
-# "slug" field
-#truncate_slug_length = 40
-
-# set to 'true' to run the environment during
-# the 'revision' command, regardless of autogenerate
-# revision_environment = false
-
-# set to 'true' to allow .pyc and .pyo files without
-# a source .py file to be detected as revisions in the
-# versions/ directory
-# sourceless = false
-
-sqlalchemy.url = driver://user:pass@localhost/dbname
-
-
-# Logging configuration
-[loggers]
-keys = root,sqlalchemy,alembic
-
-[handlers]
-keys = console
-
-[formatters]
-keys = generic
-
-[logger_root]
-level = WARN
-handlers = console
-qualname =
-
-[logger_sqlalchemy]
-level = WARN
-handlers =
-qualname = sqlalchemy.engine
-
-[logger_alembic]
-level = INFO
-handlers =
-qualname = alembic
-
-[handler_console]
-class = StreamHandler
-args = (sys.stderr,)
-level = NOTSET
-formatter = generic
-
-[formatter_generic]
-format = %(levelname)-5.5s [%(name)s] %(message)s
-datefmt = %H:%M:%S
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/generic/env.py b/Darwin/lib/python2.7/site-packages/alembic/templates/generic/env.py
deleted file mode 100644
index 712b616..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/generic/env.py
+++ /dev/null
@@ -1,71 +0,0 @@
-from __future__ import with_statement
-from alembic import context
-from sqlalchemy import engine_from_config, pool
-from logging.config import fileConfig
-
-# this is the Alembic Config object, which provides
-# access to the values within the .ini file in use.
-config = context.config
-
-# Interpret the config file for Python logging.
-# This line sets up loggers basically.
-fileConfig(config.config_file_name)
-
-# add your model's MetaData object here
-# for 'autogenerate' support
-# from myapp import mymodel
-# target_metadata = mymodel.Base.metadata
-target_metadata = None
-
-# other values from the config, defined by the needs of env.py,
-# can be acquired:
-# my_important_option = config.get_main_option("my_important_option")
-# ... etc.
-
-def run_migrations_offline():
- """Run migrations in 'offline' mode.
-
- This configures the context with just a URL
- and not an Engine, though an Engine is acceptable
- here as well. By skipping the Engine creation
- we don't even need a DBAPI to be available.
-
- Calls to context.execute() here emit the given string to the
- script output.
-
- """
- url = config.get_main_option("sqlalchemy.url")
- context.configure(url=url, target_metadata=target_metadata)
-
- with context.begin_transaction():
- context.run_migrations()
-
-def run_migrations_online():
- """Run migrations in 'online' mode.
-
- In this scenario we need to create an Engine
- and associate a connection with the context.
-
- """
- engine = engine_from_config(
- config.get_section(config.config_ini_section),
- prefix='sqlalchemy.',
- poolclass=pool.NullPool)
-
- connection = engine.connect()
- context.configure(
- connection=connection,
- target_metadata=target_metadata
- )
-
- try:
- with context.begin_transaction():
- context.run_migrations()
- finally:
- connection.close()
-
-if context.is_offline_mode():
- run_migrations_offline()
-else:
- run_migrations_online()
-
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/generic/script.py.mako b/Darwin/lib/python2.7/site-packages/alembic/templates/generic/script.py.mako
deleted file mode 100644
index 9570201..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/generic/script.py.mako
+++ /dev/null
@@ -1,22 +0,0 @@
-"""${message}
-
-Revision ID: ${up_revision}
-Revises: ${down_revision}
-Create Date: ${create_date}
-
-"""
-
-# revision identifiers, used by Alembic.
-revision = ${repr(up_revision)}
-down_revision = ${repr(down_revision)}
-
-from alembic import op
-import sqlalchemy as sa
-${imports if imports else ""}
-
-def upgrade():
- ${upgrades if upgrades else "pass"}
-
-
-def downgrade():
- ${downgrades if downgrades else "pass"}
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/README b/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/README
deleted file mode 100644
index 5db219f..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/README
+++ /dev/null
@@ -1 +0,0 @@
-Rudimentary multi-database configuration.
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/alembic.ini.mako b/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/alembic.ini.mako
deleted file mode 100644
index 132b246..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/alembic.ini.mako
+++ /dev/null
@@ -1,65 +0,0 @@
-# a multi-database configuration.
-
-[alembic]
-# path to migration scripts
-script_location = ${script_location}
-
-# template used to generate migration files
-# file_template = %%(rev)s_%%(slug)s
-
-# max length of characters to apply to the
-# "slug" field
-#truncate_slug_length = 40
-
-# set to 'true' to run the environment during
-# the 'revision' command, regardless of autogenerate
-# revision_environment = false
-
-# set to 'true' to allow .pyc and .pyo files without
-# a source .py file to be detected as revisions in the
-# versions/ directory
-# sourceless = false
-
-databases = engine1, engine2
-
-[engine1]
-sqlalchemy.url = driver://user:pass@localhost/dbname
-
-[engine2]
-sqlalchemy.url = driver://user:pass@localhost/dbname2
-
-
-# Logging configuration
-[loggers]
-keys = root,sqlalchemy,alembic
-
-[handlers]
-keys = console
-
-[formatters]
-keys = generic
-
-[logger_root]
-level = WARN
-handlers = console
-qualname =
-
-[logger_sqlalchemy]
-level = WARN
-handlers =
-qualname = sqlalchemy.engine
-
-[logger_alembic]
-level = INFO
-handlers =
-qualname = alembic
-
-[handler_console]
-class = StreamHandler
-args = (sys.stderr,)
-level = NOTSET
-formatter = generic
-
-[formatter_generic]
-format = %(levelname)-5.5s [%(name)s] %(message)s
-datefmt = %H:%M:%S
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/env.py b/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/env.py
deleted file mode 100644
index e3511de..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/env.py
+++ /dev/null
@@ -1,130 +0,0 @@
-from __future__ import with_statement
-from alembic import context
-from sqlalchemy import engine_from_config, pool
-from logging.config import fileConfig
-import logging
-import re
-
-USE_TWOPHASE = False
-
-# this is the Alembic Config object, which provides
-# access to the values within the .ini file in use.
-config = context.config
-
-# Interpret the config file for Python logging.
-# This line sets up loggers basically.
-fileConfig(config.config_file_name)
-logger = logging.getLogger('alembic.env')
-
-# gather section names referring to different
-# databases. These are named "engine1", "engine2"
-# in the sample .ini file.
-db_names = config.get_main_option('databases')
-
-# add your model's MetaData objects here
-# for 'autogenerate' support. These must be set
-# up to hold just those tables targeting a
-# particular database. table.tometadata() may be
-# helpful here in case a "copy" of
-# a MetaData is needed.
-# from myapp import mymodel
-# target_metadata = {
-# 'engine1':mymodel.metadata1,
-# 'engine2':mymodel.metadata2
-#}
-target_metadata = {}
-
-# other values from the config, defined by the needs of env.py,
-# can be acquired:
-# my_important_option = config.get_main_option("my_important_option")
-# ... etc.
-
-def run_migrations_offline():
- """Run migrations in 'offline' mode.
-
- This configures the context with just a URL
- and not an Engine, though an Engine is acceptable
- here as well. By skipping the Engine creation
- we don't even need a DBAPI to be available.
-
- Calls to context.execute() here emit the given string to the
- script output.
-
- """
- # for the --sql use case, run migrations for each URL into
- # individual files.
-
- engines = {}
- for name in re.split(r',\s*', db_names):
- engines[name] = rec = {}
- rec['url'] = context.config.get_section_option(name,
- "sqlalchemy.url")
-
- for name, rec in engines.items():
- logger.info("Migrating database %s" % name)
- file_ = "%s.sql" % name
- logger.info("Writing output to %s" % file_)
- with open(file_, 'w') as buffer:
- context.configure(url=rec['url'], output_buffer=buffer,
- target_metadata=target_metadata.get(name))
- with context.begin_transaction():
- context.run_migrations(engine_name=name)
-
-def run_migrations_online():
- """Run migrations in 'online' mode.
-
- In this scenario we need to create an Engine
- and associate a connection with the context.
-
- """
-
- # for the direct-to-DB use case, start a transaction on all
- # engines, then run all migrations, then commit all transactions.
-
- engines = {}
- for name in re.split(r',\s*', db_names):
- engines[name] = rec = {}
- rec['engine'] = engine_from_config(
- context.config.get_section(name),
- prefix='sqlalchemy.',
- poolclass=pool.NullPool)
-
- for name, rec in engines.items():
- engine = rec['engine']
- rec['connection'] = conn = engine.connect()
-
- if USE_TWOPHASE:
- rec['transaction'] = conn.begin_twophase()
- else:
- rec['transaction'] = conn.begin()
-
- try:
- for name, rec in engines.items():
- logger.info("Migrating database %s" % name)
- context.configure(
- connection=rec['connection'],
- upgrade_token="%s_upgrades" % name,
- downgrade_token="%s_downgrades" % name,
- target_metadata=target_metadata.get(name)
- )
- context.run_migrations(engine_name=name)
-
- if USE_TWOPHASE:
- for rec in engines.values():
- rec['transaction'].prepare()
-
- for rec in engines.values():
- rec['transaction'].commit()
- except:
- for rec in engines.values():
- rec['transaction'].rollback()
- raise
- finally:
- for rec in engines.values():
- rec['connection'].close()
-
-
-if context.is_offline_mode():
- run_migrations_offline()
-else:
- run_migrations_online()
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/script.py.mako b/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/script.py.mako
deleted file mode 100644
index 1e7f79a..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/multidb/script.py.mako
+++ /dev/null
@@ -1,43 +0,0 @@
-<%!
-import re
-
-%>"""${message}
-
-Revision ID: ${up_revision}
-Revises: ${down_revision}
-Create Date: ${create_date}
-
-"""
-
-# revision identifiers, used by Alembic.
-revision = ${repr(up_revision)}
-down_revision = ${repr(down_revision)}
-
-from alembic import op
-import sqlalchemy as sa
-${imports if imports else ""}
-
-def upgrade(engine_name):
- eval("upgrade_%s" % engine_name)()
-
-
-def downgrade(engine_name):
- eval("downgrade_%s" % engine_name)()
-
-<%
- db_names = config.get_main_option("databases")
-%>
-
-## generate an "upgrade_() / downgrade_()" function
-## for each database name in the ini file.
-
-% for db_name in re.split(r',\s*', db_names):
-
-def upgrade_${db_name}():
- ${context.get("%s_upgrades" % db_name, "pass")}
-
-
-def downgrade_${db_name}():
- ${context.get("%s_downgrades" % db_name, "pass")}
-
-% endfor
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/README b/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/README
deleted file mode 100644
index ed3c28e..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/README
+++ /dev/null
@@ -1 +0,0 @@
-Configuration that reads from a Pylons project environment.
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/alembic.ini.mako b/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/alembic.ini.mako
deleted file mode 100644
index 771c027..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/alembic.ini.mako
+++ /dev/null
@@ -1,25 +0,0 @@
-# a Pylons configuration.
-
-[alembic]
-# path to migration scripts
-script_location = ${script_location}
-
-# template used to generate migration files
-# file_template = %%(rev)s_%%(slug)s
-
-# max length of characters to apply to the
-# "slug" field
-#truncate_slug_length = 40
-
-# set to 'true' to run the environment during
-# the 'revision' command, regardless of autogenerate
-# revision_environment = false
-
-# set to 'true' to allow .pyc and .pyo files without
-# a source .py file to be detected as revisions in the
-# versions/ directory
-# sourceless = false
-
-pylons_config_file = ./development.ini
-
-# that's it !
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/env.py b/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/env.py
deleted file mode 100644
index 36c3fca..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/env.py
+++ /dev/null
@@ -1,86 +0,0 @@
-"""Pylons bootstrap environment.
-
-Place 'pylons_config_file' into alembic.ini, and the application will
-be loaded from there.
-
-"""
-from alembic import context
-from paste.deploy import loadapp
-from logging.config import fileConfig
-from sqlalchemy.engine.base import Engine
-
-
-try:
- # if pylons app already in, don't create a new app
- from pylons import config as pylons_config
- pylons_config['__file__']
-except:
- config = context.config
- # can use config['__file__'] here, i.e. the Pylons
- # ini file, instead of alembic.ini
- config_file = config.get_main_option('pylons_config_file')
- fileConfig(config_file)
- wsgi_app = loadapp('config:%s' % config_file, relative_to='.')
-
-
-# customize this section for non-standard engine configurations.
-meta = __import__("%s.model.meta" % wsgi_app.config['pylons.package']).model.meta
-
-# add your model's MetaData object here
-# for 'autogenerate' support
-# from myapp import mymodel
-# target_metadata = mymodel.Base.metadata
-target_metadata = None
-
-
-def run_migrations_offline():
- """Run migrations in 'offline' mode.
-
- This configures the context with just a URL
- and not an Engine, though an Engine is acceptable
- here as well. By skipping the Engine creation
- we don't even need a DBAPI to be available.
-
- Calls to context.execute() here emit the given string to the
- script output.
-
- """
- context.configure(
- url=meta.engine.url, target_metadata=target_metadata)
- with context.begin_transaction():
- context.run_migrations()
-
-
-def run_migrations_online():
- """Run migrations in 'online' mode.
-
- In this scenario we need to create an Engine
- and associate a connection with the context.
-
- """
- # specify here how the engine is acquired
- # engine = meta.engine
- raise NotImplementedError("Please specify engine connectivity here")
-
- if isinstance(engine, Engine):
- connection = engine.connect()
- else:
- raise Exception(
- 'Expected engine instance got %s instead' % type(engine)
- )
-
- context.configure(
- connection=connection,
- target_metadata=target_metadata
- )
-
- try:
- with context.begin_transaction():
- context.run_migrations()
- finally:
- connection.close()
-
-if context.is_offline_mode():
- run_migrations_offline()
-else:
- run_migrations_online()
diff --git a/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/script.py.mako b/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/script.py.mako
deleted file mode 100644
index 9570201..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/templates/pylons/script.py.mako
+++ /dev/null
@@ -1,22 +0,0 @@
-"""${message}
-
-Revision ID: ${up_revision}
-Revises: ${down_revision}
-Create Date: ${create_date}
-
-"""
-
-# revision identifiers, used by Alembic.
-revision = ${repr(up_revision)}
-down_revision = ${repr(down_revision)}
-
-from alembic import op
-import sqlalchemy as sa
-${imports if imports else ""}
-
-def upgrade():
- ${upgrades if upgrades else "pass"}
-
-
-def downgrade():
- ${downgrades if downgrades else "pass"}
diff --git a/Darwin/lib/python2.7/site-packages/alembic/util.py b/Darwin/lib/python2.7/site-packages/alembic/util.py
deleted file mode 100644
index 63e9269..0000000
--- a/Darwin/lib/python2.7/site-packages/alembic/util.py
+++ /dev/null
@@ -1,348 +0,0 @@
-import sys
-import os
-import textwrap
-import warnings
-import re
-import inspect
-import uuid
-
-from mako.template import Template
-from sqlalchemy.engine import url
-from sqlalchemy import __version__
-
-from .compat import callable, exec_, load_module_py, load_module_pyc, binary_type
-
-class CommandError(Exception):
- pass
-
-def _safe_int(value):
- try:
- return int(value)
- except:
- return value
-_vers = tuple([_safe_int(x) for x in re.findall(r'(\d+|[abc]\d)', __version__)])
-sqla_07 = _vers > (0, 7, 2)
-sqla_08 = _vers >= (0, 8, 0, 'b2')
-sqla_09 = _vers >= (0, 9, 0)
-sqla_092 = _vers >= (0, 9, 2)
-sqla_094 = _vers >= (0, 9, 4)
-if not sqla_07:
- raise CommandError(
- "SQLAlchemy 0.7.3 or greater is required. ")
-
-from sqlalchemy.util import format_argspec_plus, update_wrapper
-from sqlalchemy.util.compat import inspect_getfullargspec
-
-
-try:
- import fcntl
- import termios
- import struct
- ioctl = fcntl.ioctl(0, termios.TIOCGWINSZ,
- struct.pack('HHHH', 0, 0, 0, 0))
- _h, TERMWIDTH, _hp, _wp = struct.unpack('HHHH', ioctl)
- if TERMWIDTH <= 0: # can occur if running in emacs pseudo-tty
- TERMWIDTH = None
-except (ImportError, IOError):
- TERMWIDTH = None
-
-
-def template_to_file(template_file, dest, **kw):
- with open(dest, 'w') as f:
- f.write(
- Template(filename=template_file).render(**kw)
- )
-
-def create_module_class_proxy(cls, globals_, locals_):
- """Create module level proxy functions for the
- methods on a given class.
-
- The functions will have a compatible signature
- as the methods. A proxy is established
- using the ``_install_proxy(obj)`` function,
- and removed using ``_remove_proxy()``, both
- installed by calling this function.
-
- """
- attr_names = set()
-
- def _install_proxy(obj):
- globals_['_proxy'] = obj
- for name in attr_names:
- globals_[name] = getattr(obj, name)
-
- def _remove_proxy():
- globals_['_proxy'] = None
- for name in attr_names:
- del globals_[name]
-
- globals_['_install_proxy'] = _install_proxy
- globals_['_remove_proxy'] = _remove_proxy
-
- def _create_op_proxy(name):
- fn = getattr(cls, name)
- spec = inspect.getargspec(fn)
- if spec[0] and spec[0][0] == 'self':
- spec[0].pop(0)
- args = inspect.formatargspec(*spec)
- num_defaults = 0
- if spec[3]:
- num_defaults += len(spec[3])
- name_args = spec[0]
- if num_defaults:
- defaulted_vals = name_args[0 - num_defaults:]
- else:
- defaulted_vals = ()
-
- apply_kw = inspect.formatargspec(
- name_args, spec[1], spec[2],
- defaulted_vals,
- formatvalue=lambda x: '=' + x)
-
- def _name_error(name):
- raise NameError(
- "Can't invoke function '%s', as the proxy object has "\
- "not yet been "
- "established for the Alembic '%s' class. "
- "Try placing this code inside a callable." % (
- name, cls.__name__
- ))
- globals_['_name_error'] = _name_error
-
- func_text = textwrap.dedent("""\
- def %(name)s(%(args)s):
- %(doc)r
- try:
- p = _proxy
- except NameError:
- _name_error('%(name)s')
- return _proxy.%(name)s(%(apply_kw)s)
- e
- """ % {
- 'name': name,
- 'args': args[1:-1],
- 'apply_kw': apply_kw[1:-1],
- 'doc': fn.__doc__,
- })
- lcl = {}
- exec_(func_text, globals_, lcl)
- return lcl[name]
-
- for methname in dir(cls):
- if not methname.startswith('_'):
- if callable(getattr(cls, methname)):
- locals_[methname] = _create_op_proxy(methname)
- else:
- attr_names.add(methname)
-
-def write_outstream(stream, *text):
- encoding = getattr(stream, 'encoding', 'ascii') or 'ascii'
- for t in text:
- if not isinstance(t, binary_type):
- t = t.encode(encoding, 'replace')
- t = t.decode(encoding)
- try:
- stream.write(t)
- except IOError:
- # suppress "broken pipe" errors.
- # no known way to handle this on Python 3 however
- # as the exception is "ignored" (noisily) in TextIOWrapper.
- break
-
-def coerce_resource_to_filename(fname):
- """Interpret a filename as either a filesystem location or as a package resource.
-
- Names that are non absolute paths and contain a colon
- are interpreted as resources and coerced to a file location.
-
- """
- if not os.path.isabs(fname) and ":" in fname:
- import pkg_resources
- fname = pkg_resources.resource_filename(*fname.split(':'))
- return fname
-
-def status(_statmsg, fn, *arg, **kw):
- msg(_statmsg + " ...", False)
- try:
- ret = fn(*arg, **kw)
- write_outstream(sys.stdout, " done\n")
- return ret
- except:
- write_outstream(sys.stdout, " FAILED\n")
- raise
-
-def err(message):
- msg(message)
- sys.exit(-1)
-
-def obfuscate_url_pw(u):
- u = url.make_url(u)
- if u.password:
- u.password = 'XXXXX'
- return str(u)
-
-def asbool(value):
- return value is not None and \
- value.lower() == 'true'
-
-def warn(msg):
- warnings.warn(msg)
-
-def msg(msg, newline=True):
- if TERMWIDTH is None:
- write_outstream(sys.stdout, msg)
- if newline:
- write_outstream(sys.stdout, "\n")
- else:
- # left indent output lines
- lines = textwrap.wrap(msg, TERMWIDTH)
- if len(lines) > 1:
- for line in lines[0:-1]:
- write_outstream(sys.stdout, " ", line, "\n")
- write_outstream(sys.stdout, " ", lines[-1], ("\n" if newline else ""))
-
-def load_python_file(dir_, filename):
- """Load a file from the given path as a Python module."""
-
- module_id = re.sub(r'\W', "_", filename)
- path = os.path.join(dir_, filename)
- _, ext = os.path.splitext(filename)
- if ext == ".py":
- if os.path.exists(path):
- module = load_module_py(module_id, path)
- elif os.path.exists(simple_pyc_file_from_path(path)):
- # look for sourceless load
- module = load_module_pyc(module_id, simple_pyc_file_from_path(path))
- else:
- raise ImportError("Can't find Python file %s" % path)
- elif ext in (".pyc", ".pyo"):
- module = load_module_pyc(module_id, path)
- del sys.modules[module_id]
- return module
-
-def simple_pyc_file_from_path(path):
- """Given a python source path, return the so-called
- "sourceless" .pyc or .pyo path.
-
- This just a .pyc or .pyo file where the .py file would be.
-
- Even with PEP-3147, which normally puts .pyc/.pyo files in __pycache__,
- this use case remains supported as a so-called "sourceless module import".
-
- """
- if sys.flags.optimize:
- return path + "o" # e.g. .pyo
- else:
- return path + "c" # e.g. .pyc
-
-def pyc_file_from_path(path):
- """Given a python source path, locate the .pyc.
-
- See http://www.python.org/dev/peps/pep-3147/
- #detecting-pep-3147-availability
- http://www.python.org/dev/peps/pep-3147/#file-extension-checks
-
- """
- import imp
- has3147 = hasattr(imp, 'get_tag')
- if has3147:
- return imp.cache_from_source(path)
- else:
- return simple_pyc_file_from_path(path)
-
-def rev_id():
- val = int(uuid.uuid4()) % 100000000000000
- return hex(val)[2:-1]
-
-class memoized_property(object):
- """A read-only @property that is only evaluated once."""
-
- def __init__(self, fget, doc=None):
- self.fget = fget
- self.__doc__ = doc or fget.__doc__
- self.__name__ = fget.__name__
-
- def __get__(self, obj, cls):
- if obj is None:
- return None
- obj.__dict__[self.__name__] = result = self.fget(obj)
- return result
-
-
-class immutabledict(dict):
-
- def _immutable(self, *arg, **kw):
- raise TypeError("%s object is immutable" % self.__class__.__name__)
-
- __delitem__ = __setitem__ = __setattr__ = \
- clear = pop = popitem = setdefault = \
- update = _immutable
-
- def __new__(cls, *args):
- new = dict.__new__(cls)
- dict.__init__(new, *args)
- return new
-
- def __init__(self, *args):
- pass
-
- def __reduce__(self):
- return immutabledict, (dict(self), )
-
- def union(self, d):
- if not self:
- return immutabledict(d)
- else:
- d2 = immutabledict(self)
- dict.update(d2, d)
- return d2
-
- def __repr__(self):
- return "immutabledict(%s)" % dict.__repr__(self)
-
-
-def _with_legacy_names(translations):
- def decorate(fn):
-
- spec = inspect_getfullargspec(fn)
- metadata = dict(target='target', fn='fn')
- metadata.update(format_argspec_plus(spec, grouped=False))
-
- has_keywords = bool(spec[2])
-
- if not has_keywords:
- metadata['args'] += ", **kw"
- metadata['apply_kw'] += ", **kw"
-
- def go(*arg, **kw):
- names = set(kw).difference(spec[0])
- for oldname, newname in translations:
- if oldname in kw:
- kw[newname] = kw.pop(oldname)
- names.discard(oldname)
-
- warnings.warn(
- "Argument '%s' is now named '%s' for function '%s'" %
- (oldname, newname, fn.__name__))
- if not has_keywords and names:
- raise TypeError("Unknown arguments: %s" % ", ".join(names))
- return fn(*arg, **kw)
-
- code = 'lambda %(args)s: %(target)s(%(apply_kw)s)' % (
- metadata)
- decorated = eval(code, {"target": go})
- decorated.__defaults__ = getattr(fn, '__func__', fn).__defaults__
- update_wrapper(decorated, fn)
- if hasattr(decorated, '__wrapped__'):
- # update_wrapper in py3k applies __wrapped__, which causes
- # inspect.getargspec() to ignore the extra arguments on our
- # wrapper as of Python 3.4. We need this for the
- # "module class proxy" thing though, so just del the __wrapped__
- # for now. See #175 as well as bugs.python.org/issue17482
- del decorated.__wrapped__
- return decorated
-
- return decorate
-
-
-
diff --git a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/PKG-INFO b/Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/PKG-INFO
similarity index 98%
rename from Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/PKG-INFO
rename to Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/PKG-INFO
index 23f2982..e19ce47 100644
--- a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/PKG-INFO
+++ b/Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 1.1
Name: cffi
-Version: 0.8.2
+Version: 0.8.6
Summary: Foreign Function Interface for Python calling C code.
Home-page: http://cffi.readthedocs.org
Author: Armin Rigo, Maciej Fijalkowski
diff --git a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/SOURCES.txt
similarity index 81%
rename from Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/SOURCES.txt
rename to Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/SOURCES.txt
index 0fe9fb2..599d5cc 100644
--- a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/SOURCES.txt
+++ b/Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/SOURCES.txt
@@ -4,7 +4,6 @@ setup.cfg
setup.py
setup_base.py
c/_cffi_backend.c
-c/check__thread.c
c/file_emulator.h
c/malloc_closure.h
c/minibuffer.h
@@ -12,7 +11,6 @@ c/misc_thread.h
c/misc_win32.h
c/test_c.py
c/wchar_helper.h
-c/x.py
c/libffi_msvc/ffi.c
c/libffi_msvc/ffi.h
c/libffi_msvc/ffi_common.h
@@ -41,7 +39,6 @@ cffi.egg-info/dependency_links.txt
cffi.egg-info/not-zip-safe
cffi.egg-info/requires.txt
cffi.egg-info/top_level.txt
-demo/_csvmodule.py
demo/_curses.py
demo/api.py
demo/bsdopendirtype.py
@@ -49,20 +46,15 @@ demo/btrfs-snap.py
demo/cffi-cocoa.py
demo/fastcsv.py
demo/gmp.py
-demo/image.py
demo/pwuid.py
demo/py.cleanup
demo/pyobj.py
demo/readdir.py
demo/readdir2.py
demo/readdir_ctypes.py
-demo/sarvi.py
demo/setup.py
-demo/syslog.py
-demo/ui.py
demo/winclipboard.py
demo/xclient.py
-demo/y.py
doc/Makefile
doc/design.rst
doc/make.bat
@@ -91,22 +83,22 @@ testing/test_zintegration.py
testing/udir.py
testing/snippets/distutils_module/setup.py
testing/snippets/distutils_module/snip_basic_verify.py
-testing/snippets/distutils_module/build/lib.linux-x86_64-3.2/snip_basic_verify.py
+testing/snippets/distutils_module/build/lib.linux-x86_64-2.7/snip_basic_verify.py
testing/snippets/distutils_package_1/setup.py
-testing/snippets/distutils_package_1/build/lib.linux-x86_64-3.2/snip_basic_verify1/__init__.py
+testing/snippets/distutils_package_1/build/lib.linux-x86_64-2.7/snip_basic_verify1/__init__.py
testing/snippets/distutils_package_1/snip_basic_verify1/__init__.py
testing/snippets/distutils_package_2/setup.py
-testing/snippets/distutils_package_2/build/lib.linux-x86_64-3.2/snip_basic_verify2/__init__.py
+testing/snippets/distutils_package_2/build/lib.linux-x86_64-2.7/snip_basic_verify2/__init__.py
testing/snippets/distutils_package_2/snip_basic_verify2/__init__.py
testing/snippets/infrastructure/setup.py
-testing/snippets/infrastructure/build/lib/snip_infrastructure/__init__.py
+testing/snippets/infrastructure/build/lib.linux-x86_64-2.7/snip_infrastructure/__init__.py
testing/snippets/infrastructure/snip_infrastructure/__init__.py
testing/snippets/setuptools_module/setup.py
testing/snippets/setuptools_module/snip_setuptools_verify.py
-testing/snippets/setuptools_module/build/lib.linux-x86_64-3.2/snip_setuptools_verify.py
+testing/snippets/setuptools_module/build/lib.linux-x86_64-2.7/snip_setuptools_verify.py
testing/snippets/setuptools_package_1/setup.py
-testing/snippets/setuptools_package_1/build/lib.linux-x86_64-3.2/snip_setuptools_verify1/__init__.py
+testing/snippets/setuptools_package_1/build/lib.linux-x86_64-2.7/snip_setuptools_verify1/__init__.py
testing/snippets/setuptools_package_1/snip_setuptools_verify1/__init__.py
testing/snippets/setuptools_package_2/setup.py
-testing/snippets/setuptools_package_2/build/lib.linux-x86_64-3.2/snip_setuptools_verify2/__init__.py
+testing/snippets/setuptools_package_2/build/lib.linux-x86_64-2.7/snip_setuptools_verify2/__init__.py
testing/snippets/setuptools_package_2/snip_setuptools_verify2/__init__.py
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/dependency_links.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg-info/dependency_links.txt
rename to Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/dependency_links.txt
diff --git a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/installed-files.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/installed-files.txt
rename to Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/installed-files.txt
diff --git a/Darwin/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/not-zip-safe
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/Flask-0.10.1-py2.7.egg-info/not-zip-safe
rename to Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/not-zip-safe
diff --git a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/requires.txt b/Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/requires.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/requires.txt
rename to Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/requires.txt
diff --git a/Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/top_level.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/cffi-0.8.2-py2.7.egg-info/top_level.txt
rename to Darwin/lib/python2.7/site-packages/cffi-0.8.6-py2.7.egg-info/top_level.txt
diff --git a/Darwin/lib/python2.7/site-packages/cffi/__init__.py b/Darwin/lib/python2.7/site-packages/cffi/__init__.py
index fa9e86f..df981fd 100644
--- a/Darwin/lib/python2.7/site-packages/cffi/__init__.py
+++ b/Darwin/lib/python2.7/site-packages/cffi/__init__.py
@@ -4,5 +4,5 @@ __all__ = ['FFI', 'VerificationError', 'VerificationMissing', 'CDefError',
from .api import FFI, CDefError, FFIError
from .ffiplatform import VerificationError, VerificationMissing
-__version__ = "0.8.2"
-__version_info__ = (0, 8, 2)
+__version__ = "0.8.6"
+__version_info__ = (0, 8, 6)
diff --git a/Darwin/lib/python2.7/site-packages/cffi/api.py b/Darwin/lib/python2.7/site-packages/cffi/api.py
index f44f086..aed9715 100644
--- a/Darwin/lib/python2.7/site-packages/cffi/api.py
+++ b/Darwin/lib/python2.7/site-packages/cffi/api.py
@@ -55,8 +55,7 @@ class FFI(object):
# _cffi_backend.so compiled.
import _cffi_backend as backend
from . import __version__
- assert (backend.__version__ == __version__ or
- backend.__version__ == __version__[:3])
+ assert backend.__version__ == __version__
# (If you insist you can also try to pass the option
# 'backend=backend_ctypes.CTypesBackend()', but don't
# rely on it! It's probably not going to work well.)
@@ -443,6 +442,10 @@ def _make_ffi_library(ffi, libname, flags):
for enumname, enumval in zip(tp.enumerators, tp.enumvalues):
if enumname not in library.__dict__:
library.__dict__[enumname] = enumval
+ for key, val in ffi._parser._int_constants.items():
+ if key not in library.__dict__:
+ library.__dict__[key] = val
+
copied_enums.append(True)
if name in library.__dict__:
return
diff --git a/Darwin/lib/python2.7/site-packages/cffi/cparser.py b/Darwin/lib/python2.7/site-packages/cffi/cparser.py
index 99998ac..a53d4c3 100644
--- a/Darwin/lib/python2.7/site-packages/cffi/cparser.py
+++ b/Darwin/lib/python2.7/site-packages/cffi/cparser.py
@@ -24,6 +24,7 @@ _r_enum_dotdotdot = re.compile(r"__dotdotdot\d+__$")
_r_partial_array = re.compile(r"\[\s*\.\.\.\s*\]")
_r_words = re.compile(r"\w+|\S")
_parser_cache = None
+_r_int_literal = re.compile(r"^0?x?[0-9a-f]+u?l?$", re.IGNORECASE)
def _get_parser():
global _parser_cache
@@ -99,6 +100,7 @@ class Parser(object):
self._structnode2type = weakref.WeakKeyDictionary()
self._override = False
self._packed = False
+ self._int_constants = {}
def _parse(self, csource):
csource, macros = _preprocess(csource)
@@ -128,9 +130,10 @@ class Parser(object):
finally:
if lock is not None:
lock.release()
- return ast, macros
+ # csource will be used to find buggy source text
+ return ast, macros, csource
- def convert_pycparser_error(self, e, csource):
+ def _convert_pycparser_error(self, e, csource):
# xxx look for ":NUM:" at the start of str(e) and try to interpret
# it as a line number
line = None
@@ -142,6 +145,12 @@ class Parser(object):
csourcelines = csource.splitlines()
if 1 <= linenum <= len(csourcelines):
line = csourcelines[linenum-1]
+ return line
+
+ def convert_pycparser_error(self, e, csource):
+ line = self._convert_pycparser_error(e, csource)
+
+ msg = str(e)
if line:
msg = 'cannot parse "%s"\n%s' % (line.strip(), msg)
else:
@@ -160,14 +169,9 @@ class Parser(object):
self._packed = prev_packed
def _internal_parse(self, csource):
- ast, macros = self._parse(csource)
+ ast, macros, csource = self._parse(csource)
# add the macros
- for key, value in macros.items():
- value = value.strip()
- if value != '...':
- raise api.CDefError('only supports the syntax "#define '
- '%s ..." for now (literally)' % key)
- self._declare('macro ' + key, value)
+ self._process_macros(macros)
# find the first "__dotdotdot__" and use that as a separator
# between the repeated typedefs and the real csource
iterator = iter(ast.ext)
@@ -175,27 +179,61 @@ class Parser(object):
if decl.name == '__dotdotdot__':
break
#
- for decl in iterator:
- if isinstance(decl, pycparser.c_ast.Decl):
- self._parse_decl(decl)
- elif isinstance(decl, pycparser.c_ast.Typedef):
- if not decl.name:
- raise api.CDefError("typedef does not declare any name",
- decl)
- if (isinstance(decl.type.type, pycparser.c_ast.IdentifierType)
- and decl.type.type.names == ['__dotdotdot__']):
- realtype = model.unknown_type(decl.name)
- elif (isinstance(decl.type, pycparser.c_ast.PtrDecl) and
- isinstance(decl.type.type, pycparser.c_ast.TypeDecl) and
- isinstance(decl.type.type.type,
- pycparser.c_ast.IdentifierType) and
- decl.type.type.type.names == ['__dotdotdot__']):
- realtype = model.unknown_ptr_type(decl.name)
+ try:
+ for decl in iterator:
+ if isinstance(decl, pycparser.c_ast.Decl):
+ self._parse_decl(decl)
+ elif isinstance(decl, pycparser.c_ast.Typedef):
+ if not decl.name:
+ raise api.CDefError("typedef does not declare any name",
+ decl)
+ if (isinstance(decl.type.type, pycparser.c_ast.IdentifierType)
+ and decl.type.type.names == ['__dotdotdot__']):
+ realtype = model.unknown_type(decl.name)
+ elif (isinstance(decl.type, pycparser.c_ast.PtrDecl) and
+ isinstance(decl.type.type, pycparser.c_ast.TypeDecl) and
+ isinstance(decl.type.type.type,
+ pycparser.c_ast.IdentifierType) and
+ decl.type.type.type.names == ['__dotdotdot__']):
+ realtype = model.unknown_ptr_type(decl.name)
+ else:
+ realtype = self._get_type(decl.type, name=decl.name)
+ self._declare('typedef ' + decl.name, realtype)
else:
- realtype = self._get_type(decl.type, name=decl.name)
- self._declare('typedef ' + decl.name, realtype)
+ raise api.CDefError("unrecognized construct", decl)
+ except api.FFIError as e:
+ msg = self._convert_pycparser_error(e, csource)
+ if msg:
+ e.args = (e.args[0] + "\n *** Err: %s" % msg,)
+ raise
+
+ def _add_constants(self, key, val):
+ if key in self._int_constants:
+ raise api.FFIError(
+ "multiple declarations of constant: %s" % (key,))
+ self._int_constants[key] = val
+
+ def _process_macros(self, macros):
+ for key, value in macros.items():
+ value = value.strip()
+ match = _r_int_literal.search(value)
+ if match is not None:
+ int_str = match.group(0).lower().rstrip("ul")
+
+ # "010" is not valid oct in py3
+ if (int_str.startswith("0") and
+ int_str != "0" and
+ not int_str.startswith("0x")):
+ int_str = "0o" + int_str[1:]
+
+ pyvalue = int(int_str, 0)
+ self._add_constants(key, pyvalue)
+ elif value == '...':
+ self._declare('macro ' + key, value)
else:
- raise api.CDefError("unrecognized construct", decl)
+ raise api.CDefError('only supports the syntax "#define '
+ '%s ..." (literally) or "#define '
+ '%s 0x1FF" for now' % (key, key))
def _parse_decl(self, decl):
node = decl.type
@@ -227,7 +265,7 @@ class Parser(object):
self._declare('variable ' + decl.name, tp)
def parse_type(self, cdecl):
- ast, macros = self._parse('void __dummy(\n%s\n);' % cdecl)
+ ast, macros = self._parse('void __dummy(\n%s\n);' % cdecl)[:2]
assert not macros
exprnode = ast.ext[-1].type.args.params[0]
if isinstance(exprnode, pycparser.c_ast.ID):
@@ -306,7 +344,8 @@ class Parser(object):
if ident == 'void':
return model.void_type
if ident == '__dotdotdot__':
- raise api.FFIError('bad usage of "..."')
+ raise api.FFIError(':%d: bad usage of "..."' %
+ typenode.coord.line)
return resolve_common_type(ident)
#
if isinstance(type, pycparser.c_ast.Struct):
@@ -333,7 +372,8 @@ class Parser(object):
return self._get_struct_union_enum_type('union', typenode, name,
nested=True)
#
- raise api.FFIError("bad or unsupported type declaration")
+ raise api.FFIError(":%d: bad or unsupported type declaration" %
+ typenode.coord.line)
def _parse_function_type(self, typenode, funcname=None):
params = list(getattr(typenode.args, 'params', []))
@@ -499,6 +539,10 @@ class Parser(object):
if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
exprnode.op == '-'):
return -self._parse_constant(exprnode.expr)
+ # load previously defined int constant
+ if (isinstance(exprnode, pycparser.c_ast.ID) and
+ exprnode.name in self._int_constants):
+ return self._int_constants[exprnode.name]
#
if partial_length_ok:
if (isinstance(exprnode, pycparser.c_ast.ID) and
@@ -506,8 +550,8 @@ class Parser(object):
self._partial_length = True
return '...'
#
- raise api.FFIError("unsupported expression: expected a "
- "simple numeric constant")
+ raise api.FFIError(":%d: unsupported expression: expected a "
+ "simple numeric constant" % exprnode.coord.line)
def _build_enum_type(self, explicit_name, decls):
if decls is not None:
@@ -522,6 +566,7 @@ class Parser(object):
if enum.value is not None:
nextenumvalue = self._parse_constant(enum.value)
enumvalues.append(nextenumvalue)
+ self._add_constants(enum.name, nextenumvalue)
nextenumvalue += 1
enumvalues = tuple(enumvalues)
tp = model.EnumType(explicit_name, enumerators, enumvalues)
@@ -535,3 +580,5 @@ class Parser(object):
kind = name.split(' ', 1)[0]
if kind in ('typedef', 'struct', 'union', 'enum'):
self._declare(name, tp)
+ for k, v in other._int_constants.items():
+ self._add_constants(k, v)
diff --git a/Darwin/lib/python2.7/site-packages/cffi/ffiplatform.py b/Darwin/lib/python2.7/site-packages/cffi/ffiplatform.py
index 460ba90..4515d6c 100644
--- a/Darwin/lib/python2.7/site-packages/cffi/ffiplatform.py
+++ b/Darwin/lib/python2.7/site-packages/cffi/ffiplatform.py
@@ -38,6 +38,7 @@ def _build(tmpdir, ext):
import distutils.errors
#
dist = Distribution({'ext_modules': [ext]})
+ dist.parse_config_files()
options = dist.get_option_dict('build_ext')
options['force'] = ('ffiplatform', True)
options['build_lib'] = ('ffiplatform', tmpdir)
diff --git a/Darwin/lib/python2.7/site-packages/cffi/vengine_cpy.py b/Darwin/lib/python2.7/site-packages/cffi/vengine_cpy.py
index d9af334..31793f0 100644
--- a/Darwin/lib/python2.7/site-packages/cffi/vengine_cpy.py
+++ b/Darwin/lib/python2.7/site-packages/cffi/vengine_cpy.py
@@ -89,43 +89,54 @@ class VCPythonEngine(object):
# by generate_cpy_function_method().
prnt('static PyMethodDef _cffi_methods[] = {')
self._generate("method")
- prnt(' {"_cffi_setup", _cffi_setup, METH_VARARGS},')
- prnt(' {NULL, NULL} /* Sentinel */')
+ prnt(' {"_cffi_setup", _cffi_setup, METH_VARARGS, NULL},')
+ prnt(' {NULL, NULL, 0, NULL} /* Sentinel */')
prnt('};')
prnt()
#
# standard init.
modname = self.verifier.get_module_name()
- if sys.version_info >= (3,):
- prnt('static struct PyModuleDef _cffi_module_def = {')
- prnt(' PyModuleDef_HEAD_INIT,')
- prnt(' "%s",' % modname)
- prnt(' NULL,')
- prnt(' -1,')
- prnt(' _cffi_methods,')
- prnt(' NULL, NULL, NULL, NULL')
- prnt('};')
- prnt()
- initname = 'PyInit_%s' % modname
- createmod = 'PyModule_Create(&_cffi_module_def)'
- errorcase = 'return NULL'
- finalreturn = 'return lib'
- else:
- initname = 'init%s' % modname
- createmod = 'Py_InitModule("%s", _cffi_methods)' % modname
- errorcase = 'return'
- finalreturn = 'return'
+ constants = self._chained_list_constants[False]
+ prnt('#if PY_MAJOR_VERSION >= 3')
+ prnt()
+ prnt('static struct PyModuleDef _cffi_module_def = {')
+ prnt(' PyModuleDef_HEAD_INIT,')
+ prnt(' "%s",' % modname)
+ prnt(' NULL,')
+ prnt(' -1,')
+ prnt(' _cffi_methods,')
+ prnt(' NULL, NULL, NULL, NULL')
+ prnt('};')
+ prnt()
prnt('PyMODINIT_FUNC')
- prnt('%s(void)' % initname)
+ prnt('PyInit_%s(void)' % modname)
prnt('{')
prnt(' PyObject *lib;')
- prnt(' lib = %s;' % createmod)
- prnt(' if (lib == NULL || %s < 0)' % (
- self._chained_list_constants[False],))
- prnt(' %s;' % errorcase)
- prnt(' _cffi_init();')
- prnt(' %s;' % finalreturn)
+ prnt(' lib = PyModule_Create(&_cffi_module_def);')
+ prnt(' if (lib == NULL)')
+ prnt(' return NULL;')
+ prnt(' if (%s < 0 || _cffi_init() < 0) {' % (constants,))
+ prnt(' Py_DECREF(lib);')
+ prnt(' return NULL;')
+ prnt(' }')
+ prnt(' return lib;')
prnt('}')
+ prnt()
+ prnt('#else')
+ prnt()
+ prnt('PyMODINIT_FUNC')
+ prnt('init%s(void)' % modname)
+ prnt('{')
+ prnt(' PyObject *lib;')
+ prnt(' lib = Py_InitModule("%s", _cffi_methods);' % modname)
+ prnt(' if (lib == NULL)')
+ prnt(' return;')
+ prnt(' if (%s < 0 || _cffi_init() < 0)' % (constants,))
+ prnt(' return;')
+ prnt(' return;')
+ prnt('}')
+ prnt()
+ prnt('#endif')
def load_library(self):
# XXX review all usages of 'self' here!
@@ -394,7 +405,7 @@ class VCPythonEngine(object):
meth = 'METH_O'
else:
meth = 'METH_VARARGS'
- self._prnt(' {"%s", _cffi_f_%s, %s},' % (name, name, meth))
+ self._prnt(' {"%s", _cffi_f_%s, %s, NULL},' % (name, name, meth))
_loading_cpy_function = _loaded_noop
@@ -481,8 +492,8 @@ class VCPythonEngine(object):
if tp.fldnames is None:
return # nothing to do with opaque structs
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
- self._prnt(' {"%s", %s, METH_NOARGS},' % (layoutfuncname,
- layoutfuncname))
+ self._prnt(' {"%s", %s, METH_NOARGS, NULL},' % (layoutfuncname,
+ layoutfuncname))
def _loading_struct_or_union(self, tp, prefix, name, module):
if tp.fldnames is None:
@@ -589,13 +600,7 @@ class VCPythonEngine(object):
'variable type'),))
assert delayed
else:
- prnt(' if (LONG_MIN <= (%s) && (%s) <= LONG_MAX)' % (name, name))
- prnt(' o = PyInt_FromLong((long)(%s));' % (name,))
- prnt(' else if ((%s) <= 0)' % (name,))
- prnt(' o = PyLong_FromLongLong((long long)(%s));' % (name,))
- prnt(' else')
- prnt(' o = PyLong_FromUnsignedLongLong('
- '(unsigned long long)(%s));' % (name,))
+ prnt(' o = _cffi_from_c_int_const(%s);' % name)
prnt(' if (o == NULL)')
prnt(' return -1;')
if size_too:
@@ -632,13 +637,18 @@ class VCPythonEngine(object):
# ----------
# enums
+ def _enum_funcname(self, prefix, name):
+ # "$enum_$1" => "___D_enum____D_1"
+ name = name.replace('$', '___D_')
+ return '_cffi_e_%s_%s' % (prefix, name)
+
def _generate_cpy_enum_decl(self, tp, name, prefix='enum'):
if tp.partial:
for enumerator in tp.enumerators:
self._generate_cpy_const(True, enumerator, delayed=False)
return
#
- funcname = '_cffi_e_%s_%s' % (prefix, name)
+ funcname = self._enum_funcname(prefix, name)
prnt = self._prnt
prnt('static int %s(PyObject *lib)' % funcname)
prnt('{')
@@ -760,17 +770,30 @@ cffimod_header = r'''
#include
#include
-#ifdef MS_WIN32
-#include /* for alloca() */
-typedef __int8 int8_t;
-typedef __int16 int16_t;
-typedef __int32 int32_t;
-typedef __int64 int64_t;
-typedef unsigned __int8 uint8_t;
-typedef unsigned __int16 uint16_t;
-typedef unsigned __int32 uint32_t;
-typedef unsigned __int64 uint64_t;
-typedef unsigned char _Bool;
+/* this block of #ifs should be kept exactly identical between
+ c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py */
+#if defined(_MSC_VER)
+# include /* for alloca() */
+# if _MSC_VER < 1600 /* MSVC < 2010 */
+ typedef __int8 int8_t;
+ typedef __int16 int16_t;
+ typedef __int32 int32_t;
+ typedef __int64 int64_t;
+ typedef unsigned __int8 uint8_t;
+ typedef unsigned __int16 uint16_t;
+ typedef unsigned __int32 uint32_t;
+ typedef unsigned __int64 uint64_t;
+# else
+# include
+# endif
+# if _MSC_VER < 1800 /* MSVC < 2013 */
+ typedef unsigned char _Bool;
+# endif
+#else
+# include
+# if (defined (__SVR4) && defined (__sun)) || defined(_AIX)
+# include
+# endif
#endif
#if PY_MAJOR_VERSION < 3
@@ -795,6 +818,15 @@ typedef unsigned char _Bool;
#define _cffi_to_c_double PyFloat_AsDouble
#define _cffi_to_c_float PyFloat_AsDouble
+#define _cffi_from_c_int_const(x) \
+ (((x) > 0) ? \
+ ((unsigned long long)(x) <= (unsigned long long)LONG_MAX) ? \
+ PyInt_FromLong((long)(x)) : \
+ PyLong_FromUnsignedLongLong((unsigned long long)(x)) : \
+ ((long long)(x) >= (long long)LONG_MIN) ? \
+ PyInt_FromLong((long)(x)) : \
+ PyLong_FromLongLong((long long)(x)))
+
#define _cffi_from_c_int(x, type) \
(((type)-1) > 0 ? /* unsigned */ \
(sizeof(type) < sizeof(long) ? PyInt_FromLong(x) : \
@@ -804,14 +836,14 @@ typedef unsigned char _Bool;
PyLong_FromLongLong(x)))
#define _cffi_to_c_int(o, type) \
- (sizeof(type) == 1 ? (((type)-1) > 0 ? _cffi_to_c_u8(o) \
- : _cffi_to_c_i8(o)) : \
- sizeof(type) == 2 ? (((type)-1) > 0 ? _cffi_to_c_u16(o) \
- : _cffi_to_c_i16(o)) : \
- sizeof(type) == 4 ? (((type)-1) > 0 ? _cffi_to_c_u32(o) \
- : _cffi_to_c_i32(o)) : \
- sizeof(type) == 8 ? (((type)-1) > 0 ? _cffi_to_c_u64(o) \
- : _cffi_to_c_i64(o)) : \
+ (sizeof(type) == 1 ? (((type)-1) > 0 ? (type)_cffi_to_c_u8(o) \
+ : (type)_cffi_to_c_i8(o)) : \
+ sizeof(type) == 2 ? (((type)-1) > 0 ? (type)_cffi_to_c_u16(o) \
+ : (type)_cffi_to_c_i16(o)) : \
+ sizeof(type) == 4 ? (((type)-1) > 0 ? (type)_cffi_to_c_u32(o) \
+ : (type)_cffi_to_c_i32(o)) : \
+ sizeof(type) == 8 ? (((type)-1) > 0 ? (type)_cffi_to_c_u64(o) \
+ : (type)_cffi_to_c_i64(o)) : \
(Py_FatalError("unsupported size for type " #type), 0))
#define _cffi_to_c_i8 \
@@ -885,25 +917,32 @@ static PyObject *_cffi_setup(PyObject *self, PyObject *args)
return PyBool_FromLong(was_alive);
}
-static void _cffi_init(void)
+static int _cffi_init(void)
{
- PyObject *module = PyImport_ImportModule("_cffi_backend");
- PyObject *c_api_object;
+ PyObject *module, *c_api_object = NULL;
+ module = PyImport_ImportModule("_cffi_backend");
if (module == NULL)
- return;
+ goto failure;
c_api_object = PyObject_GetAttrString(module, "_C_API");
if (c_api_object == NULL)
- return;
+ goto failure;
if (!PyCapsule_CheckExact(c_api_object)) {
- Py_DECREF(c_api_object);
PyErr_SetNone(PyExc_ImportError);
- return;
+ goto failure;
}
memcpy(_cffi_exports, PyCapsule_GetPointer(c_api_object, "cffi"),
_CFFI_NUM_EXPORTS * sizeof(void *));
+
+ Py_DECREF(module);
Py_DECREF(c_api_object);
+ return 0;
+
+ failure:
+ Py_XDECREF(module);
+ Py_XDECREF(c_api_object);
+ return -1;
}
#define _cffi_type(num) ((CTypeDescrObject *)PyList_GET_ITEM(_cffi_types, num))
diff --git a/Darwin/lib/python2.7/site-packages/cffi/vengine_gen.py b/Darwin/lib/python2.7/site-packages/cffi/vengine_gen.py
index f8715c7..133ec7f 100644
--- a/Darwin/lib/python2.7/site-packages/cffi/vengine_gen.py
+++ b/Darwin/lib/python2.7/site-packages/cffi/vengine_gen.py
@@ -249,10 +249,10 @@ class VGenericEngine(object):
prnt(' /* %s */' % str(e)) # cannot verify it, ignore
prnt('}')
self.export_symbols.append(layoutfuncname)
- prnt('ssize_t %s(ssize_t i)' % (layoutfuncname,))
+ prnt('intptr_t %s(intptr_t i)' % (layoutfuncname,))
prnt('{')
prnt(' struct _cffi_aligncheck { char x; %s y; };' % cname)
- prnt(' static ssize_t nums[] = {')
+ prnt(' static intptr_t nums[] = {')
prnt(' sizeof(%s),' % cname)
prnt(' offsetof(struct _cffi_aligncheck, y),')
for fname, ftype, fbitsize in tp.enumfields():
@@ -276,7 +276,7 @@ class VGenericEngine(object):
return # nothing to do with opaque structs
layoutfuncname = '_cffi_layout_%s_%s' % (prefix, name)
#
- BFunc = self.ffi._typeof_locked("ssize_t(*)(ssize_t)")[0]
+ BFunc = self.ffi._typeof_locked("intptr_t(*)(intptr_t)")[0]
function = module.load_function(BFunc, layoutfuncname)
layout = []
num = 0
@@ -410,13 +410,18 @@ class VGenericEngine(object):
# ----------
# enums
+ def _enum_funcname(self, prefix, name):
+ # "$enum_$1" => "___D_enum____D_1"
+ name = name.replace('$', '___D_')
+ return '_cffi_e_%s_%s' % (prefix, name)
+
def _generate_gen_enum_decl(self, tp, name, prefix='enum'):
if tp.partial:
for enumerator in tp.enumerators:
self._generate_gen_const(True, enumerator)
return
#
- funcname = '_cffi_e_%s_%s' % (prefix, name)
+ funcname = self._enum_funcname(prefix, name)
self.export_symbols.append(funcname)
prnt = self._prnt
prnt('int %s(char *out_error)' % funcname)
@@ -430,14 +435,14 @@ class VGenericEngine(object):
enumerator, enumerator, enumvalue))
prnt(' char buf[64];')
prnt(' if ((%s) < 0)' % enumerator)
- prnt(' snprintf(buf, 63, "%%ld", (long)(%s));' % enumerator)
+ prnt(' sprintf(buf, "%%ld", (long)(%s));' % enumerator)
prnt(' else')
- prnt(' snprintf(buf, 63, "%%lu", (unsigned long)(%s));' %
+ prnt(' sprintf(buf, "%%lu", (unsigned long)(%s));' %
enumerator)
- prnt(' snprintf(out_error, 255,'
+ prnt(' sprintf(out_error,'
' "%s has the real value %s, not %s",')
prnt(' "%s", buf, "%d");' % (
- enumerator, enumvalue))
+ enumerator[:100], enumvalue))
prnt(' return -1;')
prnt(' }')
prnt(' return 0;')
@@ -453,7 +458,7 @@ class VGenericEngine(object):
else:
BType = self.ffi._typeof_locked("char[]")[0]
BFunc = self.ffi._typeof_locked("int(*)(char*)")[0]
- funcname = '_cffi_e_%s_%s' % (prefix, name)
+ funcname = self._enum_funcname(prefix, name)
function = module.load_function(BFunc, funcname)
p = self.ffi.new(BType, 256)
if function(p) < 0:
@@ -547,20 +552,29 @@ cffimod_header = r'''
#include
#include /* XXX for ssize_t on some platforms */
-#ifdef _WIN32
-# include
-# define snprintf _snprintf
-typedef __int8 int8_t;
-typedef __int16 int16_t;
-typedef __int32 int32_t;
-typedef __int64 int64_t;
-typedef unsigned __int8 uint8_t;
-typedef unsigned __int16 uint16_t;
-typedef unsigned __int32 uint32_t;
-typedef unsigned __int64 uint64_t;
-typedef SSIZE_T ssize_t;
-typedef unsigned char _Bool;
-#else
+/* this block of #ifs should be kept exactly identical between
+ c/_cffi_backend.c, cffi/vengine_cpy.py, cffi/vengine_gen.py */
+#if defined(_MSC_VER)
+# include /* for alloca() */
+# if _MSC_VER < 1600 /* MSVC < 2010 */
+ typedef __int8 int8_t;
+ typedef __int16 int16_t;
+ typedef __int32 int32_t;
+ typedef __int64 int64_t;
+ typedef unsigned __int8 uint8_t;
+ typedef unsigned __int16 uint16_t;
+ typedef unsigned __int32 uint32_t;
+ typedef unsigned __int64 uint64_t;
+# else
# include
+# endif
+# if _MSC_VER < 1800 /* MSVC < 2013 */
+ typedef unsigned char _Bool;
+# endif
+#else
+# include
+# if (defined (__SVR4) && defined (__sun)) || defined(_AIX)
+# include
+# endif
#endif
'''
diff --git a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/PKG-INFO b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/PKG-INFO
similarity index 94%
rename from Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/PKG-INFO
rename to Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/PKG-INFO
index a3eb033..40d0e13 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/PKG-INFO
+++ b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 1.1
Name: cryptography
-Version: 0.4
+Version: 0.5.4
Summary: cryptography is a package which provides cryptographic recipes and primitives to Python developers.
Home-page: https://github.com/pyca/cryptography
Author: The cryptography developers
@@ -9,6 +9,10 @@ License: Apache License, Version 2.0
Description: Cryptography
============
+ .. image:: https://pypip.in/version/cryptography/badge.svg
+ :target: https://pypi.python.org/pypi/cryptography/
+ :alt: Latest Version
+
.. image:: https://travis-ci.org/pyca/cryptography.svg?branch=master
:target: https://travis-ci.org/pyca/cryptography
diff --git a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/SOURCES.txt
similarity index 83%
rename from Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/SOURCES.txt
rename to Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/SOURCES.txt
index d15cf6e..064a501 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/SOURCES.txt
+++ b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/SOURCES.txt
@@ -23,18 +23,34 @@ cryptography/hazmat/backends/interfaces.py
cryptography/hazmat/backends/multibackend.py
cryptography/hazmat/backends/commoncrypto/__init__.py
cryptography/hazmat/backends/commoncrypto/backend.py
+cryptography/hazmat/backends/commoncrypto/ciphers.py
+cryptography/hazmat/backends/commoncrypto/hashes.py
+cryptography/hazmat/backends/commoncrypto/hmac.py
cryptography/hazmat/backends/openssl/__init__.py
cryptography/hazmat/backends/openssl/backend.py
+cryptography/hazmat/backends/openssl/ciphers.py
+cryptography/hazmat/backends/openssl/cmac.py
+cryptography/hazmat/backends/openssl/dsa.py
+cryptography/hazmat/backends/openssl/ec.py
+cryptography/hazmat/backends/openssl/hashes.py
+cryptography/hazmat/backends/openssl/hmac.py
+cryptography/hazmat/backends/openssl/rsa.py
cryptography/hazmat/bindings/__init__.py
cryptography/hazmat/bindings/utils.py
-cryptography/hazmat/bindings/__pycache__/_Cryptography_cffi_444d7397xa22f8491.c
-cryptography/hazmat/bindings/__pycache__/_Cryptography_cffi_be05eb56x6daa9a79.c
+cryptography/hazmat/bindings/__pycache__/_Cryptography_cffi_4ed9e37dx4000d087.c
+cryptography/hazmat/bindings/__pycache__/_Cryptography_cffi_d62b3d91x972e1c0b.c
cryptography/hazmat/bindings/commoncrypto/__init__.py
cryptography/hazmat/bindings/commoncrypto/binding.py
+cryptography/hazmat/bindings/commoncrypto/cf.py
cryptography/hazmat/bindings/commoncrypto/common_cryptor.py
cryptography/hazmat/bindings/commoncrypto/common_digest.py
cryptography/hazmat/bindings/commoncrypto/common_hmac.py
cryptography/hazmat/bindings/commoncrypto/common_key_derivation.py
+cryptography/hazmat/bindings/commoncrypto/secimport.py
+cryptography/hazmat/bindings/commoncrypto/secitem.py
+cryptography/hazmat/bindings/commoncrypto/seckey.py
+cryptography/hazmat/bindings/commoncrypto/seckeychain.py
+cryptography/hazmat/bindings/commoncrypto/sectransform.py
cryptography/hazmat/bindings/openssl/__init__.py
cryptography/hazmat/bindings/openssl/aes.py
cryptography/hazmat/bindings/openssl/asn1.py
@@ -65,6 +81,7 @@ cryptography/hazmat/bindings/openssl/rand.py
cryptography/hazmat/bindings/openssl/rsa.py
cryptography/hazmat/bindings/openssl/ssl.py
cryptography/hazmat/bindings/openssl/x509.py
+cryptography/hazmat/bindings/openssl/x509_vfy.py
cryptography/hazmat/bindings/openssl/x509name.py
cryptography/hazmat/bindings/openssl/x509v3.py
cryptography/hazmat/primitives/__init__.py
@@ -74,10 +91,12 @@ cryptography/hazmat/primitives/hashes.py
cryptography/hazmat/primitives/hmac.py
cryptography/hazmat/primitives/interfaces.py
cryptography/hazmat/primitives/padding.py
+cryptography/hazmat/primitives/serialization.py
cryptography/hazmat/primitives/__pycache__/_Cryptography_cffi_684bb40axf342507b.c
cryptography/hazmat/primitives/__pycache__/_Cryptography_cffi_8f86901cxc1767c5a.c
cryptography/hazmat/primitives/asymmetric/__init__.py
cryptography/hazmat/primitives/asymmetric/dsa.py
+cryptography/hazmat/primitives/asymmetric/ec.py
cryptography/hazmat/primitives/asymmetric/padding.py
cryptography/hazmat/primitives/asymmetric/rsa.py
cryptography/hazmat/primitives/ciphers/__init__.py
@@ -109,6 +128,7 @@ docs/random-numbers.rst
docs/security.rst
docs/spelling_wordlist.txt
docs/_static/.keep
+docs/development/c-bindings.rst
docs/development/getting-started.rst
docs/development/index.rst
docs/development/reviewing-patches.rst
@@ -140,9 +160,11 @@ docs/hazmat/primitives/padding.rst
docs/hazmat/primitives/symmetric-encryption.rst
docs/hazmat/primitives/twofactor.rst
docs/hazmat/primitives/asymmetric/dsa.rst
+docs/hazmat/primitives/asymmetric/ec.rst
docs/hazmat/primitives/asymmetric/index.rst
docs/hazmat/primitives/asymmetric/padding.rst
docs/hazmat/primitives/asymmetric/rsa.rst
+docs/hazmat/primitives/asymmetric/serialization.rst
docs/hazmat/primitives/mac/cmac.rst
docs/hazmat/primitives/mac/hmac.rst
docs/hazmat/primitives/mac/index.rst
@@ -160,6 +182,8 @@ tests/hazmat/bindings/test_commoncrypto.py
tests/hazmat/bindings/test_openssl.py
tests/hazmat/bindings/test_utils.py
tests/hazmat/primitives/__init__.py
+tests/hazmat/primitives/fixtures_dsa.py
+tests/hazmat/primitives/fixtures_rsa.py
tests/hazmat/primitives/test_3des.py
tests/hazmat/primitives/test_aes.py
tests/hazmat/primitives/test_arc4.py
@@ -171,6 +195,7 @@ tests/hazmat/primitives/test_ciphers.py
tests/hazmat/primitives/test_cmac.py
tests/hazmat/primitives/test_constant_time.py
tests/hazmat/primitives/test_dsa.py
+tests/hazmat/primitives/test_ec.py
tests/hazmat/primitives/test_hash_vectors.py
tests/hazmat/primitives/test_hashes.py
tests/hazmat/primitives/test_hkdf.py
@@ -183,6 +208,7 @@ tests/hazmat/primitives/test_pbkdf2hmac.py
tests/hazmat/primitives/test_pbkdf2hmac_vectors.py
tests/hazmat/primitives/test_rsa.py
tests/hazmat/primitives/test_seed.py
+tests/hazmat/primitives/test_serialization.py
tests/hazmat/primitives/utils.py
tests/hazmat/primitives/twofactor/__init__.py
tests/hazmat/primitives/twofactor/test_hotp.py
diff --git a/Darwin/lib/python2.7/site-packages/Flask_Migrate-1.2.0-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/dependency_links.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/Flask_Migrate-1.2.0-py2.7.egg-info/dependency_links.txt
rename to Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/dependency_links.txt
diff --git a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/installed-files.txt
similarity index 78%
rename from Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/installed-files.txt
rename to Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/installed-files.txt
index 8ff3d53..faf60e7 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/installed-files.txt
+++ b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/installed-files.txt
@@ -16,16 +16,33 @@
../cryptography/hazmat/primitives/hmac.py
../cryptography/hazmat/primitives/interfaces.py
../cryptography/hazmat/primitives/padding.py
+../cryptography/hazmat/primitives/serialization.py
../cryptography/hazmat/backends/commoncrypto/__init__.py
../cryptography/hazmat/backends/commoncrypto/backend.py
+../cryptography/hazmat/backends/commoncrypto/ciphers.py
+../cryptography/hazmat/backends/commoncrypto/hashes.py
+../cryptography/hazmat/backends/commoncrypto/hmac.py
../cryptography/hazmat/backends/openssl/__init__.py
../cryptography/hazmat/backends/openssl/backend.py
+../cryptography/hazmat/backends/openssl/ciphers.py
+../cryptography/hazmat/backends/openssl/cmac.py
+../cryptography/hazmat/backends/openssl/dsa.py
+../cryptography/hazmat/backends/openssl/ec.py
+../cryptography/hazmat/backends/openssl/hashes.py
+../cryptography/hazmat/backends/openssl/hmac.py
+../cryptography/hazmat/backends/openssl/rsa.py
../cryptography/hazmat/bindings/commoncrypto/__init__.py
../cryptography/hazmat/bindings/commoncrypto/binding.py
+../cryptography/hazmat/bindings/commoncrypto/cf.py
../cryptography/hazmat/bindings/commoncrypto/common_cryptor.py
../cryptography/hazmat/bindings/commoncrypto/common_digest.py
../cryptography/hazmat/bindings/commoncrypto/common_hmac.py
../cryptography/hazmat/bindings/commoncrypto/common_key_derivation.py
+../cryptography/hazmat/bindings/commoncrypto/secimport.py
+../cryptography/hazmat/bindings/commoncrypto/secitem.py
+../cryptography/hazmat/bindings/commoncrypto/seckey.py
+../cryptography/hazmat/bindings/commoncrypto/seckeychain.py
+../cryptography/hazmat/bindings/commoncrypto/sectransform.py
../cryptography/hazmat/bindings/openssl/__init__.py
../cryptography/hazmat/bindings/openssl/aes.py
../cryptography/hazmat/bindings/openssl/asn1.py
@@ -56,10 +73,12 @@
../cryptography/hazmat/bindings/openssl/rsa.py
../cryptography/hazmat/bindings/openssl/ssl.py
../cryptography/hazmat/bindings/openssl/x509.py
+../cryptography/hazmat/bindings/openssl/x509_vfy.py
../cryptography/hazmat/bindings/openssl/x509name.py
../cryptography/hazmat/bindings/openssl/x509v3.py
../cryptography/hazmat/primitives/asymmetric/__init__.py
../cryptography/hazmat/primitives/asymmetric/dsa.py
+../cryptography/hazmat/primitives/asymmetric/ec.py
../cryptography/hazmat/primitives/asymmetric/padding.py
../cryptography/hazmat/primitives/asymmetric/rsa.py
../cryptography/hazmat/primitives/ciphers/__init__.py
@@ -90,16 +109,33 @@
../cryptography/hazmat/primitives/hmac.pyc
../cryptography/hazmat/primitives/interfaces.pyc
../cryptography/hazmat/primitives/padding.pyc
+../cryptography/hazmat/primitives/serialization.pyc
../cryptography/hazmat/backends/commoncrypto/__init__.pyc
../cryptography/hazmat/backends/commoncrypto/backend.pyc
+../cryptography/hazmat/backends/commoncrypto/ciphers.pyc
+../cryptography/hazmat/backends/commoncrypto/hashes.pyc
+../cryptography/hazmat/backends/commoncrypto/hmac.pyc
../cryptography/hazmat/backends/openssl/__init__.pyc
../cryptography/hazmat/backends/openssl/backend.pyc
+../cryptography/hazmat/backends/openssl/ciphers.pyc
+../cryptography/hazmat/backends/openssl/cmac.pyc
+../cryptography/hazmat/backends/openssl/dsa.pyc
+../cryptography/hazmat/backends/openssl/ec.pyc
+../cryptography/hazmat/backends/openssl/hashes.pyc
+../cryptography/hazmat/backends/openssl/hmac.pyc
+../cryptography/hazmat/backends/openssl/rsa.pyc
../cryptography/hazmat/bindings/commoncrypto/__init__.pyc
../cryptography/hazmat/bindings/commoncrypto/binding.pyc
+../cryptography/hazmat/bindings/commoncrypto/cf.pyc
../cryptography/hazmat/bindings/commoncrypto/common_cryptor.pyc
../cryptography/hazmat/bindings/commoncrypto/common_digest.pyc
../cryptography/hazmat/bindings/commoncrypto/common_hmac.pyc
../cryptography/hazmat/bindings/commoncrypto/common_key_derivation.pyc
+../cryptography/hazmat/bindings/commoncrypto/secimport.pyc
+../cryptography/hazmat/bindings/commoncrypto/secitem.pyc
+../cryptography/hazmat/bindings/commoncrypto/seckey.pyc
+../cryptography/hazmat/bindings/commoncrypto/seckeychain.pyc
+../cryptography/hazmat/bindings/commoncrypto/sectransform.pyc
../cryptography/hazmat/bindings/openssl/__init__.pyc
../cryptography/hazmat/bindings/openssl/aes.pyc
../cryptography/hazmat/bindings/openssl/asn1.pyc
@@ -130,10 +166,12 @@
../cryptography/hazmat/bindings/openssl/rsa.pyc
../cryptography/hazmat/bindings/openssl/ssl.pyc
../cryptography/hazmat/bindings/openssl/x509.pyc
+../cryptography/hazmat/bindings/openssl/x509_vfy.pyc
../cryptography/hazmat/bindings/openssl/x509name.pyc
../cryptography/hazmat/bindings/openssl/x509v3.pyc
../cryptography/hazmat/primitives/asymmetric/__init__.pyc
../cryptography/hazmat/primitives/asymmetric/dsa.pyc
+../cryptography/hazmat/primitives/asymmetric/ec.pyc
../cryptography/hazmat/primitives/asymmetric/padding.pyc
../cryptography/hazmat/primitives/asymmetric/rsa.pyc
../cryptography/hazmat/primitives/ciphers/__init__.pyc
@@ -146,7 +184,7 @@
../cryptography/hazmat/primitives/twofactor/__init__.pyc
../cryptography/hazmat/primitives/twofactor/hotp.pyc
../cryptography/hazmat/primitives/twofactor/totp.pyc
-../cryptography/_Cryptography_cffi_444d7397xa22f8491.so
+../cryptography/_Cryptography_cffi_4ed9e37dx4000d087.so
../cryptography/_Cryptography_cffi_684bb40axf342507b.so
../cryptography/_Cryptography_cffi_8f86901cxc1767c5a.so
./
diff --git a/Darwin/lib/python2.7/site-packages/Flask_Migrate-1.2.0-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/not-zip-safe
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/Flask_Migrate-1.2.0-py2.7.egg-info/not-zip-safe
rename to Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/not-zip-safe
diff --git a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/requires.txt b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/requires.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/requires.txt
rename to Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/requires.txt
diff --git a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/top_level.txt
similarity index 70%
rename from Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/top_level.txt
rename to Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/top_level.txt
index 2cead95..c05850b 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography-0.4-py2.7.egg-info/top_level.txt
+++ b/Darwin/lib/python2.7/site-packages/cryptography-0.5.4-py2.7.egg-info/top_level.txt
@@ -1,4 +1,4 @@
-_Cryptography_cffi_444d7397xa22f8491
_Cryptography_cffi_684bb40axf342507b
+_Cryptography_cffi_4ed9e37dx4000d087
cryptography
_Cryptography_cffi_8f86901cxc1767c5a
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_444d7397xa22f8491.so b/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_444d7397xa22f8491.so
deleted file mode 100755
index 91cb880..0000000
Binary files a/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_444d7397xa22f8491.so and /dev/null differ
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_4ed9e37dx4000d087.so b/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_4ed9e37dx4000d087.so
new file mode 100755
index 0000000..28c4181
Binary files /dev/null and b/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_4ed9e37dx4000d087.so differ
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_684bb40axf342507b.so b/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_684bb40axf342507b.so
index 58dbb35..7431707 100755
Binary files a/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_684bb40axf342507b.so and b/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_684bb40axf342507b.so differ
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_8f86901cxc1767c5a.so b/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_8f86901cxc1767c5a.so
index 27938f9..f9b70d1 100755
Binary files a/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_8f86901cxc1767c5a.so and b/Darwin/lib/python2.7/site-packages/cryptography/_Cryptography_cffi_8f86901cxc1767c5a.so differ
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/__about__.py b/Darwin/lib/python2.7/site-packages/cryptography/__about__.py
index d1151dc..048a2d9 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/__about__.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/__about__.py
@@ -22,10 +22,10 @@ __summary__ = ("cryptography is a package which provides cryptographic recipes"
" and primitives to Python developers.")
__uri__ = "https://github.com/pyca/cryptography"
-__version__ = "0.4"
+__version__ = "0.5.4"
__author__ = "The cryptography developers"
__email__ = "cryptography-dev@python.org"
__license__ = "Apache License, Version 2.0"
-__copyright__ = "Copyright 2013-2014 %s" % __author__
+__copyright__ = "Copyright 2013-2014 {0}".format(__author__)
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/exceptions.py b/Darwin/lib/python2.7/site-packages/cryptography/exceptions.py
index b4ee8fe..c14763f 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/exceptions.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/exceptions.py
@@ -21,6 +21,8 @@ class _Reasons(object):
UNSUPPORTED_PADDING = object()
UNSUPPORTED_MGF = object()
UNSUPPORTED_PUBLIC_KEY_ALGORITHM = object()
+ UNSUPPORTED_ELLIPTIC_CURVE = object()
+ UNSUPPORTED_SERIALIZATION = object()
class UnsupportedAlgorithm(Exception):
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/fernet.py b/Darwin/lib/python2.7/site-packages/cryptography/fernet.py
index 674ce8a..cdb9bdc 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/fernet.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/fernet.py
@@ -43,7 +43,7 @@ class Fernet(object):
key = base64.urlsafe_b64decode(key)
if len(key) != 32:
raise ValueError(
- "Fernet key must be 32 url-safe base64-encoded bytes"
+ "Fernet key must be 32 url-safe base64-encoded bytes."
)
self._signing_key = key[:16]
@@ -60,10 +60,8 @@ class Fernet(object):
return self._encrypt_from_parts(data, current_time, iv)
def _encrypt_from_parts(self, data, current_time, iv):
- if isinstance(data, six.text_type):
- raise TypeError(
- "Unicode-objects must be encoded before encryption"
- )
+ if not isinstance(data, bytes):
+ raise TypeError("data must be bytes.")
padder = padding.PKCS7(algorithms.AES.block_size).padder()
padded_data = padder.update(data) + padder.finalize()
@@ -82,10 +80,8 @@ class Fernet(object):
return base64.urlsafe_b64encode(basic_parts + hmac)
def decrypt(self, token, ttl=None):
- if isinstance(token, six.text_type):
- raise TypeError(
- "Unicode-objects must be encoded before decryption"
- )
+ if not isinstance(token, bytes):
+ raise TypeError("token must be bytes.")
current_time = int(time.time())
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/backend.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/backend.py
index 4faca73..7bab979 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/backend.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/backend.py
@@ -16,19 +16,21 @@ from __future__ import absolute_import, division, print_function
from collections import namedtuple
from cryptography import utils
-from cryptography.exceptions import (
- InternalError, InvalidTag, UnsupportedAlgorithm, _Reasons
+from cryptography.exceptions import InternalError
+from cryptography.hazmat.backends.commoncrypto.ciphers import (
+ _CipherContext, _GCMCipherContext
)
+from cryptography.hazmat.backends.commoncrypto.hashes import _HashContext
+from cryptography.hazmat.backends.commoncrypto.hmac import _HMACContext
from cryptography.hazmat.backends.interfaces import (
CipherBackend, HMACBackend, HashBackend, PBKDF2HMACBackend
)
from cryptography.hazmat.bindings.commoncrypto.binding import Binding
-from cryptography.hazmat.primitives import constant_time, interfaces
from cryptography.hazmat.primitives.ciphers.algorithms import (
AES, ARC4, Blowfish, CAST5, TripleDES
)
from cryptography.hazmat.primitives.ciphers.modes import (
- CBC, CFB, CTR, ECB, GCM, OFB
+ CBC, CFB, CFB8, CTR, ECB, GCM, OFB
)
@@ -147,14 +149,14 @@ class Backend(object):
buf,
length
)
- self._check_response(res)
+ self._check_cipher_response(res)
return self._ffi.buffer(buf)[:]
def _register_cipher_adapter(self, cipher_cls, cipher_const, mode_cls,
mode_const):
if (cipher_cls, mode_cls) in self._cipher_registry:
- raise ValueError("Duplicate registration for: {0} {1}".format(
+ raise ValueError("Duplicate registration for: {0} {1}.".format(
cipher_cls, mode_cls)
)
self._cipher_registry[cipher_cls, mode_cls] = (cipher_const,
@@ -165,6 +167,7 @@ class Backend(object):
(CBC, self._lib.kCCModeCBC),
(ECB, self._lib.kCCModeECB),
(CFB, self._lib.kCCModeCFB),
+ (CFB8, self._lib.kCCModeCFB8),
(OFB, self._lib.kCCModeOFB),
(CTR, self._lib.kCCModeCTR),
(GCM, self._lib.kCCModeGCM),
@@ -177,7 +180,9 @@ class Backend(object):
)
for mode_cls, mode_const in [
(CBC, self._lib.kCCModeCBC),
+ (ECB, self._lib.kCCModeECB),
(CFB, self._lib.kCCModeCFB),
+ (CFB8, self._lib.kCCModeCFB8),
(OFB, self._lib.kCCModeOFB),
]:
self._register_cipher_adapter(
@@ -218,7 +223,7 @@ class Backend(object):
self._lib.kCCModeRC4
)
- def _check_response(self, response):
+ def _check_cipher_response(self, response):
if response == self._lib.kCCSuccess:
return
elif response == self._lib.kCCAlignmentError:
@@ -226,7 +231,7 @@ class Backend(object):
# rdar://15589470
raise ValueError(
"The length of the provided data is not a multiple of "
- "the block length"
+ "the block length."
)
else:
raise InternalError(
@@ -234,266 +239,15 @@ class Backend(object):
" Code: {0}.".format(response)
)
-
-def _release_cipher_ctx(ctx):
- """
- Called by the garbage collector and used to safely dereference and
- release the context.
- """
- if ctx[0] != backend._ffi.NULL:
- res = backend._lib.CCCryptorRelease(ctx[0])
- backend._check_response(res)
- ctx[0] = backend._ffi.NULL
-
-
-@utils.register_interface(interfaces.CipherContext)
-class _CipherContext(object):
- def __init__(self, backend, cipher, mode, operation):
- self._backend = backend
- self._cipher = cipher
- self._mode = mode
- self._operation = operation
- # There is a bug in CommonCrypto where block ciphers do not raise
- # kCCAlignmentError when finalizing if you supply non-block aligned
- # data. To work around this we need to keep track of the block
- # alignment ourselves, but only for alg+mode combos that require
- # block alignment. OFB, CFB, and CTR make a block cipher algorithm
- # into a stream cipher so we don't need to track them (and thus their
- # block size is effectively 1 byte just like OpenSSL/CommonCrypto
- # treat RC4 and other stream cipher block sizes).
- # This bug has been filed as rdar://15589470
- self._bytes_processed = 0
- if (isinstance(cipher, interfaces.BlockCipherAlgorithm) and not
- isinstance(mode, (OFB, CFB, CTR))):
- self._byte_block_size = cipher.block_size // 8
- else:
- self._byte_block_size = 1
-
- registry = self._backend._cipher_registry
- try:
- cipher_enum, mode_enum = registry[type(cipher), type(mode)]
- except KeyError:
- raise UnsupportedAlgorithm(
- "cipher {0} in {1} mode is not supported "
- "by this backend".format(
- cipher.name, mode.name if mode else mode),
- _Reasons.UNSUPPORTED_CIPHER
- )
-
- ctx = self._backend._ffi.new("CCCryptorRef *")
- ctx = self._backend._ffi.gc(ctx, _release_cipher_ctx)
-
- if isinstance(mode, interfaces.ModeWithInitializationVector):
- iv_nonce = mode.initialization_vector
- elif isinstance(mode, interfaces.ModeWithNonce):
- iv_nonce = mode.nonce
- else:
- iv_nonce = self._backend._ffi.NULL
-
- if isinstance(mode, CTR):
- mode_option = self._backend._lib.kCCModeOptionCTR_BE
- else:
- mode_option = 0
-
- res = self._backend._lib.CCCryptorCreateWithMode(
- operation,
- mode_enum, cipher_enum,
- self._backend._lib.ccNoPadding, iv_nonce,
- cipher.key, len(cipher.key),
- self._backend._ffi.NULL, 0, 0, mode_option, ctx)
- self._backend._check_response(res)
-
- self._ctx = ctx
-
- def update(self, data):
- # Count bytes processed to handle block alignment.
- self._bytes_processed += len(data)
- buf = self._backend._ffi.new(
- "unsigned char[]", len(data) + self._byte_block_size - 1)
- outlen = self._backend._ffi.new("size_t *")
- res = self._backend._lib.CCCryptorUpdate(
- self._ctx[0], data, len(data), buf,
- len(data) + self._byte_block_size - 1, outlen)
- self._backend._check_response(res)
- return self._backend._ffi.buffer(buf)[:outlen[0]]
-
- def finalize(self):
- # Raise error if block alignment is wrong.
- if self._bytes_processed % self._byte_block_size:
- raise ValueError(
- "The length of the provided data is not a multiple of "
- "the block length"
- )
- buf = self._backend._ffi.new("unsigned char[]", self._byte_block_size)
- outlen = self._backend._ffi.new("size_t *")
- res = self._backend._lib.CCCryptorFinal(
- self._ctx[0], buf, len(buf), outlen)
- self._backend._check_response(res)
- _release_cipher_ctx(self._ctx)
- return self._backend._ffi.buffer(buf)[:outlen[0]]
-
-
-@utils.register_interface(interfaces.AEADCipherContext)
-@utils.register_interface(interfaces.AEADEncryptionContext)
-class _GCMCipherContext(object):
- def __init__(self, backend, cipher, mode, operation):
- self._backend = backend
- self._cipher = cipher
- self._mode = mode
- self._operation = operation
- self._tag = None
-
- registry = self._backend._cipher_registry
- try:
- cipher_enum, mode_enum = registry[type(cipher), type(mode)]
- except KeyError:
- raise UnsupportedAlgorithm(
- "cipher {0} in {1} mode is not supported "
- "by this backend".format(
- cipher.name, mode.name if mode else mode),
- _Reasons.UNSUPPORTED_CIPHER
- )
-
- ctx = self._backend._ffi.new("CCCryptorRef *")
- ctx = self._backend._ffi.gc(ctx, _release_cipher_ctx)
-
- self._ctx = ctx
-
- res = self._backend._lib.CCCryptorCreateWithMode(
- operation,
- mode_enum, cipher_enum,
- self._backend._lib.ccNoPadding,
- self._backend._ffi.NULL,
- cipher.key, len(cipher.key),
- self._backend._ffi.NULL, 0, 0, 0, self._ctx)
- self._backend._check_response(res)
-
- res = self._backend._lib.CCCryptorGCMAddIV(
- self._ctx[0],
- mode.initialization_vector,
- len(mode.initialization_vector)
- )
- self._backend._check_response(res)
-
- def update(self, data):
- buf = self._backend._ffi.new("unsigned char[]", len(data))
- args = (self._ctx[0], data, len(data), buf)
- if self._operation == self._backend._lib.kCCEncrypt:
- res = self._backend._lib.CCCryptorGCMEncrypt(*args)
- else:
- res = self._backend._lib.CCCryptorGCMDecrypt(*args)
-
- self._backend._check_response(res)
- return self._backend._ffi.buffer(buf)[:]
-
- def finalize(self):
- tag_size = self._cipher.block_size // 8
- tag_buf = self._backend._ffi.new("unsigned char[]", tag_size)
- tag_len = self._backend._ffi.new("size_t *", tag_size)
- res = backend._lib.CCCryptorGCMFinal(self._ctx[0], tag_buf, tag_len)
- self._backend._check_response(res)
- _release_cipher_ctx(self._ctx)
- self._tag = self._backend._ffi.buffer(tag_buf)[:]
- if (self._operation == self._backend._lib.kCCDecrypt and
- not constant_time.bytes_eq(
- self._tag[:len(self._mode.tag)], self._mode.tag
- )):
- raise InvalidTag
- return b""
-
- def authenticate_additional_data(self, data):
- res = self._backend._lib.CCCryptorGCMAddAAD(
- self._ctx[0], data, len(data)
- )
- self._backend._check_response(res)
-
- @property
- def tag(self):
- return self._tag
-
-
-@utils.register_interface(interfaces.HashContext)
-class _HashContext(object):
- def __init__(self, backend, algorithm, ctx=None):
- self.algorithm = algorithm
- self._backend = backend
-
- if ctx is None:
- try:
- methods = self._backend._hash_mapping[self.algorithm.name]
- except KeyError:
- raise UnsupportedAlgorithm(
- "{0} is not a supported hash on this backend".format(
- algorithm.name),
- _Reasons.UNSUPPORTED_HASH
- )
- ctx = self._backend._ffi.new(methods.ctx)
- res = methods.hash_init(ctx)
- assert res == 1
-
- self._ctx = ctx
-
- def copy(self):
- methods = self._backend._hash_mapping[self.algorithm.name]
- new_ctx = self._backend._ffi.new(methods.ctx)
- # CommonCrypto has no APIs for copying hashes, so we have to copy the
- # underlying struct.
- new_ctx[0] = self._ctx[0]
-
- return _HashContext(self._backend, self.algorithm, ctx=new_ctx)
-
- def update(self, data):
- methods = self._backend._hash_mapping[self.algorithm.name]
- res = methods.hash_update(self._ctx, data, len(data))
- assert res == 1
-
- def finalize(self):
- methods = self._backend._hash_mapping[self.algorithm.name]
- buf = self._backend._ffi.new("unsigned char[]",
- self.algorithm.digest_size)
- res = methods.hash_final(buf, self._ctx)
- assert res == 1
- return self._backend._ffi.buffer(buf)[:]
-
-
-@utils.register_interface(interfaces.HashContext)
-class _HMACContext(object):
- def __init__(self, backend, key, algorithm, ctx=None):
- self.algorithm = algorithm
- self._backend = backend
- if ctx is None:
- ctx = self._backend._ffi.new("CCHmacContext *")
- try:
- alg = self._backend._supported_hmac_algorithms[algorithm.name]
- except KeyError:
- raise UnsupportedAlgorithm(
- "{0} is not a supported HMAC hash on this backend".format(
- algorithm.name),
- _Reasons.UNSUPPORTED_HASH
- )
-
- self._backend._lib.CCHmacInit(ctx, alg, key, len(key))
-
- self._ctx = ctx
- self._key = key
-
- def copy(self):
- copied_ctx = self._backend._ffi.new("CCHmacContext *")
- # CommonCrypto has no APIs for copying HMACs, so we have to copy the
- # underlying struct.
- copied_ctx[0] = self._ctx[0]
- return _HMACContext(
- self._backend, self._key, self.algorithm, ctx=copied_ctx
- )
-
- def update(self, data):
- self._backend._lib.CCHmacUpdate(self._ctx, data, len(data))
-
- def finalize(self):
- buf = self._backend._ffi.new("unsigned char[]",
- self.algorithm.digest_size)
- self._backend._lib.CCHmacFinal(self._ctx, buf)
- return self._backend._ffi.buffer(buf)[:]
+ def _release_cipher_ctx(self, ctx):
+ """
+ Called by the garbage collector and used to safely dereference and
+ release the context.
+ """
+ if ctx[0] != self._ffi.NULL:
+ res = self._lib.CCCryptorRelease(ctx[0])
+ self._check_cipher_response(res)
+ ctx[0] = self._ffi.NULL
backend = Backend()
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/ciphers.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/ciphers.py
new file mode 100644
index 0000000..525500c
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/ciphers.py
@@ -0,0 +1,191 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+from cryptography import utils
+from cryptography.exceptions import (
+ InvalidTag, UnsupportedAlgorithm, _Reasons
+)
+from cryptography.hazmat.primitives import constant_time, interfaces
+from cryptography.hazmat.primitives.ciphers.modes import (
+ CFB, CFB8, CTR, OFB
+)
+
+
+@utils.register_interface(interfaces.CipherContext)
+class _CipherContext(object):
+ def __init__(self, backend, cipher, mode, operation):
+ self._backend = backend
+ self._cipher = cipher
+ self._mode = mode
+ self._operation = operation
+ # There is a bug in CommonCrypto where block ciphers do not raise
+ # kCCAlignmentError when finalizing if you supply non-block aligned
+ # data. To work around this we need to keep track of the block
+ # alignment ourselves, but only for alg+mode combos that require
+ # block alignment. OFB, CFB, and CTR make a block cipher algorithm
+ # into a stream cipher so we don't need to track them (and thus their
+ # block size is effectively 1 byte just like OpenSSL/CommonCrypto
+ # treat RC4 and other stream cipher block sizes).
+ # This bug has been filed as rdar://15589470
+ self._bytes_processed = 0
+ if (isinstance(cipher, interfaces.BlockCipherAlgorithm) and not
+ isinstance(mode, (OFB, CFB, CFB8, CTR))):
+ self._byte_block_size = cipher.block_size // 8
+ else:
+ self._byte_block_size = 1
+
+ registry = self._backend._cipher_registry
+ try:
+ cipher_enum, mode_enum = registry[type(cipher), type(mode)]
+ except KeyError:
+ raise UnsupportedAlgorithm(
+ "cipher {0} in {1} mode is not supported "
+ "by this backend.".format(
+ cipher.name, mode.name if mode else mode),
+ _Reasons.UNSUPPORTED_CIPHER
+ )
+
+ ctx = self._backend._ffi.new("CCCryptorRef *")
+ ctx = self._backend._ffi.gc(ctx, self._backend._release_cipher_ctx)
+
+ if isinstance(mode, interfaces.ModeWithInitializationVector):
+ iv_nonce = mode.initialization_vector
+ elif isinstance(mode, interfaces.ModeWithNonce):
+ iv_nonce = mode.nonce
+ else:
+ iv_nonce = self._backend._ffi.NULL
+
+ if isinstance(mode, CTR):
+ mode_option = self._backend._lib.kCCModeOptionCTR_BE
+ else:
+ mode_option = 0
+
+ res = self._backend._lib.CCCryptorCreateWithMode(
+ operation,
+ mode_enum, cipher_enum,
+ self._backend._lib.ccNoPadding, iv_nonce,
+ cipher.key, len(cipher.key),
+ self._backend._ffi.NULL, 0, 0, mode_option, ctx)
+ self._backend._check_cipher_response(res)
+
+ self._ctx = ctx
+
+ def update(self, data):
+ # Count bytes processed to handle block alignment.
+ self._bytes_processed += len(data)
+ buf = self._backend._ffi.new(
+ "unsigned char[]", len(data) + self._byte_block_size - 1)
+ outlen = self._backend._ffi.new("size_t *")
+ res = self._backend._lib.CCCryptorUpdate(
+ self._ctx[0], data, len(data), buf,
+ len(data) + self._byte_block_size - 1, outlen)
+ self._backend._check_cipher_response(res)
+ return self._backend._ffi.buffer(buf)[:outlen[0]]
+
+ def finalize(self):
+ # Raise error if block alignment is wrong.
+ if self._bytes_processed % self._byte_block_size:
+ raise ValueError(
+ "The length of the provided data is not a multiple of "
+ "the block length."
+ )
+ buf = self._backend._ffi.new("unsigned char[]", self._byte_block_size)
+ outlen = self._backend._ffi.new("size_t *")
+ res = self._backend._lib.CCCryptorFinal(
+ self._ctx[0], buf, len(buf), outlen)
+ self._backend._check_cipher_response(res)
+ self._backend._release_cipher_ctx(self._ctx)
+ return self._backend._ffi.buffer(buf)[:outlen[0]]
+
+
+@utils.register_interface(interfaces.AEADCipherContext)
+@utils.register_interface(interfaces.AEADEncryptionContext)
+class _GCMCipherContext(object):
+ def __init__(self, backend, cipher, mode, operation):
+ self._backend = backend
+ self._cipher = cipher
+ self._mode = mode
+ self._operation = operation
+ self._tag = None
+
+ registry = self._backend._cipher_registry
+ try:
+ cipher_enum, mode_enum = registry[type(cipher), type(mode)]
+ except KeyError:
+ raise UnsupportedAlgorithm(
+ "cipher {0} in {1} mode is not supported "
+ "by this backend.".format(
+ cipher.name, mode.name if mode else mode),
+ _Reasons.UNSUPPORTED_CIPHER
+ )
+
+ ctx = self._backend._ffi.new("CCCryptorRef *")
+ ctx = self._backend._ffi.gc(ctx, self._backend._release_cipher_ctx)
+
+ self._ctx = ctx
+
+ res = self._backend._lib.CCCryptorCreateWithMode(
+ operation,
+ mode_enum, cipher_enum,
+ self._backend._lib.ccNoPadding,
+ self._backend._ffi.NULL,
+ cipher.key, len(cipher.key),
+ self._backend._ffi.NULL, 0, 0, 0, self._ctx)
+ self._backend._check_cipher_response(res)
+
+ res = self._backend._lib.CCCryptorGCMAddIV(
+ self._ctx[0],
+ mode.initialization_vector,
+ len(mode.initialization_vector)
+ )
+ self._backend._check_cipher_response(res)
+
+ def update(self, data):
+ buf = self._backend._ffi.new("unsigned char[]", len(data))
+ args = (self._ctx[0], data, len(data), buf)
+ if self._operation == self._backend._lib.kCCEncrypt:
+ res = self._backend._lib.CCCryptorGCMEncrypt(*args)
+ else:
+ res = self._backend._lib.CCCryptorGCMDecrypt(*args)
+
+ self._backend._check_cipher_response(res)
+ return self._backend._ffi.buffer(buf)[:]
+
+ def finalize(self):
+ tag_size = self._cipher.block_size // 8
+ tag_buf = self._backend._ffi.new("unsigned char[]", tag_size)
+ tag_len = self._backend._ffi.new("size_t *", tag_size)
+ res = self._backend._lib.CCCryptorGCMFinal(
+ self._ctx[0], tag_buf, tag_len
+ )
+ self._backend._check_cipher_response(res)
+ self._backend._release_cipher_ctx(self._ctx)
+ self._tag = self._backend._ffi.buffer(tag_buf)[:]
+ if (self._operation == self._backend._lib.kCCDecrypt and
+ not constant_time.bytes_eq(
+ self._tag[:len(self._mode.tag)], self._mode.tag
+ )):
+ raise InvalidTag
+ return b""
+
+ def authenticate_additional_data(self, data):
+ res = self._backend._lib.CCCryptorGCMAddAAD(
+ self._ctx[0], data, len(data)
+ )
+ self._backend._check_cipher_response(res)
+
+ @property
+ def tag(self):
+ return self._tag
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/hashes.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/hashes.py
new file mode 100644
index 0000000..ebad720
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/hashes.py
@@ -0,0 +1,62 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+from cryptography import utils
+from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
+from cryptography.hazmat.primitives import interfaces
+
+
+@utils.register_interface(interfaces.HashContext)
+class _HashContext(object):
+ def __init__(self, backend, algorithm, ctx=None):
+ self.algorithm = algorithm
+ self._backend = backend
+
+ if ctx is None:
+ try:
+ methods = self._backend._hash_mapping[self.algorithm.name]
+ except KeyError:
+ raise UnsupportedAlgorithm(
+ "{0} is not a supported hash on this backend.".format(
+ algorithm.name),
+ _Reasons.UNSUPPORTED_HASH
+ )
+ ctx = self._backend._ffi.new(methods.ctx)
+ res = methods.hash_init(ctx)
+ assert res == 1
+
+ self._ctx = ctx
+
+ def copy(self):
+ methods = self._backend._hash_mapping[self.algorithm.name]
+ new_ctx = self._backend._ffi.new(methods.ctx)
+ # CommonCrypto has no APIs for copying hashes, so we have to copy the
+ # underlying struct.
+ new_ctx[0] = self._ctx[0]
+
+ return _HashContext(self._backend, self.algorithm, ctx=new_ctx)
+
+ def update(self, data):
+ methods = self._backend._hash_mapping[self.algorithm.name]
+ res = methods.hash_update(self._ctx, data, len(data))
+ assert res == 1
+
+ def finalize(self):
+ methods = self._backend._hash_mapping[self.algorithm.name]
+ buf = self._backend._ffi.new("unsigned char[]",
+ self.algorithm.digest_size)
+ res = methods.hash_final(buf, self._ctx)
+ assert res == 1
+ return self._backend._ffi.buffer(buf)[:]
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/hmac.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/hmac.py
new file mode 100644
index 0000000..ec3a878
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/commoncrypto/hmac.py
@@ -0,0 +1,58 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+from cryptography import utils
+from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
+from cryptography.hazmat.primitives import interfaces
+
+
+@utils.register_interface(interfaces.HashContext)
+class _HMACContext(object):
+ def __init__(self, backend, key, algorithm, ctx=None):
+ self.algorithm = algorithm
+ self._backend = backend
+ if ctx is None:
+ ctx = self._backend._ffi.new("CCHmacContext *")
+ try:
+ alg = self._backend._supported_hmac_algorithms[algorithm.name]
+ except KeyError:
+ raise UnsupportedAlgorithm(
+ "{0} is not a supported HMAC hash on this backend.".format(
+ algorithm.name),
+ _Reasons.UNSUPPORTED_HASH
+ )
+
+ self._backend._lib.CCHmacInit(ctx, alg, key, len(key))
+
+ self._ctx = ctx
+ self._key = key
+
+ def copy(self):
+ copied_ctx = self._backend._ffi.new("CCHmacContext *")
+ # CommonCrypto has no APIs for copying HMACs, so we have to copy the
+ # underlying struct.
+ copied_ctx[0] = self._ctx[0]
+ return _HMACContext(
+ self._backend, self._key, self.algorithm, ctx=copied_ctx
+ )
+
+ def update(self, data):
+ self._backend._lib.CCHmacUpdate(self._ctx, data, len(data))
+
+ def finalize(self):
+ buf = self._backend._ffi.new("unsigned char[]",
+ self.algorithm.digest_size)
+ self._backend._lib.CCHmacFinal(self._ctx, buf)
+ return self._backend._ffi.buffer(buf)[:]
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/interfaces.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/interfaces.py
index 264c5af..5ed4996 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/interfaces.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/interfaces.py
@@ -129,6 +129,31 @@ class RSABackend(object):
Returns encrypted bytes.
"""
+ @abc.abstractmethod
+ def rsa_padding_supported(self, padding):
+ """
+ Returns True if the backend supports the given padding options.
+ """
+
+ @abc.abstractmethod
+ def generate_rsa_parameters_supported(self, public_exponent, key_size):
+ """
+ Returns True if the backend supports the given parameters for key
+ generation.
+ """
+
+ @abc.abstractmethod
+ def load_rsa_private_numbers(self, numbers):
+ """
+ Returns an RSAPrivateKey provider.
+ """
+
+ @abc.abstractmethod
+ def load_rsa_public_numbers(self, numbers):
+ """
+ Returns an RSAPublicKey provider.
+ """
+
@six.add_metaclass(abc.ABCMeta)
class DSABackend(object):
@@ -141,8 +166,14 @@ class DSABackend(object):
@abc.abstractmethod
def generate_dsa_private_key(self, parameters):
"""
- Generate an DSAPrivateKey instance with parameters as
- a DSAParameters object.
+ Generate a DSAPrivateKey instance with parameters as a DSAParameters
+ object.
+ """
+
+ @abc.abstractmethod
+ def generate_dsa_private_key_and_parameters(self, key_size):
+ """
+ Generate a DSAPrivateKey instance using key size only.
"""
@abc.abstractmethod
@@ -171,6 +202,24 @@ class DSABackend(object):
Return True if the parameters are supported by the backend for DSA.
"""
+ @abc.abstractmethod
+ def load_dsa_private_numbers(self, numbers):
+ """
+ Returns a DSAPrivateKey provider.
+ """
+
+ @abc.abstractmethod
+ def load_dsa_public_numbers(self, numbers):
+ """
+ Returns a DSAPublicKey provider.
+ """
+
+ @abc.abstractmethod
+ def load_dsa_parameter_numbers(self, numbers):
+ """
+ Returns a DSAParameters provider.
+ """
+
@six.add_metaclass(abc.ABCMeta)
class TraditionalOpenSSLSerializationBackend(object):
@@ -182,6 +231,16 @@ class TraditionalOpenSSLSerializationBackend(object):
"""
+@six.add_metaclass(abc.ABCMeta)
+class PKCS8SerializationBackend(object):
+ @abc.abstractmethod
+ def load_pkcs8_pem_private_key(self, data, password):
+ """
+ Load a private key from PEM encoded data, using password if the data
+ is encrypted.
+ """
+
+
@six.add_metaclass(abc.ABCMeta)
class CMACBackend(object):
@abc.abstractmethod
@@ -195,3 +254,39 @@ class CMACBackend(object):
"""
Create a CMACContext for calculating a message authentication code.
"""
+
+
+@six.add_metaclass(abc.ABCMeta)
+class EllipticCurveBackend(object):
+ @abc.abstractmethod
+ def elliptic_curve_signature_algorithm_supported(
+ self, signature_algorithm, curve
+ ):
+ """
+ Returns True if the backend supports the named elliptic curve with the
+ specified signature algorithm.
+ """
+
+ @abc.abstractmethod
+ def elliptic_curve_supported(self, curve):
+ """
+ Returns True if the backend supports the named elliptic curve.
+ """
+
+ @abc.abstractmethod
+ def generate_elliptic_curve_private_key(self, curve):
+ """
+ Return an object conforming to the EllipticCurvePrivateKey interface.
+ """
+
+ @abc.abstractmethod
+ def elliptic_curve_public_key_from_numbers(self, numbers):
+ """
+ Return an EllipticCurvePublicKey provider using the given numbers.
+ """
+
+ @abc.abstractmethod
+ def elliptic_curve_private_key_from_numbers(self, numbers):
+ """
+ Return an EllipticCurvePublicKey provider using the given numbers.
+ """
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/multibackend.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/multibackend.py
index 753f4fc..35e2a09 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/multibackend.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/multibackend.py
@@ -16,8 +16,9 @@ from __future__ import absolute_import, division, print_function
from cryptography import utils
from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
from cryptography.hazmat.backends.interfaces import (
- CMACBackend, CipherBackend, DSABackend, HMACBackend, HashBackend,
- PBKDF2HMACBackend, RSABackend
+ CMACBackend, CipherBackend, DSABackend, EllipticCurveBackend, HMACBackend,
+ HashBackend, PBKDF2HMACBackend, PKCS8SerializationBackend,
+ RSABackend, TraditionalOpenSSLSerializationBackend
)
@@ -26,8 +27,11 @@ from cryptography.hazmat.backends.interfaces import (
@utils.register_interface(HashBackend)
@utils.register_interface(HMACBackend)
@utils.register_interface(PBKDF2HMACBackend)
+@utils.register_interface(PKCS8SerializationBackend)
@utils.register_interface(RSABackend)
+@utils.register_interface(TraditionalOpenSSLSerializationBackend)
@utils.register_interface(DSABackend)
+@utils.register_interface(EllipticCurveBackend)
class MultiBackend(object):
name = "multibackend"
@@ -52,7 +56,7 @@ class MultiBackend(object):
except UnsupportedAlgorithm:
pass
raise UnsupportedAlgorithm(
- "cipher {0} in {1} mode is not supported by this backend".format(
+ "cipher {0} in {1} mode is not supported by this backend.".format(
algorithm.name, mode.name if mode else mode),
_Reasons.UNSUPPORTED_CIPHER
)
@@ -64,7 +68,7 @@ class MultiBackend(object):
except UnsupportedAlgorithm:
pass
raise UnsupportedAlgorithm(
- "cipher {0} in {1} mode is not supported by this backend".format(
+ "cipher {0} in {1} mode is not supported by this backend.".format(
algorithm.name, mode.name if mode else mode),
_Reasons.UNSUPPORTED_CIPHER
)
@@ -82,7 +86,7 @@ class MultiBackend(object):
except UnsupportedAlgorithm:
pass
raise UnsupportedAlgorithm(
- "{0} is not a supported hash on this backend".format(
+ "{0} is not a supported hash on this backend.".format(
algorithm.name),
_Reasons.UNSUPPORTED_HASH
)
@@ -100,7 +104,7 @@ class MultiBackend(object):
except UnsupportedAlgorithm:
pass
raise UnsupportedAlgorithm(
- "{0} is not a supported hash on this backend".format(
+ "{0} is not a supported hash on this backend.".format(
algorithm.name),
_Reasons.UNSUPPORTED_HASH
)
@@ -121,7 +125,7 @@ class MultiBackend(object):
except UnsupportedAlgorithm:
pass
raise UnsupportedAlgorithm(
- "{0} is not a supported hash on this backend".format(
+ "{0} is not a supported hash on this backend.".format(
algorithm.name),
_Reasons.UNSUPPORTED_HASH
)
@@ -129,13 +133,21 @@ class MultiBackend(object):
def generate_rsa_private_key(self, public_exponent, key_size):
for b in self._filtered_backends(RSABackend):
return b.generate_rsa_private_key(public_exponent, key_size)
- raise UnsupportedAlgorithm("RSA is not supported by the backend",
+ raise UnsupportedAlgorithm("RSA is not supported by the backend.",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
+
+ def generate_rsa_parameters_supported(self, public_exponent, key_size):
+ for b in self._filtered_backends(RSABackend):
+ return b.generate_rsa_parameters_supported(
+ public_exponent, key_size
+ )
+ raise UnsupportedAlgorithm("RSA is not supported by the backend.",
_Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
def create_rsa_signature_ctx(self, private_key, padding, algorithm):
for b in self._filtered_backends(RSABackend):
return b.create_rsa_signature_ctx(private_key, padding, algorithm)
- raise UnsupportedAlgorithm("RSA is not supported by the backend",
+ raise UnsupportedAlgorithm("RSA is not supported by the backend.",
_Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
def create_rsa_verification_ctx(self, public_key, signature, padding,
@@ -143,44 +155,88 @@ class MultiBackend(object):
for b in self._filtered_backends(RSABackend):
return b.create_rsa_verification_ctx(public_key, signature,
padding, algorithm)
+ raise UnsupportedAlgorithm("RSA is not supported by the backend.",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
+
+ def mgf1_hash_supported(self, algorithm):
+ for b in self._filtered_backends(RSABackend):
+ return b.mgf1_hash_supported(algorithm)
+ raise UnsupportedAlgorithm("RSA is not supported by the backend.",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
+
+ def decrypt_rsa(self, private_key, ciphertext, padding):
+ for b in self._filtered_backends(RSABackend):
+ return b.decrypt_rsa(private_key, ciphertext, padding)
+ raise UnsupportedAlgorithm("RSA is not supported by the backend.",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
+
+ def encrypt_rsa(self, public_key, plaintext, padding):
+ for b in self._filtered_backends(RSABackend):
+ return b.encrypt_rsa(public_key, plaintext, padding)
+ raise UnsupportedAlgorithm("RSA is not supported by the backend.",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
+
+ def rsa_padding_supported(self, padding):
+ for b in self._filtered_backends(RSABackend):
+ return b.rsa_padding_supported(padding)
+ raise UnsupportedAlgorithm("RSA is not supported by the backend.",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
+
+ def load_rsa_private_numbers(self, numbers):
+ for b in self._filtered_backends(RSABackend):
+ return b.load_rsa_private_numbers(numbers)
+
+ raise UnsupportedAlgorithm("RSA is not supported by the backend",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
+
+ def load_rsa_public_numbers(self, numbers):
+ for b in self._filtered_backends(RSABackend):
+ return b.load_rsa_public_numbers(numbers)
+
raise UnsupportedAlgorithm("RSA is not supported by the backend",
_Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
def generate_dsa_parameters(self, key_size):
for b in self._filtered_backends(DSABackend):
return b.generate_dsa_parameters(key_size)
- raise UnsupportedAlgorithm("DSA is not supported by the backend",
+ raise UnsupportedAlgorithm("DSA is not supported by the backend.",
_Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
def generate_dsa_private_key(self, parameters):
for b in self._filtered_backends(DSABackend):
return b.generate_dsa_private_key(parameters)
- raise UnsupportedAlgorithm("DSA is not supported by the backend",
+ raise UnsupportedAlgorithm("DSA is not supported by the backend.",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
+
+ def generate_dsa_private_key_and_parameters(self, key_size):
+ for b in self._filtered_backends(DSABackend):
+ return b.generate_dsa_private_key_and_parameters(key_size)
+ raise UnsupportedAlgorithm("DSA is not supported by the backend.",
_Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
def create_dsa_verification_ctx(self, public_key, signature, algorithm):
for b in self._filtered_backends(DSABackend):
return b.create_dsa_verification_ctx(public_key, signature,
algorithm)
- raise UnsupportedAlgorithm("DSA is not supported by the backend",
+ raise UnsupportedAlgorithm("DSA is not supported by the backend.",
_Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
def create_dsa_signature_ctx(self, private_key, algorithm):
for b in self._filtered_backends(DSABackend):
return b.create_dsa_signature_ctx(private_key, algorithm)
- raise UnsupportedAlgorithm("DSA is not supported by the backend",
+ raise UnsupportedAlgorithm("DSA is not supported by the backend.",
_Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
def dsa_hash_supported(self, algorithm):
for b in self._filtered_backends(DSABackend):
return b.dsa_hash_supported(algorithm)
- raise UnsupportedAlgorithm("DSA is not supported by the backend",
+ raise UnsupportedAlgorithm("DSA is not supported by the backend.",
_Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
def dsa_parameters_supported(self, p, q, g):
for b in self._filtered_backends(DSABackend):
return b.dsa_parameters_supported(p, q, g)
- raise UnsupportedAlgorithm("DSA is not supported by the backend",
+ raise UnsupportedAlgorithm("DSA is not supported by the backend.",
_Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
def cmac_algorithm_supported(self, algorithm):
@@ -195,5 +251,77 @@ class MultiBackend(object):
return b.create_cmac_ctx(algorithm)
except UnsupportedAlgorithm:
pass
- raise UnsupportedAlgorithm("This backend does not support CMAC",
+ raise UnsupportedAlgorithm("This backend does not support CMAC.",
_Reasons.UNSUPPORTED_CIPHER)
+
+ def elliptic_curve_supported(self, curve):
+ return any(
+ b.elliptic_curve_supported(curve)
+ for b in self._filtered_backends(EllipticCurveBackend)
+ )
+
+ def elliptic_curve_signature_algorithm_supported(
+ self, signature_algorithm, curve
+ ):
+ return any(
+ b.elliptic_curve_signature_algorithm_supported(
+ signature_algorithm, curve
+ )
+ for b in self._filtered_backends(EllipticCurveBackend)
+ )
+
+ def generate_elliptic_curve_private_key(self, curve):
+ for b in self._filtered_backends(EllipticCurveBackend):
+ try:
+ return b.generate_elliptic_curve_private_key(curve)
+ except UnsupportedAlgorithm:
+ continue
+
+ raise UnsupportedAlgorithm(
+ "This backend does not support this elliptic curve.",
+ _Reasons.UNSUPPORTED_ELLIPTIC_CURVE
+ )
+
+ def elliptic_curve_private_key_from_numbers(self, numbers):
+ for b in self._filtered_backends(EllipticCurveBackend):
+ try:
+ return b.elliptic_curve_private_key_from_numbers(numbers)
+ except UnsupportedAlgorithm:
+ continue
+
+ raise UnsupportedAlgorithm(
+ "This backend does not support this elliptic curve.",
+ _Reasons.UNSUPPORTED_ELLIPTIC_CURVE
+ )
+
+ def elliptic_curve_public_key_from_numbers(self, numbers):
+ for b in self._filtered_backends(EllipticCurveBackend):
+ try:
+ return b.elliptic_curve_public_key_from_numbers(numbers)
+ except UnsupportedAlgorithm:
+ continue
+
+ raise UnsupportedAlgorithm(
+ "This backend does not support this elliptic curve.",
+ _Reasons.UNSUPPORTED_ELLIPTIC_CURVE
+ )
+
+ def load_pkcs8_pem_private_key(self, data, password):
+ for b in self._filtered_backends(PKCS8SerializationBackend):
+ return b.load_pkcs8_pem_private_key(data, password)
+
+ raise UnsupportedAlgorithm(
+ "This backend does not support this key serialization.",
+ _Reasons.UNSUPPORTED_SERIALIZATION
+ )
+
+ def load_traditional_openssl_pem_private_key(self, data, password):
+ for b in self._filtered_backends(
+ TraditionalOpenSSLSerializationBackend
+ ):
+ return b.load_traditional_openssl_pem_private_key(data, password)
+
+ raise UnsupportedAlgorithm(
+ "This backend does not support this key serialization.",
+ _Reasons.UNSUPPORTED_SERIALIZATION
+ )
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py
index e00be92..4991177 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/backend.py
@@ -15,22 +15,39 @@ from __future__ import absolute_import, division, print_function
import collections
import itertools
-import math
+import warnings
import six
from cryptography import utils
from cryptography.exceptions import (
- AlreadyFinalized, InternalError, InvalidSignature, InvalidTag,
- UnsupportedAlgorithm, _Reasons
+ InternalError, UnsupportedAlgorithm, _Reasons
)
from cryptography.hazmat.backends.interfaces import (
- CMACBackend, CipherBackend, DSABackend, HMACBackend, HashBackend,
- PBKDF2HMACBackend, RSABackend
+ CMACBackend, CipherBackend, DSABackend, EllipticCurveBackend, HMACBackend,
+ HashBackend, PBKDF2HMACBackend, PKCS8SerializationBackend, RSABackend,
+ TraditionalOpenSSLSerializationBackend
+)
+from cryptography.hazmat.backends.openssl.ciphers import (
+ _AESCTRCipherContext, _CipherContext
+)
+from cryptography.hazmat.backends.openssl.cmac import _CMACContext
+from cryptography.hazmat.backends.openssl.dsa import (
+ _DSAParameters, _DSAPrivateKey, _DSAPublicKey,
+ _DSASignatureContext, _DSAVerificationContext
+)
+from cryptography.hazmat.backends.openssl.ec import (
+ _EllipticCurvePrivateKey, _EllipticCurvePublicKey
+)
+from cryptography.hazmat.backends.openssl.hashes import _HashContext
+from cryptography.hazmat.backends.openssl.hmac import _HMACContext
+from cryptography.hazmat.backends.openssl.rsa import (
+ _RSAPrivateKey, _RSAPublicKey, _RSASignatureContext,
+ _RSAVerificationContext
)
from cryptography.hazmat.bindings.openssl.binding import Binding
-from cryptography.hazmat.primitives import hashes, interfaces
-from cryptography.hazmat.primitives.asymmetric import dsa, rsa
+from cryptography.hazmat.primitives import hashes
+from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa
from cryptography.hazmat.primitives.asymmetric.padding import (
MGF1, OAEP, PKCS1v15, PSS
)
@@ -38,10 +55,11 @@ from cryptography.hazmat.primitives.ciphers.algorithms import (
AES, ARC4, Blowfish, CAST5, Camellia, IDEA, SEED, TripleDES
)
from cryptography.hazmat.primitives.ciphers.modes import (
- CBC, CFB, CTR, ECB, GCM, OFB
+ CBC, CFB, CFB8, CTR, ECB, GCM, OFB
)
+_MemoryBIO = collections.namedtuple("_MemoryBIO", ["bio", "char_ptr"])
_OpenSSLError = collections.namedtuple("_OpenSSLError",
["code", "lib", "func", "reason"])
@@ -49,10 +67,13 @@ _OpenSSLError = collections.namedtuple("_OpenSSLError",
@utils.register_interface(CipherBackend)
@utils.register_interface(CMACBackend)
@utils.register_interface(DSABackend)
+@utils.register_interface(EllipticCurveBackend)
@utils.register_interface(HashBackend)
@utils.register_interface(HMACBackend)
@utils.register_interface(PBKDF2HMACBackend)
+@utils.register_interface(PKCS8SerializationBackend)
@utils.register_interface(RSABackend)
+@utils.register_interface(TraditionalOpenSSLSerializationBackend)
class Backend(object):
"""
OpenSSL API binding interfaces.
@@ -112,11 +133,14 @@ class Backend(object):
def openssl_version_text(self):
"""
- Friendly string name of linked OpenSSL.
+ Friendly string name of the loaded OpenSSL library. This is not
+ necessarily the same version as it was compiled against.
Example: OpenSSL 1.0.1e 11 Feb 2013
"""
- return self._ffi.string(self._lib.OPENSSL_VERSION_TEXT).decode("ascii")
+ return self._ffi.string(
+ self._lib.SSLeay_version(self._lib.SSLEAY_VERSION)
+ ).decode("ascii")
def create_hmac_ctx(self, key, algorithm):
return _HMACContext(self, key, algorithm)
@@ -132,6 +156,14 @@ class Backend(object):
return _HashContext(self, algorithm)
def cipher_supported(self, cipher, mode):
+ if self._evp_cipher_supported(cipher, mode):
+ return True
+ elif isinstance(mode, CTR) and isinstance(cipher, AES):
+ return True
+ else:
+ return False
+
+ def _evp_cipher_supported(self, cipher, mode):
try:
adapter = self._cipher_registry[type(cipher), type(mode)]
except KeyError:
@@ -141,27 +173,35 @@ class Backend(object):
def register_cipher_adapter(self, cipher_cls, mode_cls, adapter):
if (cipher_cls, mode_cls) in self._cipher_registry:
- raise ValueError("Duplicate registration for: {0} {1}".format(
+ raise ValueError("Duplicate registration for: {0} {1}.".format(
cipher_cls, mode_cls)
)
self._cipher_registry[cipher_cls, mode_cls] = adapter
def _register_default_ciphers(self):
- for cipher_cls, mode_cls in itertools.product(
- [AES, Camellia],
- [CBC, CTR, ECB, OFB, CFB],
- ):
+ for mode_cls in [CBC, CTR, ECB, OFB, CFB, CFB8]:
self.register_cipher_adapter(
- cipher_cls,
+ AES,
mode_cls,
GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}")
)
- for mode_cls in [CBC, CFB, OFB]:
+ for mode_cls in [CBC, CTR, ECB, OFB, CFB]:
+ self.register_cipher_adapter(
+ Camellia,
+ mode_cls,
+ GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}")
+ )
+ for mode_cls in [CBC, CFB, CFB8, OFB]:
self.register_cipher_adapter(
TripleDES,
mode_cls,
GetCipherByName("des-ede3-{mode.name}")
)
+ self.register_cipher_adapter(
+ TripleDES,
+ ECB,
+ GetCipherByName("des-ede3")
+ )
for mode_cls in [CBC, CFB, OFB, ECB]:
self.register_cipher_adapter(
Blowfish,
@@ -195,10 +235,24 @@ class Backend(object):
)
def create_symmetric_encryption_ctx(self, cipher, mode):
- return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT)
+ if (isinstance(mode, CTR) and isinstance(cipher, AES)
+ and not self._evp_cipher_supported(cipher, mode)):
+ # This is needed to provide support for AES CTR mode in OpenSSL
+ # 0.9.8. It can be removed when we drop 0.9.8 support (RHEL 5
+ # extended life ends 2020).
+ return _AESCTRCipherContext(self, cipher, mode)
+ else:
+ return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT)
def create_symmetric_decryption_ctx(self, cipher, mode):
- return _CipherContext(self, cipher, mode, _CipherContext._DECRYPT)
+ if (isinstance(mode, CTR) and isinstance(cipher, AES)
+ and not self._evp_cipher_supported(cipher, mode)):
+ # This is needed to provide support for AES CTR mode in OpenSSL
+ # 0.9.8. It can be removed when we drop 0.9.8 support (RHEL 5
+ # extended life ends 2020).
+ return _AESCTRCipherContext(self, cipher, mode)
+ else:
+ return _CipherContext(self, cipher, mode, _CipherContext._DECRYPT)
def pbkdf2_hmac_supported(self, algorithm):
if self._lib.Cryptography_HAS_PBKDF2_HMAC:
@@ -231,7 +285,7 @@ class Backend(object):
if not isinstance(algorithm, hashes.SHA1):
raise UnsupportedAlgorithm(
"This version of OpenSSL only supports PBKDF2HMAC with "
- "SHA1",
+ "SHA1.",
_Reasons.UNSUPPORTED_HASH
)
res = self._lib.PKCS5_PBKDF2_HMAC_SHA1(
@@ -269,7 +323,7 @@ class Backend(object):
def _unknown_error(self, error):
return InternalError(
"Unknown error code {0} from OpenSSL, "
- "you should probably file a bug. {1}".format(
+ "you should probably file a bug. {1}.".format(
error.code, self._err_string(error.code)
)
)
@@ -325,69 +379,137 @@ class Backend(object):
return bn_ptr[0]
def generate_rsa_private_key(self, public_exponent, key_size):
- if public_exponent < 3:
- raise ValueError("public_exponent must be >= 3")
+ rsa._verify_rsa_parameters(public_exponent, key_size)
- if public_exponent & 1 == 0:
- raise ValueError("public_exponent must be odd")
-
- if key_size < 512:
- raise ValueError("key_size must be at least 512-bits")
-
- ctx = self._lib.RSA_new()
- assert ctx != self._ffi.NULL
- ctx = self._ffi.gc(ctx, self._lib.RSA_free)
+ rsa_cdata = self._lib.RSA_new()
+ assert rsa_cdata != self._ffi.NULL
+ rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
bn = self._int_to_bn(public_exponent)
bn = self._ffi.gc(bn, self._lib.BN_free)
res = self._lib.RSA_generate_key_ex(
- ctx, key_size, bn, self._ffi.NULL
+ rsa_cdata, key_size, bn, self._ffi.NULL
)
assert res == 1
- return self._rsa_cdata_to_private_key(ctx)
+ return _RSAPrivateKey(self, rsa_cdata)
- def _new_evp_pkey(self):
- evp_pkey = self._lib.EVP_PKEY_new()
- assert evp_pkey != self._ffi.NULL
- return self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
+ def generate_rsa_parameters_supported(self, public_exponent, key_size):
+ return (public_exponent >= 3 and public_exponent & 1 != 0 and
+ key_size >= 512)
- def _rsa_private_key_to_evp_pkey(self, private_key):
- evp_pkey = self._new_evp_pkey()
- rsa_cdata = self._rsa_cdata_from_private_key(private_key)
-
- res = self._lib.EVP_PKEY_assign_RSA(evp_pkey, rsa_cdata)
+ def load_rsa_private_numbers(self, numbers):
+ rsa._check_private_key_components(
+ numbers.p,
+ numbers.q,
+ numbers.d,
+ numbers.dmp1,
+ numbers.dmq1,
+ numbers.iqmp,
+ numbers.public_numbers.e,
+ numbers.public_numbers.n
+ )
+ rsa_cdata = self._lib.RSA_new()
+ assert rsa_cdata != self._ffi.NULL
+ rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
+ rsa_cdata.p = self._int_to_bn(numbers.p)
+ rsa_cdata.q = self._int_to_bn(numbers.q)
+ rsa_cdata.d = self._int_to_bn(numbers.d)
+ rsa_cdata.dmp1 = self._int_to_bn(numbers.dmp1)
+ rsa_cdata.dmq1 = self._int_to_bn(numbers.dmq1)
+ rsa_cdata.iqmp = self._int_to_bn(numbers.iqmp)
+ rsa_cdata.e = self._int_to_bn(numbers.public_numbers.e)
+ rsa_cdata.n = self._int_to_bn(numbers.public_numbers.n)
+ res = self._lib.RSA_blinding_on(rsa_cdata, self._ffi.NULL)
assert res == 1
- return evp_pkey
+ return _RSAPrivateKey(self, rsa_cdata)
- def _rsa_public_key_to_evp_pkey(self, public_key):
- evp_pkey = self._new_evp_pkey()
- rsa_cdata = self._rsa_cdata_from_public_key(public_key)
-
- res = self._lib.EVP_PKEY_assign_RSA(evp_pkey, rsa_cdata)
+ def load_rsa_public_numbers(self, numbers):
+ rsa._check_public_key_components(numbers.e, numbers.n)
+ rsa_cdata = self._lib.RSA_new()
+ assert rsa_cdata != self._ffi.NULL
+ rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
+ rsa_cdata.e = self._int_to_bn(numbers.e)
+ rsa_cdata.n = self._int_to_bn(numbers.n)
+ res = self._lib.RSA_blinding_on(rsa_cdata, self._ffi.NULL)
assert res == 1
- return evp_pkey
+ return _RSAPublicKey(self, rsa_cdata)
- def _rsa_cdata_to_private_key(self, cdata):
- return rsa.RSAPrivateKey(
- p=self._bn_to_int(cdata.p),
- q=self._bn_to_int(cdata.q),
- dmp1=self._bn_to_int(cdata.dmp1),
- dmq1=self._bn_to_int(cdata.dmq1),
- iqmp=self._bn_to_int(cdata.iqmp),
- private_exponent=self._bn_to_int(cdata.d),
- public_exponent=self._bn_to_int(cdata.e),
- modulus=self._bn_to_int(cdata.n),
+ def _bytes_to_bio(self, data):
+ """
+ Return a _MemoryBIO namedtuple of (BIO, char*).
+
+ The char* is the storage for the BIO and it must stay alive until the
+ BIO is finished with.
+ """
+ data_char_p = self._ffi.new("char[]", data)
+ bio = self._lib.BIO_new_mem_buf(
+ data_char_p, len(data)
+ )
+ assert bio != self._ffi.NULL
+
+ return _MemoryBIO(self._ffi.gc(bio, self._lib.BIO_free), data_char_p)
+
+ def _evp_pkey_to_private_key(self, evp_pkey):
+ """
+ Return the appropriate type of PrivateKey given an evp_pkey cdata
+ pointer.
+ """
+
+ type = evp_pkey.type
+
+ if type == self._lib.EVP_PKEY_RSA:
+ rsa_cdata = self._lib.EVP_PKEY_get1_RSA(evp_pkey)
+ assert rsa_cdata != self._ffi.NULL
+ rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
+ return _RSAPrivateKey(self, rsa_cdata)
+ elif type == self._lib.EVP_PKEY_DSA:
+ dsa_cdata = self._lib.EVP_PKEY_get1_DSA(evp_pkey)
+ assert dsa_cdata != self._ffi.NULL
+ dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
+ return _DSAPrivateKey(self, dsa_cdata)
+ else:
+ raise UnsupportedAlgorithm("Unsupported key type.")
+
+ def _pem_password_cb(self, password):
+ """
+ Generate a pem_password_cb function pointer that copied the password to
+ OpenSSL as required and returns the number of bytes copied.
+
+ typedef int pem_password_cb(char *buf, int size,
+ int rwflag, void *userdata);
+
+ Useful for decrypting PKCS8 files and so on.
+
+ Returns a tuple of (cdata function pointer, callback function).
+ """
+
+ def pem_password_cb(buf, size, writing, userdata):
+ pem_password_cb.called += 1
+
+ if not password or len(password) >= size:
+ return 0
+ else:
+ pw_buf = self._ffi.buffer(buf, size)
+ pw_buf[:len(password)] = password
+ return len(password)
+
+ pem_password_cb.called = 0
+
+ return (
+ self._ffi.callback("int (char *, int, int, void *)",
+ pem_password_cb),
+ pem_password_cb
)
def _rsa_cdata_from_private_key(self, private_key):
- # Does not GC the RSA cdata. You *must* make sure it's freed
- # correctly yourself!
ctx = self._lib.RSA_new()
assert ctx != self._ffi.NULL
+ ctx = self._ffi.gc(ctx, self._lib.RSA_free)
+
ctx.p = self._int_to_bn(private_key.p)
ctx.q = self._int_to_bn(private_key.q)
ctx.d = self._int_to_bn(private_key.d)
@@ -402,11 +524,10 @@ class Backend(object):
return ctx
def _rsa_cdata_from_public_key(self, public_key):
- # Does not GC the RSA cdata. You *must* make sure it's freed
- # correctly yourself!
-
ctx = self._lib.RSA_new()
assert ctx != self._ffi.NULL
+ ctx = self._ffi.gc(ctx, self._lib.RSA_free)
+
ctx.e = self._int_to_bn(public_key.e)
ctx.n = self._int_to_bn(public_key.n)
res = self._lib.RSA_blinding_on(ctx, self._ffi.NULL)
@@ -415,29 +536,64 @@ class Backend(object):
return ctx
def create_rsa_signature_ctx(self, private_key, padding, algorithm):
- return _RSASignatureContext(self, private_key, padding, algorithm)
+ warnings.warn(
+ "create_rsa_signature_ctx is deprecated and will be removed in a "
+ "future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
+ rsa_cdata = self._rsa_cdata_from_private_key(private_key)
+ key = _RSAPrivateKey(self, rsa_cdata)
+ return _RSASignatureContext(self, key, padding, algorithm)
def create_rsa_verification_ctx(self, public_key, signature, padding,
algorithm):
- return _RSAVerificationContext(self, public_key, signature, padding,
+ warnings.warn(
+ "create_rsa_verification_ctx is deprecated and will be removed in "
+ "a future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
+ rsa_cdata = self._rsa_cdata_from_public_key(public_key)
+ key = _RSAPublicKey(self, rsa_cdata)
+ return _RSAVerificationContext(self, key, signature, padding,
algorithm)
def mgf1_hash_supported(self, algorithm):
+ warnings.warn(
+ "mgf1_hash_supported is deprecated and will be removed in "
+ "a future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
+ return self._mgf1_hash_supported(algorithm)
+
+ def _mgf1_hash_supported(self, algorithm):
if self._lib.Cryptography_HAS_MGF1_MD:
return self.hash_supported(algorithm)
else:
return isinstance(algorithm, hashes.SHA1)
+ def rsa_padding_supported(self, padding):
+ if isinstance(padding, PKCS1v15):
+ return True
+ elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1):
+ return self._mgf1_hash_supported(padding._mgf._algorithm)
+ elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1):
+ return isinstance(padding._mgf._algorithm, hashes.SHA1)
+ else:
+ return False
+
def generate_dsa_parameters(self, key_size):
if key_size not in (1024, 2048, 3072):
raise ValueError(
- "Key size must be 1024 or 2048 or 3072 bits")
+ "Key size must be 1024 or 2048 or 3072 bits.")
if (self._lib.OPENSSL_VERSION_NUMBER < 0x1000000f and
key_size > 1024):
raise ValueError(
"Key size must be 1024 because OpenSSL < 1.0.0 doesn't "
- "support larger key sizes")
+ "support larger key sizes.")
ctx = self._lib.DSA_new()
assert ctx != self._ffi.NULL
@@ -450,43 +606,97 @@ class Backend(object):
assert res == 1
- return dsa.DSAParameters(
- modulus=self._bn_to_int(ctx.p),
- subgroup_order=self._bn_to_int(ctx.q),
- generator=self._bn_to_int(ctx.g)
- )
+ return _DSAParameters(self, ctx)
def generate_dsa_private_key(self, parameters):
ctx = self._lib.DSA_new()
assert ctx != self._ffi.NULL
ctx = self._ffi.gc(ctx, self._lib.DSA_free)
- ctx.p = self._int_to_bn(parameters.p)
- ctx.q = self._int_to_bn(parameters.q)
- ctx.g = self._int_to_bn(parameters.g)
+ if isinstance(parameters, dsa.DSAParameters):
+ ctx.p = self._int_to_bn(parameters.p)
+ ctx.q = self._int_to_bn(parameters.q)
+ ctx.g = self._int_to_bn(parameters.g)
+ else:
+ ctx.p = self._lib.BN_dup(parameters._dsa_cdata.p)
+ ctx.q = self._lib.BN_dup(parameters._dsa_cdata.q)
+ ctx.g = self._lib.BN_dup(parameters._dsa_cdata.g)
self._lib.DSA_generate_key(ctx)
- return dsa.DSAPrivateKey(
- modulus=self._bn_to_int(ctx.p),
- subgroup_order=self._bn_to_int(ctx.q),
- generator=self._bn_to_int(ctx.g),
- x=self._bn_to_int(ctx.priv_key),
- y=self._bn_to_int(ctx.pub_key)
- )
+ return _DSAPrivateKey(self, ctx)
+
+ def generate_dsa_private_key_and_parameters(self, key_size):
+ parameters = self.generate_dsa_parameters(key_size)
+ return self.generate_dsa_private_key(parameters)
def create_dsa_signature_ctx(self, private_key, algorithm):
- return _DSASignatureContext(self, private_key, algorithm)
+ warnings.warn(
+ "create_dsa_signature_ctx is deprecated and will be removed in "
+ "a future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
+ dsa_cdata = self._dsa_cdata_from_private_key(private_key)
+ key = _DSAPrivateKey(self, dsa_cdata)
+ return _DSASignatureContext(self, key, algorithm)
def create_dsa_verification_ctx(self, public_key, signature,
algorithm):
- return _DSAVerificationContext(self, public_key, signature,
- algorithm)
+ warnings.warn(
+ "create_dsa_verification_ctx is deprecated and will be removed in "
+ "a future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
+ dsa_cdata = self._dsa_cdata_from_public_key(public_key)
+ key = _DSAPublicKey(self, dsa_cdata)
+ return _DSAVerificationContext(self, key, signature, algorithm)
+
+ def load_dsa_private_numbers(self, numbers):
+ dsa._check_dsa_private_numbers(numbers)
+ parameter_numbers = numbers.public_numbers.parameter_numbers
+
+ dsa_cdata = self._lib.DSA_new()
+ assert dsa_cdata != self._ffi.NULL
+ dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
+
+ dsa_cdata.p = self._int_to_bn(parameter_numbers.p)
+ dsa_cdata.q = self._int_to_bn(parameter_numbers.q)
+ dsa_cdata.g = self._int_to_bn(parameter_numbers.g)
+ dsa_cdata.pub_key = self._int_to_bn(numbers.public_numbers.y)
+ dsa_cdata.priv_key = self._int_to_bn(numbers.x)
+
+ return _DSAPrivateKey(self, dsa_cdata)
+
+ def load_dsa_public_numbers(self, numbers):
+ dsa._check_dsa_parameters(numbers.parameter_numbers)
+ dsa_cdata = self._lib.DSA_new()
+ assert dsa_cdata != self._ffi.NULL
+ dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
+
+ dsa_cdata.p = self._int_to_bn(numbers.parameter_numbers.p)
+ dsa_cdata.q = self._int_to_bn(numbers.parameter_numbers.q)
+ dsa_cdata.g = self._int_to_bn(numbers.parameter_numbers.g)
+ dsa_cdata.pub_key = self._int_to_bn(numbers.y)
+
+ return _DSAPublicKey(self, dsa_cdata)
+
+ def load_dsa_parameter_numbers(self, numbers):
+ dsa._check_dsa_parameters(numbers)
+ dsa_cdata = self._lib.DSA_new()
+ assert dsa_cdata != self._ffi.NULL
+ dsa_cdata = self._ffi.gc(dsa_cdata, self._lib.DSA_free)
+
+ dsa_cdata.p = self._int_to_bn(numbers.p)
+ dsa_cdata.q = self._int_to_bn(numbers.q)
+ dsa_cdata.g = self._int_to_bn(numbers.g)
+
+ return _DSAParameters(self, dsa_cdata)
def _dsa_cdata_from_public_key(self, public_key):
- # Does not GC the DSA cdata. You *must* make sure it's freed
- # correctly yourself!
ctx = self._lib.DSA_new()
assert ctx != self._ffi.NULL
+ ctx = self._ffi.gc(ctx, self._lib.DSA_free)
parameters = public_key.parameters()
ctx.p = self._int_to_bn(parameters.p)
ctx.q = self._int_to_bn(parameters.q)
@@ -495,10 +705,9 @@ class Backend(object):
return ctx
def _dsa_cdata_from_private_key(self, private_key):
- # Does not GC the DSA cdata. You *must* make sure it's freed
- # correctly yourself!
ctx = self._lib.DSA_new()
assert ctx != self._ffi.NULL
+ ctx = self._ffi.gc(ctx, self._lib.DSA_free)
parameters = private_key.parameters()
ctx.p = self._int_to_bn(parameters.p)
ctx.q = self._int_to_bn(parameters.q)
@@ -520,131 +729,26 @@ class Backend(object):
return True
def decrypt_rsa(self, private_key, ciphertext, padding):
- key_size_bytes = int(math.ceil(private_key.key_size / 8.0))
- if key_size_bytes != len(ciphertext):
- raise ValueError("Ciphertext length must be equal to key size.")
-
- return self._enc_dec_rsa(private_key, ciphertext, padding)
+ warnings.warn(
+ "decrypt_rsa is deprecated and will be removed in a future "
+ "version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
+ rsa_cdata = self._rsa_cdata_from_private_key(private_key)
+ key = _RSAPrivateKey(self, rsa_cdata)
+ return key.decrypt(ciphertext, padding)
def encrypt_rsa(self, public_key, plaintext, padding):
- return self._enc_dec_rsa(public_key, plaintext, padding)
-
- def _enc_dec_rsa(self, key, data, padding):
- if isinstance(padding, PKCS1v15):
- padding_enum = self._lib.RSA_PKCS1_PADDING
- elif isinstance(padding, OAEP):
- padding_enum = self._lib.RSA_PKCS1_OAEP_PADDING
- if not isinstance(padding._mgf, MGF1):
- raise UnsupportedAlgorithm(
- "Only MGF1 is supported by this backend",
- _Reasons.UNSUPPORTED_MGF
- )
-
- if not isinstance(padding._mgf._algorithm, hashes.SHA1):
- raise UnsupportedAlgorithm(
- "This backend supports only SHA1 inside MGF1 when "
- "using OAEP",
- _Reasons.UNSUPPORTED_HASH
- )
-
- if padding._label is not None and padding._label != b"":
- raise ValueError("This backend does not support OAEP labels")
-
- if not isinstance(padding._algorithm, hashes.SHA1):
- raise UnsupportedAlgorithm(
- "This backend only supports SHA1 when using OAEP",
- _Reasons.UNSUPPORTED_HASH
- )
- else:
- raise UnsupportedAlgorithm(
- "{0} is not supported by this backend".format(
- padding.name
- ),
- _Reasons.UNSUPPORTED_PADDING
- )
-
- if self._lib.Cryptography_HAS_PKEY_CTX:
- return self._enc_dec_rsa_pkey_ctx(key, data, padding_enum)
- else:
- return self._enc_dec_rsa_098(key, data, padding_enum)
-
- def _enc_dec_rsa_pkey_ctx(self, key, data, padding_enum):
- if isinstance(key, rsa.RSAPublicKey):
- init = self._lib.EVP_PKEY_encrypt_init
- crypt = self._lib.Cryptography_EVP_PKEY_encrypt
- evp_pkey = self._rsa_public_key_to_evp_pkey(key)
- else:
- init = self._lib.EVP_PKEY_decrypt_init
- crypt = self._lib.Cryptography_EVP_PKEY_decrypt
- evp_pkey = self._rsa_private_key_to_evp_pkey(key)
-
- pkey_ctx = self._lib.EVP_PKEY_CTX_new(
- evp_pkey, self._ffi.NULL
+ warnings.warn(
+ "encrypt_rsa is deprecated and will be removed in a future "
+ "version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
)
- assert pkey_ctx != self._ffi.NULL
- pkey_ctx = self._ffi.gc(pkey_ctx, self._lib.EVP_PKEY_CTX_free)
- res = init(pkey_ctx)
- assert res == 1
- res = self._lib.EVP_PKEY_CTX_set_rsa_padding(
- pkey_ctx, padding_enum)
- assert res > 0
- buf_size = self._lib.EVP_PKEY_size(evp_pkey)
- assert buf_size > 0
- outlen = self._ffi.new("size_t *", buf_size)
- buf = self._ffi.new("char[]", buf_size)
- res = crypt(
- pkey_ctx,
- buf,
- outlen,
- data,
- len(data)
- )
- if res <= 0:
- self._handle_rsa_enc_dec_error(key)
-
- return self._ffi.buffer(buf)[:outlen[0]]
-
- def _enc_dec_rsa_098(self, key, data, padding_enum):
- if isinstance(key, rsa.RSAPublicKey):
- crypt = self._lib.RSA_public_encrypt
- rsa_cdata = self._rsa_cdata_from_public_key(key)
- else:
- crypt = self._lib.RSA_private_decrypt
- rsa_cdata = self._rsa_cdata_from_private_key(key)
-
- rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free)
- key_size = self._lib.RSA_size(rsa_cdata)
- assert key_size > 0
- buf = self._ffi.new("unsigned char[]", key_size)
- res = crypt(
- len(data),
- data,
- buf,
- rsa_cdata,
- padding_enum
- )
- if res < 0:
- self._handle_rsa_enc_dec_error(key)
-
- return self._ffi.buffer(buf)[:res]
-
- def _handle_rsa_enc_dec_error(self, key):
- errors = self._consume_errors()
- assert errors
- assert errors[0].lib == self._lib.ERR_LIB_RSA
- if isinstance(key, rsa.RSAPublicKey):
- assert (errors[0].reason ==
- self._lib.RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE)
- raise ValueError(
- "Data too long for key size. Encrypt less data or use a "
- "larger key size"
- )
- else:
- assert (
- errors[0].reason == self._lib.RSA_R_BLOCK_TYPE_IS_NOT_01 or
- errors[0].reason == self._lib.RSA_R_BLOCK_TYPE_IS_NOT_02
- )
- raise ValueError("Decryption failed")
+ rsa_cdata = self._rsa_cdata_from_public_key(public_key)
+ key = _RSAPublicKey(self, rsa_cdata)
+ return key.encrypt(plaintext, padding)
def cmac_algorithm_supported(self, algorithm):
return (
@@ -656,6 +760,294 @@ class Backend(object):
def create_cmac_ctx(self, algorithm):
return _CMACContext(self, algorithm)
+ def load_traditional_openssl_pem_private_key(self, data, password):
+ # OpenSSLs API for loading PKCS#8 certs can also load the traditional
+ # format so we just use that for both of them.
+
+ return self.load_pkcs8_pem_private_key(data, password)
+
+ def load_pkcs8_pem_private_key(self, data, password):
+ mem_bio = self._bytes_to_bio(data)
+
+ password_callback, password_func = self._pem_password_cb(password)
+
+ evp_pkey = self._lib.PEM_read_bio_PrivateKey(
+ mem_bio.bio,
+ self._ffi.NULL,
+ password_callback,
+ self._ffi.NULL
+ )
+
+ if evp_pkey == self._ffi.NULL:
+ errors = self._consume_errors()
+ if not errors:
+ raise ValueError("Could not unserialize key data.")
+
+ if (
+ errors[0][1:] == (
+ self._lib.ERR_LIB_PEM,
+ self._lib.PEM_F_PEM_DO_HEADER,
+ self._lib.PEM_R_BAD_PASSWORD_READ
+ )
+ ) or (
+ errors[0][1:] == (
+ self._lib.ERR_LIB_PEM,
+ self._lib.PEM_F_PEM_READ_BIO_PRIVATEKEY,
+ self._lib.PEM_R_BAD_PASSWORD_READ
+ )
+ ):
+ assert not password
+ raise TypeError(
+ "Password was not given but private key is encrypted.")
+
+ elif errors[0][1:] == (
+ self._lib.ERR_LIB_EVP,
+ self._lib.EVP_F_EVP_DECRYPTFINAL_EX,
+ self._lib.EVP_R_BAD_DECRYPT
+ ):
+ raise ValueError(
+ "Bad decrypt. Incorrect password?"
+ )
+
+ elif errors[0][1:] in (
+ (
+ self._lib.ERR_LIB_PEM,
+ self._lib.PEM_F_PEM_GET_EVP_CIPHER_INFO,
+ self._lib.PEM_R_UNSUPPORTED_ENCRYPTION
+ ),
+
+ (
+ self._lib.ERR_LIB_EVP,
+ self._lib.EVP_F_EVP_PBE_CIPHERINIT,
+ self._lib.EVP_R_UNKNOWN_PBE_ALGORITHM
+ )
+ ):
+ raise UnsupportedAlgorithm(
+ "PEM data is encrypted with an unsupported cipher",
+ _Reasons.UNSUPPORTED_CIPHER
+ )
+
+ elif any(
+ error[1:] == (
+ self._lib.ERR_LIB_EVP,
+ self._lib.EVP_F_EVP_PKCS82PKEY,
+ self._lib.EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM
+ )
+ for error in errors
+ ):
+ raise UnsupportedAlgorithm(
+ "Unsupported public key algorithm.",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM
+ )
+
+ else:
+ assert errors[0][1] in (
+ self._lib.ERR_LIB_EVP,
+ self._lib.ERR_LIB_PEM,
+ self._lib.ERR_LIB_ASN1,
+ )
+ raise ValueError("Could not unserialize key data.")
+
+ evp_pkey = self._ffi.gc(evp_pkey, self._lib.EVP_PKEY_free)
+
+ if password is not None and password_func.called == 0:
+ raise TypeError(
+ "Password was given but private key is not encrypted.")
+
+ assert (
+ (password is not None and password_func.called == 1) or
+ password is None
+ )
+
+ return self._evp_pkey_to_private_key(evp_pkey)
+
+ def elliptic_curve_supported(self, curve):
+ if self._lib.Cryptography_HAS_EC != 1:
+ return False
+
+ try:
+ curve_nid = self._elliptic_curve_to_nid(curve)
+ except UnsupportedAlgorithm:
+ curve_nid = self._lib.NID_undef
+
+ ctx = self._lib.EC_GROUP_new_by_curve_name(curve_nid)
+
+ if ctx == self._ffi.NULL:
+ errors = self._consume_errors()
+ assert (
+ curve_nid == self._lib.NID_undef or
+ errors[0][1:] == (
+ self._lib.ERR_LIB_EC,
+ self._lib.EC_F_EC_GROUP_NEW_BY_CURVE_NAME,
+ self._lib.EC_R_UNKNOWN_GROUP
+ )
+ )
+ return False
+ else:
+ assert curve_nid != self._lib.NID_undef
+ self._lib.EC_GROUP_free(ctx)
+ return True
+
+ def elliptic_curve_signature_algorithm_supported(
+ self, signature_algorithm, curve
+ ):
+ if self._lib.Cryptography_HAS_EC != 1:
+ return False
+
+ # We only support ECDSA right now.
+ if not isinstance(signature_algorithm, ec.ECDSA):
+ return False
+
+ # Before 0.9.8m OpenSSL can't cope with digests longer than the curve.
+ if (
+ self._lib.OPENSSL_VERSION_NUMBER < 0x009080df and
+ curve.key_size < signature_algorithm.algorithm.digest_size * 8
+ ):
+ return False
+
+ return self.elliptic_curve_supported(curve)
+
+ def generate_elliptic_curve_private_key(self, curve):
+ """
+ Generate a new private key on the named curve.
+ """
+
+ if self.elliptic_curve_supported(curve):
+ curve_nid = self._elliptic_curve_to_nid(curve)
+
+ ctx = self._lib.EC_KEY_new_by_curve_name(curve_nid)
+ assert ctx != self._ffi.NULL
+ ctx = self._ffi.gc(ctx, self._lib.EC_KEY_free)
+
+ res = self._lib.EC_KEY_generate_key(ctx)
+ assert res == 1
+
+ res = self._lib.EC_KEY_check_key(ctx)
+ assert res == 1
+
+ return _EllipticCurvePrivateKey(self, ctx, curve)
+ else:
+ raise UnsupportedAlgorithm(
+ "Backend object does not support {0}.".format(curve.name),
+ _Reasons.UNSUPPORTED_ELLIPTIC_CURVE
+ )
+
+ def elliptic_curve_private_key_from_numbers(self, numbers):
+ public = numbers.public_numbers
+
+ curve_nid = self._elliptic_curve_to_nid(public.curve)
+
+ ctx = self._lib.EC_KEY_new_by_curve_name(curve_nid)
+ assert ctx != self._ffi.NULL
+ ctx = self._ffi.gc(ctx, self._lib.EC_KEY_free)
+
+ ctx = self._ec_key_set_public_key_affine_coordinates(
+ ctx, public.x, public.y)
+
+ res = self._lib.EC_KEY_set_private_key(
+ ctx, self._int_to_bn(numbers.private_value))
+ assert res == 1
+
+ return _EllipticCurvePrivateKey(self, ctx,
+ numbers.public_numbers.curve)
+
+ def elliptic_curve_public_key_from_numbers(self, numbers):
+ curve_nid = self._elliptic_curve_to_nid(numbers.curve)
+
+ ctx = self._lib.EC_KEY_new_by_curve_name(curve_nid)
+ assert ctx != self._ffi.NULL
+ ctx = self._ffi.gc(ctx, self._lib.EC_KEY_free)
+
+ ctx = self._ec_key_set_public_key_affine_coordinates(
+ ctx, numbers.x, numbers.y)
+
+ return _EllipticCurvePublicKey(self, ctx, numbers.curve)
+
+ def _elliptic_curve_to_nid(self, curve):
+ """
+ Get the NID for a curve name.
+ """
+
+ curve_aliases = {
+ "secp192r1": "prime192v1",
+ "secp256r1": "prime256v1"
+ }
+
+ curve_name = curve_aliases.get(curve.name, curve.name)
+
+ curve_nid = self._lib.OBJ_sn2nid(curve_name.encode())
+ if curve_nid == self._lib.NID_undef:
+ raise UnsupportedAlgorithm(
+ "{0} is not a supported elliptic curve".format(curve.name),
+ _Reasons.UNSUPPORTED_ELLIPTIC_CURVE
+ )
+ return curve_nid
+
+ def _ec_key_set_public_key_affine_coordinates(self, ctx, x, y):
+ """
+ This is a port of EC_KEY_set_public_key_affine_coordinates that was
+ added in 1.0.1.
+
+ Sets the public key point in the EC_KEY context to the affine x and y
+ values.
+ """
+
+ assert ctx != self._ffi.NULL
+
+ bn_x = self._int_to_bn(x)
+ bn_y = self._int_to_bn(y)
+
+ nid_two_field = self._lib.OBJ_sn2nid(b"characteristic-two-field")
+ assert nid_two_field != self._lib.NID_undef
+
+ bn_ctx = self._lib.BN_CTX_new()
+ assert bn_ctx != self._ffi.NULL
+ bn_ctx = self._ffi.gc(bn_ctx, self._lib.BN_CTX_free)
+
+ group = self._lib.EC_KEY_get0_group(ctx)
+ assert group != self._ffi.NULL
+
+ point = self._lib.EC_POINT_new(group)
+ assert point != self._ffi.NULL
+ point = self._ffi.gc(point, self._lib.EC_POINT_free)
+
+ method = self._lib.EC_GROUP_method_of(group)
+ assert method != self._ffi.NULL
+
+ nid = self._lib.EC_METHOD_get_field_type(method)
+ assert nid != self._lib.NID_undef
+
+ check_x = self._lib.BN_CTX_get(bn_ctx)
+ check_y = self._lib.BN_CTX_get(bn_ctx)
+
+ if nid == nid_two_field and self._lib.Cryptography_HAS_EC2M:
+ set_func = self._lib.EC_POINT_set_affine_coordinates_GF2m
+ get_func = self._lib.EC_POINT_get_affine_coordinates_GF2m
+ else:
+ set_func = self._lib.EC_POINT_set_affine_coordinates_GFp
+ get_func = self._lib.EC_POINT_get_affine_coordinates_GFp
+
+ assert set_func and get_func
+
+ res = set_func(group, point, bn_x, bn_y, bn_ctx)
+ assert res == 1
+
+ res = get_func(group, point, check_x, check_y, bn_ctx)
+ assert res == 1
+
+ assert (
+ self._lib.BN_cmp(bn_x, check_x) == 0 and
+ self._lib.BN_cmp(bn_y, check_y) == 0
+ )
+
+ res = self._lib.EC_KEY_set_public_key(ctx, point)
+ assert res == 1
+
+ res = self._lib.EC_KEY_check_key(ctx)
+ assert res == 1
+
+ return ctx
+
class GetCipherByName(object):
def __init__(self, fmt):
@@ -666,822 +1058,4 @@ class GetCipherByName(object):
return backend._lib.EVP_get_cipherbyname(cipher_name.encode("ascii"))
-@utils.register_interface(interfaces.CipherContext)
-@utils.register_interface(interfaces.AEADCipherContext)
-@utils.register_interface(interfaces.AEADEncryptionContext)
-class _CipherContext(object):
- _ENCRYPT = 1
- _DECRYPT = 0
-
- def __init__(self, backend, cipher, mode, operation):
- self._backend = backend
- self._cipher = cipher
- self._mode = mode
- self._operation = operation
- self._tag = None
-
- if isinstance(self._cipher, interfaces.BlockCipherAlgorithm):
- self._block_size = self._cipher.block_size
- else:
- self._block_size = 1
-
- ctx = self._backend._lib.EVP_CIPHER_CTX_new()
- ctx = self._backend._ffi.gc(
- ctx, self._backend._lib.EVP_CIPHER_CTX_free
- )
-
- registry = self._backend._cipher_registry
- try:
- adapter = registry[type(cipher), type(mode)]
- except KeyError:
- raise UnsupportedAlgorithm(
- "cipher {0} in {1} mode is not supported "
- "by this backend".format(
- cipher.name, mode.name if mode else mode),
- _Reasons.UNSUPPORTED_CIPHER
- )
-
- evp_cipher = adapter(self._backend, cipher, mode)
- if evp_cipher == self._backend._ffi.NULL:
- raise UnsupportedAlgorithm(
- "cipher {0} in {1} mode is not supported "
- "by this backend".format(
- cipher.name, mode.name if mode else mode),
- _Reasons.UNSUPPORTED_CIPHER
- )
-
- if isinstance(mode, interfaces.ModeWithInitializationVector):
- iv_nonce = mode.initialization_vector
- elif isinstance(mode, interfaces.ModeWithNonce):
- iv_nonce = mode.nonce
- else:
- iv_nonce = self._backend._ffi.NULL
- # begin init with cipher and operation type
- res = self._backend._lib.EVP_CipherInit_ex(ctx, evp_cipher,
- self._backend._ffi.NULL,
- self._backend._ffi.NULL,
- self._backend._ffi.NULL,
- operation)
- assert res != 0
- # set the key length to handle variable key ciphers
- res = self._backend._lib.EVP_CIPHER_CTX_set_key_length(
- ctx, len(cipher.key)
- )
- assert res != 0
- if isinstance(mode, GCM):
- res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
- ctx, self._backend._lib.EVP_CTRL_GCM_SET_IVLEN,
- len(iv_nonce), self._backend._ffi.NULL
- )
- assert res != 0
- if operation == self._DECRYPT:
- res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
- ctx, self._backend._lib.EVP_CTRL_GCM_SET_TAG,
- len(mode.tag), mode.tag
- )
- assert res != 0
-
- # pass key/iv
- res = self._backend._lib.EVP_CipherInit_ex(
- ctx,
- self._backend._ffi.NULL,
- self._backend._ffi.NULL,
- cipher.key,
- iv_nonce,
- operation
- )
- assert res != 0
- # We purposely disable padding here as it's handled higher up in the
- # API.
- self._backend._lib.EVP_CIPHER_CTX_set_padding(ctx, 0)
- self._ctx = ctx
-
- def update(self, data):
- # OpenSSL 0.9.8e has an assertion in its EVP code that causes it
- # to SIGABRT if you call update with an empty byte string. This can be
- # removed when we drop support for 0.9.8e (CentOS/RHEL 5). This branch
- # should be taken only when length is zero and mode is not GCM because
- # AES GCM can return improper tag values if you don't call update
- # with empty plaintext when authenticating AAD for ...reasons.
- if len(data) == 0 and not isinstance(self._mode, GCM):
- return b""
-
- buf = self._backend._ffi.new("unsigned char[]",
- len(data) + self._block_size - 1)
- outlen = self._backend._ffi.new("int *")
- res = self._backend._lib.EVP_CipherUpdate(self._ctx, buf, outlen, data,
- len(data))
- assert res != 0
- return self._backend._ffi.buffer(buf)[:outlen[0]]
-
- def finalize(self):
- buf = self._backend._ffi.new("unsigned char[]", self._block_size)
- outlen = self._backend._ffi.new("int *")
- res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
- if res == 0:
- errors = self._backend._consume_errors()
-
- if not errors and isinstance(self._mode, GCM):
- raise InvalidTag
-
- assert errors
-
- if errors[0][1:] == (
- self._backend._lib.ERR_LIB_EVP,
- self._backend._lib.EVP_F_EVP_ENCRYPTFINAL_EX,
- self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
- ) or errors[0][1:] == (
- self._backend._lib.ERR_LIB_EVP,
- self._backend._lib.EVP_F_EVP_DECRYPTFINAL_EX,
- self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
- ):
- raise ValueError(
- "The length of the provided data is not a multiple of "
- "the block length."
- )
- else:
- raise self._backend._unknown_error(errors[0])
-
- if (isinstance(self._mode, GCM) and
- self._operation == self._ENCRYPT):
- block_byte_size = self._block_size // 8
- tag_buf = self._backend._ffi.new(
- "unsigned char[]", block_byte_size
- )
- res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
- self._ctx, self._backend._lib.EVP_CTRL_GCM_GET_TAG,
- block_byte_size, tag_buf
- )
- assert res != 0
- self._tag = self._backend._ffi.buffer(tag_buf)[:]
-
- res = self._backend._lib.EVP_CIPHER_CTX_cleanup(self._ctx)
- assert res == 1
- return self._backend._ffi.buffer(buf)[:outlen[0]]
-
- def authenticate_additional_data(self, data):
- outlen = self._backend._ffi.new("int *")
- res = self._backend._lib.EVP_CipherUpdate(
- self._ctx, self._backend._ffi.NULL, outlen, data, len(data)
- )
- assert res != 0
-
- @property
- def tag(self):
- return self._tag
-
-
-@utils.register_interface(interfaces.HashContext)
-class _HashContext(object):
- def __init__(self, backend, algorithm, ctx=None):
- self.algorithm = algorithm
-
- self._backend = backend
-
- if ctx is None:
- ctx = self._backend._lib.EVP_MD_CTX_create()
- ctx = self._backend._ffi.gc(ctx,
- self._backend._lib.EVP_MD_CTX_destroy)
- evp_md = self._backend._lib.EVP_get_digestbyname(
- algorithm.name.encode("ascii"))
- if evp_md == self._backend._ffi.NULL:
- raise UnsupportedAlgorithm(
- "{0} is not a supported hash on this backend".format(
- algorithm.name),
- _Reasons.UNSUPPORTED_HASH
- )
- res = self._backend._lib.EVP_DigestInit_ex(ctx, evp_md,
- self._backend._ffi.NULL)
- assert res != 0
-
- self._ctx = ctx
-
- def copy(self):
- copied_ctx = self._backend._lib.EVP_MD_CTX_create()
- copied_ctx = self._backend._ffi.gc(
- copied_ctx, self._backend._lib.EVP_MD_CTX_destroy
- )
- res = self._backend._lib.EVP_MD_CTX_copy_ex(copied_ctx, self._ctx)
- assert res != 0
- return _HashContext(self._backend, self.algorithm, ctx=copied_ctx)
-
- def update(self, data):
- res = self._backend._lib.EVP_DigestUpdate(self._ctx, data, len(data))
- assert res != 0
-
- def finalize(self):
- buf = self._backend._ffi.new("unsigned char[]",
- self._backend._lib.EVP_MAX_MD_SIZE)
- outlen = self._backend._ffi.new("unsigned int *")
- res = self._backend._lib.EVP_DigestFinal_ex(self._ctx, buf, outlen)
- assert res != 0
- assert outlen[0] == self.algorithm.digest_size
- res = self._backend._lib.EVP_MD_CTX_cleanup(self._ctx)
- assert res == 1
- return self._backend._ffi.buffer(buf)[:outlen[0]]
-
-
-@utils.register_interface(interfaces.HashContext)
-class _HMACContext(object):
- def __init__(self, backend, key, algorithm, ctx=None):
- self.algorithm = algorithm
- self._backend = backend
-
- if ctx is None:
- ctx = self._backend._ffi.new("HMAC_CTX *")
- self._backend._lib.HMAC_CTX_init(ctx)
- ctx = self._backend._ffi.gc(
- ctx, self._backend._lib.HMAC_CTX_cleanup
- )
- evp_md = self._backend._lib.EVP_get_digestbyname(
- algorithm.name.encode('ascii'))
- if evp_md == self._backend._ffi.NULL:
- raise UnsupportedAlgorithm(
- "{0} is not a supported hash on this backend".format(
- algorithm.name),
- _Reasons.UNSUPPORTED_HASH
- )
- res = self._backend._lib.Cryptography_HMAC_Init_ex(
- ctx, key, len(key), evp_md, self._backend._ffi.NULL
- )
- assert res != 0
-
- self._ctx = ctx
- self._key = key
-
- def copy(self):
- copied_ctx = self._backend._ffi.new("HMAC_CTX *")
- self._backend._lib.HMAC_CTX_init(copied_ctx)
- copied_ctx = self._backend._ffi.gc(
- copied_ctx, self._backend._lib.HMAC_CTX_cleanup
- )
- res = self._backend._lib.Cryptography_HMAC_CTX_copy(
- copied_ctx, self._ctx
- )
- assert res != 0
- return _HMACContext(
- self._backend, self._key, self.algorithm, ctx=copied_ctx
- )
-
- def update(self, data):
- res = self._backend._lib.Cryptography_HMAC_Update(
- self._ctx, data, len(data)
- )
- assert res != 0
-
- def finalize(self):
- buf = self._backend._ffi.new("unsigned char[]",
- self._backend._lib.EVP_MAX_MD_SIZE)
- outlen = self._backend._ffi.new("unsigned int *")
- res = self._backend._lib.Cryptography_HMAC_Final(
- self._ctx, buf, outlen
- )
- assert res != 0
- assert outlen[0] == self.algorithm.digest_size
- self._backend._lib.HMAC_CTX_cleanup(self._ctx)
- return self._backend._ffi.buffer(buf)[:outlen[0]]
-
-
-def _get_rsa_pss_salt_length(pss, key_size, digest_size):
- if pss._mgf._salt_length is not None:
- salt = pss._mgf._salt_length
- else:
- salt = pss._salt_length
-
- if salt is MGF1.MAX_LENGTH or salt is PSS.MAX_LENGTH:
- # bit length - 1 per RFC 3447
- emlen = int(math.ceil((key_size - 1) / 8.0))
- salt_length = emlen - digest_size - 2
- assert salt_length >= 0
- return salt_length
- else:
- return salt
-
-
-@utils.register_interface(interfaces.AsymmetricSignatureContext)
-class _RSASignatureContext(object):
- def __init__(self, backend, private_key, padding, algorithm):
- self._backend = backend
- self._private_key = private_key
-
- if not isinstance(padding, interfaces.AsymmetricPadding):
- raise TypeError(
- "Expected provider of interfaces.AsymmetricPadding")
-
- if isinstance(padding, PKCS1v15):
- if self._backend._lib.Cryptography_HAS_PKEY_CTX:
- self._finalize_method = self._finalize_pkey_ctx
- self._padding_enum = self._backend._lib.RSA_PKCS1_PADDING
- else:
- self._finalize_method = self._finalize_pkcs1
- elif isinstance(padding, PSS):
- if not isinstance(padding._mgf, MGF1):
- raise UnsupportedAlgorithm(
- "Only MGF1 is supported by this backend",
- _Reasons.UNSUPPORTED_MGF
- )
-
- # Size of key in bytes - 2 is the maximum
- # PSS signature length (salt length is checked later)
- key_size_bytes = int(math.ceil(private_key.key_size / 8.0))
- if key_size_bytes - algorithm.digest_size - 2 < 0:
- raise ValueError("Digest too large for key size. Use a larger "
- "key.")
-
- if not self._backend.mgf1_hash_supported(padding._mgf._algorithm):
- raise UnsupportedAlgorithm(
- "When OpenSSL is older than 1.0.1 then only SHA1 is "
- "supported with MGF1.",
- _Reasons.UNSUPPORTED_HASH
- )
-
- if self._backend._lib.Cryptography_HAS_PKEY_CTX:
- self._finalize_method = self._finalize_pkey_ctx
- self._padding_enum = self._backend._lib.RSA_PKCS1_PSS_PADDING
- else:
- self._finalize_method = self._finalize_pss
- else:
- raise UnsupportedAlgorithm(
- "{0} is not supported by this backend".format(padding.name),
- _Reasons.UNSUPPORTED_PADDING
- )
-
- self._padding = padding
- self._algorithm = algorithm
- self._hash_ctx = _HashContext(backend, self._algorithm)
-
- def update(self, data):
- if self._hash_ctx is None:
- raise AlreadyFinalized("Context has already been finalized")
-
- self._hash_ctx.update(data)
-
- def finalize(self):
- if self._hash_ctx is None:
- raise AlreadyFinalized("Context has already been finalized")
-
- evp_pkey = self._backend._rsa_private_key_to_evp_pkey(
- self._private_key)
-
- evp_md = self._backend._lib.EVP_get_digestbyname(
- self._algorithm.name.encode("ascii"))
- assert evp_md != self._backend._ffi.NULL
- pkey_size = self._backend._lib.EVP_PKEY_size(evp_pkey)
- assert pkey_size > 0
-
- return self._finalize_method(evp_pkey, pkey_size, evp_md)
-
- def _finalize_pkey_ctx(self, evp_pkey, pkey_size, evp_md):
- pkey_ctx = self._backend._lib.EVP_PKEY_CTX_new(
- evp_pkey, self._backend._ffi.NULL
- )
- assert pkey_ctx != self._backend._ffi.NULL
- pkey_ctx = self._backend._ffi.gc(pkey_ctx,
- self._backend._lib.EVP_PKEY_CTX_free)
- res = self._backend._lib.EVP_PKEY_sign_init(pkey_ctx)
- assert res == 1
- res = self._backend._lib.EVP_PKEY_CTX_set_signature_md(
- pkey_ctx, evp_md)
- assert res > 0
-
- res = self._backend._lib.EVP_PKEY_CTX_set_rsa_padding(
- pkey_ctx, self._padding_enum)
- assert res > 0
- if isinstance(self._padding, PSS):
- res = self._backend._lib.EVP_PKEY_CTX_set_rsa_pss_saltlen(
- pkey_ctx,
- _get_rsa_pss_salt_length(
- self._padding,
- self._private_key.key_size,
- self._hash_ctx.algorithm.digest_size
- )
- )
- assert res > 0
-
- if self._backend._lib.Cryptography_HAS_MGF1_MD:
- # MGF1 MD is configurable in OpenSSL 1.0.1+
- mgf1_md = self._backend._lib.EVP_get_digestbyname(
- self._padding._mgf._algorithm.name.encode("ascii"))
- assert mgf1_md != self._backend._ffi.NULL
- res = self._backend._lib.EVP_PKEY_CTX_set_rsa_mgf1_md(
- pkey_ctx, mgf1_md
- )
- assert res > 0
- data_to_sign = self._hash_ctx.finalize()
- self._hash_ctx = None
- buflen = self._backend._ffi.new("size_t *")
- res = self._backend._lib.EVP_PKEY_sign(
- pkey_ctx,
- self._backend._ffi.NULL,
- buflen,
- data_to_sign,
- len(data_to_sign)
- )
- assert res == 1
- buf = self._backend._ffi.new("unsigned char[]", buflen[0])
- res = self._backend._lib.EVP_PKEY_sign(
- pkey_ctx, buf, buflen, data_to_sign, len(data_to_sign))
- if res != 1:
- errors = self._backend._consume_errors()
- assert errors[0].lib == self._backend._lib.ERR_LIB_RSA
- reason = None
- if (errors[0].reason ==
- self._backend._lib.RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE):
- reason = ("Salt length too long for key size. Try using "
- "MAX_LENGTH instead.")
- elif (errors[0].reason ==
- self._backend._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY):
- reason = "Digest too large for key size. Use a larger key."
- assert reason is not None
- raise ValueError(reason)
-
- return self._backend._ffi.buffer(buf)[:]
-
- def _finalize_pkcs1(self, evp_pkey, pkey_size, evp_md):
- sig_buf = self._backend._ffi.new("char[]", pkey_size)
- sig_len = self._backend._ffi.new("unsigned int *")
- res = self._backend._lib.EVP_SignFinal(
- self._hash_ctx._ctx,
- sig_buf,
- sig_len,
- evp_pkey
- )
- self._hash_ctx.finalize()
- self._hash_ctx = None
- if res == 0:
- errors = self._backend._consume_errors()
- assert errors[0].lib == self._backend._lib.ERR_LIB_RSA
- assert (errors[0].reason ==
- self._backend._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY)
- raise ValueError("Digest too large for key size. Use a larger "
- "key.")
-
- return self._backend._ffi.buffer(sig_buf)[:sig_len[0]]
-
- def _finalize_pss(self, evp_pkey, pkey_size, evp_md):
- data_to_sign = self._hash_ctx.finalize()
- self._hash_ctx = None
- padded = self._backend._ffi.new("unsigned char[]", pkey_size)
- rsa_cdata = self._backend._lib.EVP_PKEY_get1_RSA(evp_pkey)
- assert rsa_cdata != self._backend._ffi.NULL
- rsa_cdata = self._backend._ffi.gc(rsa_cdata,
- self._backend._lib.RSA_free)
- res = self._backend._lib.RSA_padding_add_PKCS1_PSS(
- rsa_cdata,
- padded,
- data_to_sign,
- evp_md,
- _get_rsa_pss_salt_length(
- self._padding,
- self._private_key.key_size,
- len(data_to_sign)
- )
- )
- if res != 1:
- errors = self._backend._consume_errors()
- assert errors[0].lib == self._backend._lib.ERR_LIB_RSA
- assert (errors[0].reason ==
- self._backend._lib.RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE)
- raise ValueError("Salt length too long for key size. Try using "
- "MAX_LENGTH instead.")
-
- sig_buf = self._backend._ffi.new("char[]", pkey_size)
- sig_len = self._backend._lib.RSA_private_encrypt(
- pkey_size,
- padded,
- sig_buf,
- rsa_cdata,
- self._backend._lib.RSA_NO_PADDING
- )
- assert sig_len != -1
- return self._backend._ffi.buffer(sig_buf)[:sig_len]
-
-
-@utils.register_interface(interfaces.AsymmetricVerificationContext)
-class _RSAVerificationContext(object):
- def __init__(self, backend, public_key, signature, padding, algorithm):
- self._backend = backend
- self._public_key = public_key
- self._signature = signature
-
- if not isinstance(padding, interfaces.AsymmetricPadding):
- raise TypeError(
- "Expected provider of interfaces.AsymmetricPadding")
-
- if isinstance(padding, PKCS1v15):
- if self._backend._lib.Cryptography_HAS_PKEY_CTX:
- self._verify_method = self._verify_pkey_ctx
- self._padding_enum = self._backend._lib.RSA_PKCS1_PADDING
- else:
- self._verify_method = self._verify_pkcs1
- elif isinstance(padding, PSS):
- if not isinstance(padding._mgf, MGF1):
- raise UnsupportedAlgorithm(
- "Only MGF1 is supported by this backend",
- _Reasons.UNSUPPORTED_MGF
- )
-
- # Size of key in bytes - 2 is the maximum
- # PSS signature length (salt length is checked later)
- key_size_bytes = int(math.ceil(public_key.key_size / 8.0))
- if key_size_bytes - algorithm.digest_size - 2 < 0:
- raise ValueError(
- "Digest too large for key size. Check that you have the "
- "correct key and digest algorithm."
- )
-
- if not self._backend.mgf1_hash_supported(padding._mgf._algorithm):
- raise UnsupportedAlgorithm(
- "When OpenSSL is older than 1.0.1 then only SHA1 is "
- "supported with MGF1.",
- _Reasons.UNSUPPORTED_HASH
- )
-
- if self._backend._lib.Cryptography_HAS_PKEY_CTX:
- self._verify_method = self._verify_pkey_ctx
- self._padding_enum = self._backend._lib.RSA_PKCS1_PSS_PADDING
- else:
- self._verify_method = self._verify_pss
- else:
- raise UnsupportedAlgorithm(
- "{0} is not supported by this backend".format(padding.name),
- _Reasons.UNSUPPORTED_PADDING
- )
-
- self._padding = padding
- self._algorithm = algorithm
- self._hash_ctx = _HashContext(backend, self._algorithm)
-
- def update(self, data):
- if self._hash_ctx is None:
- raise AlreadyFinalized("Context has already been finalized")
-
- self._hash_ctx.update(data)
-
- def verify(self):
- if self._hash_ctx is None:
- raise AlreadyFinalized("Context has already been finalized")
-
- evp_pkey = self._backend._rsa_public_key_to_evp_pkey(
- self._public_key)
-
- evp_md = self._backend._lib.EVP_get_digestbyname(
- self._algorithm.name.encode("ascii"))
- assert evp_md != self._backend._ffi.NULL
-
- self._verify_method(evp_pkey, evp_md)
-
- def _verify_pkey_ctx(self, evp_pkey, evp_md):
- pkey_ctx = self._backend._lib.EVP_PKEY_CTX_new(
- evp_pkey, self._backend._ffi.NULL
- )
- assert pkey_ctx != self._backend._ffi.NULL
- pkey_ctx = self._backend._ffi.gc(pkey_ctx,
- self._backend._lib.EVP_PKEY_CTX_free)
- res = self._backend._lib.EVP_PKEY_verify_init(pkey_ctx)
- assert res == 1
- res = self._backend._lib.EVP_PKEY_CTX_set_signature_md(
- pkey_ctx, evp_md)
- assert res > 0
-
- res = self._backend._lib.EVP_PKEY_CTX_set_rsa_padding(
- pkey_ctx, self._padding_enum)
- assert res > 0
- if isinstance(self._padding, PSS):
- res = self._backend._lib.EVP_PKEY_CTX_set_rsa_pss_saltlen(
- pkey_ctx,
- _get_rsa_pss_salt_length(
- self._padding,
- self._public_key.key_size,
- self._hash_ctx.algorithm.digest_size
- )
- )
- assert res > 0
- if self._backend._lib.Cryptography_HAS_MGF1_MD:
- # MGF1 MD is configurable in OpenSSL 1.0.1+
- mgf1_md = self._backend._lib.EVP_get_digestbyname(
- self._padding._mgf._algorithm.name.encode("ascii"))
- assert mgf1_md != self._backend._ffi.NULL
- res = self._backend._lib.EVP_PKEY_CTX_set_rsa_mgf1_md(
- pkey_ctx, mgf1_md
- )
- assert res > 0
-
- data_to_verify = self._hash_ctx.finalize()
- self._hash_ctx = None
- res = self._backend._lib.EVP_PKEY_verify(
- pkey_ctx,
- self._signature,
- len(self._signature),
- data_to_verify,
- len(data_to_verify)
- )
- # The previous call can return negative numbers in the event of an
- # error. This is not a signature failure but we need to fail if it
- # occurs.
- assert res >= 0
- if res == 0:
- errors = self._backend._consume_errors()
- assert errors
- raise InvalidSignature
-
- def _verify_pkcs1(self, evp_pkey, evp_md):
- res = self._backend._lib.EVP_VerifyFinal(
- self._hash_ctx._ctx,
- self._signature,
- len(self._signature),
- evp_pkey
- )
- self._hash_ctx.finalize()
- self._hash_ctx = None
- # The previous call can return negative numbers in the event of an
- # error. This is not a signature failure but we need to fail if it
- # occurs.
- assert res >= 0
- if res == 0:
- errors = self._backend._consume_errors()
- assert errors
- raise InvalidSignature
-
- def _verify_pss(self, evp_pkey, evp_md):
- pkey_size = self._backend._lib.EVP_PKEY_size(evp_pkey)
- assert pkey_size > 0
- rsa_cdata = self._backend._lib.EVP_PKEY_get1_RSA(evp_pkey)
- assert rsa_cdata != self._backend._ffi.NULL
- rsa_cdata = self._backend._ffi.gc(rsa_cdata,
- self._backend._lib.RSA_free)
- buf = self._backend._ffi.new("unsigned char[]", pkey_size)
- res = self._backend._lib.RSA_public_decrypt(
- len(self._signature),
- self._signature,
- buf,
- rsa_cdata,
- self._backend._lib.RSA_NO_PADDING
- )
- if res != pkey_size:
- errors = self._backend._consume_errors()
- assert errors
- raise InvalidSignature
-
- data_to_verify = self._hash_ctx.finalize()
- self._hash_ctx = None
- res = self._backend._lib.RSA_verify_PKCS1_PSS(
- rsa_cdata,
- data_to_verify,
- evp_md,
- buf,
- _get_rsa_pss_salt_length(
- self._padding,
- self._public_key.key_size,
- len(data_to_verify)
- )
- )
- if res != 1:
- errors = self._backend._consume_errors()
- assert errors
- raise InvalidSignature
-
-
-@utils.register_interface(interfaces.AsymmetricVerificationContext)
-class _DSAVerificationContext(object):
- def __init__(self, backend, public_key, signature, algorithm):
- self._backend = backend
- self._public_key = public_key
- self._signature = signature
- self._algorithm = algorithm
-
- self._hash_ctx = _HashContext(backend, self._algorithm)
-
- def update(self, data):
- if self._hash_ctx is None:
- raise AlreadyFinalized("Context has already been finalized")
-
- self._hash_ctx.update(data)
-
- def verify(self):
- if self._hash_ctx is None:
- raise AlreadyFinalized("Context has already been finalized")
-
- self._dsa_cdata = self._backend._dsa_cdata_from_public_key(
- self._public_key)
- self._dsa_cdata = self._backend._ffi.gc(self._dsa_cdata,
- self._backend._lib.DSA_free)
-
- data_to_verify = self._hash_ctx.finalize()
- self._hash_ctx = None
-
- # The first parameter passed to DSA_verify is unused by OpenSSL but
- # must be an integer.
- res = self._backend._lib.DSA_verify(
- 0, data_to_verify, len(data_to_verify), self._signature,
- len(self._signature), self._dsa_cdata)
-
- if res != 1:
- errors = self._backend._consume_errors()
- assert errors
- if res == -1:
- assert errors[0].lib == self._backend._lib.ERR_LIB_ASN1
-
- raise InvalidSignature
-
-
-@utils.register_interface(interfaces.AsymmetricSignatureContext)
-class _DSASignatureContext(object):
- def __init__(self, backend, private_key, algorithm):
- self._backend = backend
- self._private_key = private_key
- self._algorithm = algorithm
- self._hash_ctx = _HashContext(backend, self._algorithm)
- self._dsa_cdata = self._backend._dsa_cdata_from_private_key(
- self._private_key)
- self._dsa_cdata = self._backend._ffi.gc(self._dsa_cdata,
- self._backend._lib.DSA_free)
-
- def update(self, data):
- if self._hash_ctx is None:
- raise AlreadyFinalized("Context has already been finalized")
-
- self._hash_ctx.update(data)
-
- def finalize(self):
- if self._hash_ctx is None:
- raise AlreadyFinalized("Context has already been finalized")
-
- data_to_sign = self._hash_ctx.finalize()
- self._hash_ctx = None
- sig_buf_len = self._backend._lib.DSA_size(self._dsa_cdata)
- sig_buf = self._backend._ffi.new("unsigned char[]", sig_buf_len)
- buflen = self._backend._ffi.new("unsigned int *")
-
- # The first parameter passed to DSA_sign is unused by OpenSSL but
- # must be an integer.
- res = self._backend._lib.DSA_sign(
- 0, data_to_sign, len(data_to_sign), sig_buf,
- buflen, self._dsa_cdata)
- assert res == 1
- assert buflen[0]
-
- return self._backend._ffi.buffer(sig_buf)[:buflen[0]]
-
-
-@utils.register_interface(interfaces.CMACContext)
-class _CMACContext(object):
- def __init__(self, backend, algorithm, ctx=None):
- if not backend.cmac_algorithm_supported(algorithm):
- raise UnsupportedAlgorithm("This backend does not support CMAC",
- _Reasons.UNSUPPORTED_CIPHER)
-
- self._backend = backend
- self._key = algorithm.key
- self._algorithm = algorithm
- self._output_length = algorithm.block_size // 8
-
- if ctx is None:
- registry = self._backend._cipher_registry
- adapter = registry[type(algorithm), CBC]
-
- evp_cipher = adapter(self._backend, algorithm, CBC)
-
- ctx = self._backend._lib.CMAC_CTX_new()
-
- assert ctx != self._backend._ffi.NULL
- ctx = self._backend._ffi.gc(ctx, self._backend._lib.CMAC_CTX_free)
-
- self._backend._lib.CMAC_Init(
- ctx, self._key, len(self._key),
- evp_cipher, self._backend._ffi.NULL
- )
-
- self._ctx = ctx
-
- def update(self, data):
- res = self._backend._lib.CMAC_Update(self._ctx, data, len(data))
- assert res == 1
-
- def finalize(self):
- buf = self._backend._ffi.new("unsigned char[]", self._output_length)
- length = self._backend._ffi.new("size_t *", self._output_length)
- res = self._backend._lib.CMAC_Final(
- self._ctx, buf, length
- )
- assert res == 1
-
- self._ctx = None
-
- return self._backend._ffi.buffer(buf)[:]
-
- def copy(self):
- copied_ctx = self._backend._lib.CMAC_CTX_new()
- copied_ctx = self._backend._ffi.gc(
- copied_ctx, self._backend._lib.CMAC_CTX_free
- )
- res = self._backend._lib.CMAC_CTX_copy(
- copied_ctx, self._ctx
- )
- assert res == 1
- return _CMACContext(
- self._backend, self._algorithm, ctx=copied_ctx
- )
-
-
backend = Backend()
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/ciphers.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/ciphers.py
new file mode 100644
index 0000000..c3a5499
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/ciphers.py
@@ -0,0 +1,219 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+from cryptography import utils
+from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm, _Reasons
+from cryptography.hazmat.primitives import interfaces
+from cryptography.hazmat.primitives.ciphers.modes import GCM
+
+
+@utils.register_interface(interfaces.CipherContext)
+@utils.register_interface(interfaces.AEADCipherContext)
+@utils.register_interface(interfaces.AEADEncryptionContext)
+class _CipherContext(object):
+ _ENCRYPT = 1
+ _DECRYPT = 0
+
+ def __init__(self, backend, cipher, mode, operation):
+ self._backend = backend
+ self._cipher = cipher
+ self._mode = mode
+ self._operation = operation
+ self._tag = None
+
+ if isinstance(self._cipher, interfaces.BlockCipherAlgorithm):
+ self._block_size = self._cipher.block_size
+ else:
+ self._block_size = 1
+
+ ctx = self._backend._lib.EVP_CIPHER_CTX_new()
+ ctx = self._backend._ffi.gc(
+ ctx, self._backend._lib.EVP_CIPHER_CTX_free
+ )
+
+ registry = self._backend._cipher_registry
+ try:
+ adapter = registry[type(cipher), type(mode)]
+ except KeyError:
+ raise UnsupportedAlgorithm(
+ "cipher {0} in {1} mode is not supported "
+ "by this backend.".format(
+ cipher.name, mode.name if mode else mode),
+ _Reasons.UNSUPPORTED_CIPHER
+ )
+
+ evp_cipher = adapter(self._backend, cipher, mode)
+ if evp_cipher == self._backend._ffi.NULL:
+ raise UnsupportedAlgorithm(
+ "cipher {0} in {1} mode is not supported "
+ "by this backend.".format(
+ cipher.name, mode.name if mode else mode),
+ _Reasons.UNSUPPORTED_CIPHER
+ )
+
+ if isinstance(mode, interfaces.ModeWithInitializationVector):
+ iv_nonce = mode.initialization_vector
+ elif isinstance(mode, interfaces.ModeWithNonce):
+ iv_nonce = mode.nonce
+ else:
+ iv_nonce = self._backend._ffi.NULL
+ # begin init with cipher and operation type
+ res = self._backend._lib.EVP_CipherInit_ex(ctx, evp_cipher,
+ self._backend._ffi.NULL,
+ self._backend._ffi.NULL,
+ self._backend._ffi.NULL,
+ operation)
+ assert res != 0
+ # set the key length to handle variable key ciphers
+ res = self._backend._lib.EVP_CIPHER_CTX_set_key_length(
+ ctx, len(cipher.key)
+ )
+ assert res != 0
+ if isinstance(mode, GCM):
+ res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
+ ctx, self._backend._lib.EVP_CTRL_GCM_SET_IVLEN,
+ len(iv_nonce), self._backend._ffi.NULL
+ )
+ assert res != 0
+ if operation == self._DECRYPT:
+ res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
+ ctx, self._backend._lib.EVP_CTRL_GCM_SET_TAG,
+ len(mode.tag), mode.tag
+ )
+ assert res != 0
+
+ # pass key/iv
+ res = self._backend._lib.EVP_CipherInit_ex(
+ ctx,
+ self._backend._ffi.NULL,
+ self._backend._ffi.NULL,
+ cipher.key,
+ iv_nonce,
+ operation
+ )
+ assert res != 0
+ # We purposely disable padding here as it's handled higher up in the
+ # API.
+ self._backend._lib.EVP_CIPHER_CTX_set_padding(ctx, 0)
+ self._ctx = ctx
+
+ def update(self, data):
+ # OpenSSL 0.9.8e has an assertion in its EVP code that causes it
+ # to SIGABRT if you call update with an empty byte string. This can be
+ # removed when we drop support for 0.9.8e (CentOS/RHEL 5). This branch
+ # should be taken only when length is zero and mode is not GCM because
+ # AES GCM can return improper tag values if you don't call update
+ # with empty plaintext when authenticating AAD for ...reasons.
+ if len(data) == 0 and not isinstance(self._mode, GCM):
+ return b""
+
+ buf = self._backend._ffi.new("unsigned char[]",
+ len(data) + self._block_size - 1)
+ outlen = self._backend._ffi.new("int *")
+ res = self._backend._lib.EVP_CipherUpdate(self._ctx, buf, outlen, data,
+ len(data))
+ assert res != 0
+ return self._backend._ffi.buffer(buf)[:outlen[0]]
+
+ def finalize(self):
+ buf = self._backend._ffi.new("unsigned char[]", self._block_size)
+ outlen = self._backend._ffi.new("int *")
+ res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
+ if res == 0:
+ errors = self._backend._consume_errors()
+
+ if not errors and isinstance(self._mode, GCM):
+ raise InvalidTag
+
+ assert errors
+
+ if errors[0][1:] == (
+ self._backend._lib.ERR_LIB_EVP,
+ self._backend._lib.EVP_F_EVP_ENCRYPTFINAL_EX,
+ self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
+ ) or errors[0][1:] == (
+ self._backend._lib.ERR_LIB_EVP,
+ self._backend._lib.EVP_F_EVP_DECRYPTFINAL_EX,
+ self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
+ ):
+ raise ValueError(
+ "The length of the provided data is not a multiple of "
+ "the block length."
+ )
+ else:
+ raise self._backend._unknown_error(errors[0])
+
+ if (isinstance(self._mode, GCM) and
+ self._operation == self._ENCRYPT):
+ block_byte_size = self._block_size // 8
+ tag_buf = self._backend._ffi.new(
+ "unsigned char[]", block_byte_size
+ )
+ res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
+ self._ctx, self._backend._lib.EVP_CTRL_GCM_GET_TAG,
+ block_byte_size, tag_buf
+ )
+ assert res != 0
+ self._tag = self._backend._ffi.buffer(tag_buf)[:]
+
+ res = self._backend._lib.EVP_CIPHER_CTX_cleanup(self._ctx)
+ assert res == 1
+ return self._backend._ffi.buffer(buf)[:outlen[0]]
+
+ def authenticate_additional_data(self, data):
+ outlen = self._backend._ffi.new("int *")
+ res = self._backend._lib.EVP_CipherUpdate(
+ self._ctx, self._backend._ffi.NULL, outlen, data, len(data)
+ )
+ assert res != 0
+
+ @property
+ def tag(self):
+ return self._tag
+
+
+@utils.register_interface(interfaces.CipherContext)
+class _AESCTRCipherContext(object):
+ """
+ This is needed to provide support for AES CTR mode in OpenSSL 0.9.8. It can
+ be removed when we drop 0.9.8 support (RHEL5 extended life ends 2020).
+ """
+ def __init__(self, backend, cipher, mode):
+ self._backend = backend
+
+ self._key = self._backend._ffi.new("AES_KEY *")
+ assert self._key != self._backend._ffi.NULL
+ res = self._backend._lib.AES_set_encrypt_key(
+ cipher.key, len(cipher.key) * 8, self._key
+ )
+ assert res == 0
+ self._ecount = self._backend._ffi.new("char[]", 16)
+ self._nonce = self._backend._ffi.new("char[16]", mode.nonce)
+ self._num = self._backend._ffi.new("unsigned int *", 0)
+
+ def update(self, data):
+ buf = self._backend._ffi.new("unsigned char[]", len(data))
+ self._backend._lib.AES_ctr128_encrypt(
+ data, buf, len(data), self._key, self._nonce,
+ self._ecount, self._num
+ )
+ return self._backend._ffi.buffer(buf)[:]
+
+ def finalize(self):
+ self._key = None
+ self._ecount = None
+ self._nonce = None
+ self._num = None
+ return b""
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/cmac.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/cmac.py
new file mode 100644
index 0000000..7acf439
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/cmac.py
@@ -0,0 +1,80 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+
+from cryptography import utils
+from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
+from cryptography.hazmat.primitives import interfaces
+from cryptography.hazmat.primitives.ciphers.modes import CBC
+
+
+@utils.register_interface(interfaces.CMACContext)
+class _CMACContext(object):
+ def __init__(self, backend, algorithm, ctx=None):
+ if not backend.cmac_algorithm_supported(algorithm):
+ raise UnsupportedAlgorithm("This backend does not support CMAC.",
+ _Reasons.UNSUPPORTED_CIPHER)
+
+ self._backend = backend
+ self._key = algorithm.key
+ self._algorithm = algorithm
+ self._output_length = algorithm.block_size // 8
+
+ if ctx is None:
+ registry = self._backend._cipher_registry
+ adapter = registry[type(algorithm), CBC]
+
+ evp_cipher = adapter(self._backend, algorithm, CBC)
+
+ ctx = self._backend._lib.CMAC_CTX_new()
+
+ assert ctx != self._backend._ffi.NULL
+ ctx = self._backend._ffi.gc(ctx, self._backend._lib.CMAC_CTX_free)
+
+ self._backend._lib.CMAC_Init(
+ ctx, self._key, len(self._key),
+ evp_cipher, self._backend._ffi.NULL
+ )
+
+ self._ctx = ctx
+
+ def update(self, data):
+ res = self._backend._lib.CMAC_Update(self._ctx, data, len(data))
+ assert res == 1
+
+ def finalize(self):
+ buf = self._backend._ffi.new("unsigned char[]", self._output_length)
+ length = self._backend._ffi.new("size_t *", self._output_length)
+ res = self._backend._lib.CMAC_Final(
+ self._ctx, buf, length
+ )
+ assert res == 1
+
+ self._ctx = None
+
+ return self._backend._ffi.buffer(buf)[:]
+
+ def copy(self):
+ copied_ctx = self._backend._lib.CMAC_CTX_new()
+ copied_ctx = self._backend._ffi.gc(
+ copied_ctx, self._backend._lib.CMAC_CTX_free
+ )
+ res = self._backend._lib.CMAC_CTX_copy(
+ copied_ctx, self._ctx
+ )
+ assert res == 1
+ return _CMACContext(
+ self._backend, self._algorithm, ctx=copied_ctx
+ )
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/dsa.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/dsa.py
new file mode 100644
index 0000000..5e7a26f
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/dsa.py
@@ -0,0 +1,190 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+from cryptography import utils
+from cryptography.exceptions import InvalidSignature
+from cryptography.hazmat.primitives import hashes, interfaces
+from cryptography.hazmat.primitives.asymmetric import dsa
+from cryptography.hazmat.primitives.interfaces import (
+ DSAParametersWithNumbers, DSAPrivateKeyWithNumbers, DSAPublicKeyWithNumbers
+)
+
+
+@utils.register_interface(interfaces.AsymmetricVerificationContext)
+class _DSAVerificationContext(object):
+ def __init__(self, backend, public_key, signature, algorithm):
+ self._backend = backend
+ self._public_key = public_key
+ self._signature = signature
+ self._algorithm = algorithm
+
+ self._hash_ctx = hashes.Hash(self._algorithm, self._backend)
+
+ def update(self, data):
+ self._hash_ctx.update(data)
+
+ def verify(self):
+ self._dsa_cdata = self._backend._ffi.gc(self._public_key._dsa_cdata,
+ self._backend._lib.DSA_free)
+
+ data_to_verify = self._hash_ctx.finalize()
+
+ # The first parameter passed to DSA_verify is unused by OpenSSL but
+ # must be an integer.
+ res = self._backend._lib.DSA_verify(
+ 0, data_to_verify, len(data_to_verify), self._signature,
+ len(self._signature), self._public_key._dsa_cdata)
+
+ if res != 1:
+ errors = self._backend._consume_errors()
+ assert errors
+ if res == -1:
+ assert errors[0].lib == self._backend._lib.ERR_LIB_ASN1
+
+ raise InvalidSignature
+
+
+@utils.register_interface(interfaces.AsymmetricSignatureContext)
+class _DSASignatureContext(object):
+ def __init__(self, backend, private_key, algorithm):
+ self._backend = backend
+ self._private_key = private_key
+ self._algorithm = algorithm
+ self._hash_ctx = hashes.Hash(self._algorithm, self._backend)
+
+ def update(self, data):
+ self._hash_ctx.update(data)
+
+ def finalize(self):
+ data_to_sign = self._hash_ctx.finalize()
+ sig_buf_len = self._backend._lib.DSA_size(self._private_key._dsa_cdata)
+ sig_buf = self._backend._ffi.new("unsigned char[]", sig_buf_len)
+ buflen = self._backend._ffi.new("unsigned int *")
+
+ # The first parameter passed to DSA_sign is unused by OpenSSL but
+ # must be an integer.
+ res = self._backend._lib.DSA_sign(
+ 0, data_to_sign, len(data_to_sign), sig_buf,
+ buflen, self._private_key._dsa_cdata)
+ assert res == 1
+ assert buflen[0]
+
+ return self._backend._ffi.buffer(sig_buf)[:buflen[0]]
+
+
+@utils.register_interface(DSAParametersWithNumbers)
+class _DSAParameters(object):
+ def __init__(self, backend, dsa_cdata):
+ self._backend = backend
+ self._dsa_cdata = dsa_cdata
+
+ def parameter_numbers(self):
+ return dsa.DSAParameterNumbers(
+ p=self._backend._bn_to_int(self._dsa_cdata.p),
+ q=self._backend._bn_to_int(self._dsa_cdata.q),
+ g=self._backend._bn_to_int(self._dsa_cdata.g)
+ )
+
+ def generate_private_key(self):
+ return self._backend.generate_dsa_private_key(self)
+
+
+@utils.register_interface(DSAPrivateKeyWithNumbers)
+class _DSAPrivateKey(object):
+ def __init__(self, backend, dsa_cdata):
+ self._backend = backend
+ self._dsa_cdata = dsa_cdata
+ self._key_size = self._backend._lib.BN_num_bits(self._dsa_cdata.p)
+
+ @property
+ def key_size(self):
+ return self._key_size
+
+ def signer(self, algorithm):
+ return _DSASignatureContext(self._backend, self, algorithm)
+
+ def private_numbers(self):
+ return dsa.DSAPrivateNumbers(
+ public_numbers=dsa.DSAPublicNumbers(
+ parameter_numbers=dsa.DSAParameterNumbers(
+ p=self._backend._bn_to_int(self._dsa_cdata.p),
+ q=self._backend._bn_to_int(self._dsa_cdata.q),
+ g=self._backend._bn_to_int(self._dsa_cdata.g)
+ ),
+ y=self._backend._bn_to_int(self._dsa_cdata.pub_key)
+ ),
+ x=self._backend._bn_to_int(self._dsa_cdata.priv_key)
+ )
+
+ def public_key(self):
+ dsa_cdata = self._backend._lib.DSA_new()
+ assert dsa_cdata != self._backend._ffi.NULL
+ dsa_cdata = self._backend._ffi.gc(
+ dsa_cdata, self._backend._lib.DSA_free
+ )
+ dsa_cdata.p = self._backend._lib.BN_dup(self._dsa_cdata.p)
+ dsa_cdata.q = self._backend._lib.BN_dup(self._dsa_cdata.q)
+ dsa_cdata.g = self._backend._lib.BN_dup(self._dsa_cdata.g)
+ dsa_cdata.pub_key = self._backend._lib.BN_dup(self._dsa_cdata.pub_key)
+ return _DSAPublicKey(self._backend, dsa_cdata)
+
+ def parameters(self):
+ dsa_cdata = self._backend._lib.DSA_new()
+ assert dsa_cdata != self._backend._ffi.NULL
+ dsa_cdata = self._backend._ffi.gc(
+ dsa_cdata, self._backend._lib.DSA_free
+ )
+ dsa_cdata.p = self._backend._lib.BN_dup(self._dsa_cdata.p)
+ dsa_cdata.q = self._backend._lib.BN_dup(self._dsa_cdata.q)
+ dsa_cdata.g = self._backend._lib.BN_dup(self._dsa_cdata.g)
+ return _DSAParameters(self._backend, dsa_cdata)
+
+
+@utils.register_interface(DSAPublicKeyWithNumbers)
+class _DSAPublicKey(object):
+ def __init__(self, backend, dsa_cdata):
+ self._backend = backend
+ self._dsa_cdata = dsa_cdata
+ self._key_size = self._backend._lib.BN_num_bits(self._dsa_cdata.p)
+
+ @property
+ def key_size(self):
+ return self._key_size
+
+ def verifier(self, signature, algorithm):
+ return _DSAVerificationContext(
+ self._backend, self, signature, algorithm
+ )
+
+ def public_numbers(self):
+ return dsa.DSAPublicNumbers(
+ parameter_numbers=dsa.DSAParameterNumbers(
+ p=self._backend._bn_to_int(self._dsa_cdata.p),
+ q=self._backend._bn_to_int(self._dsa_cdata.q),
+ g=self._backend._bn_to_int(self._dsa_cdata.g)
+ ),
+ y=self._backend._bn_to_int(self._dsa_cdata.pub_key)
+ )
+
+ def parameters(self):
+ dsa_cdata = self._backend._lib.DSA_new()
+ assert dsa_cdata != self._backend._ffi.NULL
+ dsa_cdata = self._backend._ffi.gc(
+ dsa_cdata, self._backend._lib.DSA_free
+ )
+ dsa_cdata.p = self._backend._lib.BN_dup(self._dsa_cdata.p)
+ dsa_cdata.q = self._backend._lib.BN_dup(self._dsa_cdata.q)
+ dsa_cdata.g = self._backend._lib.BN_dup(self._dsa_cdata.g)
+ return _DSAParameters(self._backend, dsa_cdata)
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/ec.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/ec.py
new file mode 100644
index 0000000..b7cd980
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/ec.py
@@ -0,0 +1,191 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+import six
+
+from cryptography import utils
+from cryptography.exceptions import (
+ InvalidSignature, UnsupportedAlgorithm, _Reasons
+)
+from cryptography.hazmat.primitives import hashes, interfaces
+from cryptography.hazmat.primitives.asymmetric import ec
+
+
+def _truncate_digest_for_ecdsa(ec_key_cdata, digest, backend):
+ _lib = backend._lib
+ _ffi = backend._ffi
+
+ digest_len = len(digest)
+
+ group = _lib.EC_KEY_get0_group(ec_key_cdata)
+
+ bn_ctx = _lib.BN_CTX_new()
+ assert bn_ctx != _ffi.NULL
+ bn_ctx = _ffi.gc(bn_ctx, _lib.BN_CTX_free)
+
+ order = _lib.BN_CTX_get(bn_ctx)
+ assert order != _ffi.NULL
+
+ res = _lib.EC_GROUP_get_order(group, order, bn_ctx)
+ assert res == 1
+
+ order_bits = _lib.BN_num_bits(order)
+
+ if 8 * digest_len > order_bits:
+ digest_len = (order_bits + 7) // 8
+ digest = digest[:digest_len]
+
+ if 8 * digest_len > order_bits:
+ rshift = 8 - (order_bits & 0x7)
+ assert rshift > 0 and rshift < 8
+
+ mask = 0xFF >> rshift << rshift
+
+ # Set the bottom rshift bits to 0
+ digest = digest[:-1] + six.int2byte(six.indexbytes(digest, -1) & mask)
+
+ return digest
+
+
+@utils.register_interface(interfaces.AsymmetricSignatureContext)
+class _ECDSASignatureContext(object):
+ def __init__(self, backend, private_key, algorithm):
+ self._backend = backend
+ self._private_key = private_key
+ self._digest = hashes.Hash(algorithm, backend)
+
+ def update(self, data):
+ self._digest.update(data)
+
+ def finalize(self):
+ ec_key = self._private_key._ec_key
+
+ digest = self._digest.finalize()
+
+ digest = _truncate_digest_for_ecdsa(ec_key, digest, self._backend)
+
+ max_size = self._backend._lib.ECDSA_size(ec_key)
+ assert max_size > 0
+
+ sigbuf = self._backend._ffi.new("char[]", max_size)
+ siglen_ptr = self._backend._ffi.new("unsigned int[]", 1)
+ res = self._backend._lib.ECDSA_sign(
+ 0,
+ digest,
+ len(digest),
+ sigbuf,
+ siglen_ptr,
+ ec_key
+ )
+ assert res == 1
+ return self._backend._ffi.buffer(sigbuf)[:siglen_ptr[0]]
+
+
+@utils.register_interface(interfaces.AsymmetricVerificationContext)
+class _ECDSAVerificationContext(object):
+ def __init__(self, backend, public_key, signature, algorithm):
+ self._backend = backend
+ self._public_key = public_key
+ self._signature = signature
+ self._digest = hashes.Hash(algorithm, backend)
+
+ def update(self, data):
+ self._digest.update(data)
+
+ def verify(self):
+ ec_key = self._public_key._ec_key
+
+ digest = self._digest.finalize()
+
+ digest = _truncate_digest_for_ecdsa(ec_key, digest, self._backend)
+
+ res = self._backend._lib.ECDSA_verify(
+ 0,
+ digest,
+ len(digest),
+ self._signature,
+ len(self._signature),
+ ec_key
+ )
+ if res != 1:
+ self._backend._consume_errors()
+ raise InvalidSignature
+ return True
+
+
+@utils.register_interface(interfaces.EllipticCurvePrivateKey)
+class _EllipticCurvePrivateKey(object):
+ def __init__(self, backend, ec_key_cdata, curve):
+ self._backend = backend
+ self._ec_key = ec_key_cdata
+ self._curve = curve
+
+ @property
+ def curve(self):
+ return self._curve
+
+ def signer(self, signature_algorithm):
+ if isinstance(signature_algorithm, ec.ECDSA):
+ return _ECDSASignatureContext(
+ self._backend, self, signature_algorithm.algorithm
+ )
+ else:
+ raise UnsupportedAlgorithm(
+ "Unsupported elliptic curve signature algorithm.",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
+
+ def public_key(self):
+ group = self._backend._lib.EC_KEY_get0_group(self._ec_key)
+ assert group != self._backend._ffi.NULL
+
+ curve_nid = self._backend._lib.EC_GROUP_get_curve_name(group)
+
+ public_ec_key = self._backend._lib.EC_KEY_new_by_curve_name(curve_nid)
+ assert public_ec_key != self._backend._ffi.NULL
+ public_ec_key = self._backend._ffi.gc(
+ public_ec_key, self._backend._lib.EC_KEY_free
+ )
+
+ point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key)
+ assert point != self._backend._ffi.NULL
+
+ res = self._backend._lib.EC_KEY_set_public_key(public_ec_key, point)
+ assert res == 1
+
+ return _EllipticCurvePublicKey(
+ self._backend, public_ec_key, self._curve
+ )
+
+
+@utils.register_interface(interfaces.EllipticCurvePublicKey)
+class _EllipticCurvePublicKey(object):
+ def __init__(self, backend, ec_key_cdata, curve):
+ self._backend = backend
+ self._ec_key = ec_key_cdata
+ self._curve = curve
+
+ @property
+ def curve(self):
+ return self._curve
+
+ def verifier(self, signature, signature_algorithm):
+ if isinstance(signature_algorithm, ec.ECDSA):
+ return _ECDSAVerificationContext(
+ self._backend, self, signature, signature_algorithm.algorithm
+ )
+ else:
+ raise UnsupportedAlgorithm(
+ "Unsupported elliptic curve signature algorithm.",
+ _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM)
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/hashes.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/hashes.py
new file mode 100644
index 0000000..da91eef
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/hashes.py
@@ -0,0 +1,69 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+
+from cryptography import utils
+from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
+from cryptography.hazmat.primitives import interfaces
+
+
+@utils.register_interface(interfaces.HashContext)
+class _HashContext(object):
+ def __init__(self, backend, algorithm, ctx=None):
+ self.algorithm = algorithm
+
+ self._backend = backend
+
+ if ctx is None:
+ ctx = self._backend._lib.EVP_MD_CTX_create()
+ ctx = self._backend._ffi.gc(ctx,
+ self._backend._lib.EVP_MD_CTX_destroy)
+ evp_md = self._backend._lib.EVP_get_digestbyname(
+ algorithm.name.encode("ascii"))
+ if evp_md == self._backend._ffi.NULL:
+ raise UnsupportedAlgorithm(
+ "{0} is not a supported hash on this backend.".format(
+ algorithm.name),
+ _Reasons.UNSUPPORTED_HASH
+ )
+ res = self._backend._lib.EVP_DigestInit_ex(ctx, evp_md,
+ self._backend._ffi.NULL)
+ assert res != 0
+
+ self._ctx = ctx
+
+ def copy(self):
+ copied_ctx = self._backend._lib.EVP_MD_CTX_create()
+ copied_ctx = self._backend._ffi.gc(
+ copied_ctx, self._backend._lib.EVP_MD_CTX_destroy
+ )
+ res = self._backend._lib.EVP_MD_CTX_copy_ex(copied_ctx, self._ctx)
+ assert res != 0
+ return _HashContext(self._backend, self.algorithm, ctx=copied_ctx)
+
+ def update(self, data):
+ res = self._backend._lib.EVP_DigestUpdate(self._ctx, data, len(data))
+ assert res != 0
+
+ def finalize(self):
+ buf = self._backend._ffi.new("unsigned char[]",
+ self._backend._lib.EVP_MAX_MD_SIZE)
+ outlen = self._backend._ffi.new("unsigned int *")
+ res = self._backend._lib.EVP_DigestFinal_ex(self._ctx, buf, outlen)
+ assert res != 0
+ assert outlen[0] == self.algorithm.digest_size
+ res = self._backend._lib.EVP_MD_CTX_cleanup(self._ctx)
+ assert res == 1
+ return self._backend._ffi.buffer(buf)[:outlen[0]]
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/hmac.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/hmac.py
new file mode 100644
index 0000000..3f1576f
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/hmac.py
@@ -0,0 +1,80 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+
+from cryptography import utils
+from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
+from cryptography.hazmat.primitives import interfaces
+
+
+@utils.register_interface(interfaces.HashContext)
+class _HMACContext(object):
+ def __init__(self, backend, key, algorithm, ctx=None):
+ self.algorithm = algorithm
+ self._backend = backend
+
+ if ctx is None:
+ ctx = self._backend._ffi.new("HMAC_CTX *")
+ self._backend._lib.HMAC_CTX_init(ctx)
+ ctx = self._backend._ffi.gc(
+ ctx, self._backend._lib.HMAC_CTX_cleanup
+ )
+ evp_md = self._backend._lib.EVP_get_digestbyname(
+ algorithm.name.encode('ascii'))
+ if evp_md == self._backend._ffi.NULL:
+ raise UnsupportedAlgorithm(
+ "{0} is not a supported hash on this backend.".format(
+ algorithm.name),
+ _Reasons.UNSUPPORTED_HASH
+ )
+ res = self._backend._lib.Cryptography_HMAC_Init_ex(
+ ctx, key, len(key), evp_md, self._backend._ffi.NULL
+ )
+ assert res != 0
+
+ self._ctx = ctx
+ self._key = key
+
+ def copy(self):
+ copied_ctx = self._backend._ffi.new("HMAC_CTX *")
+ self._backend._lib.HMAC_CTX_init(copied_ctx)
+ copied_ctx = self._backend._ffi.gc(
+ copied_ctx, self._backend._lib.HMAC_CTX_cleanup
+ )
+ res = self._backend._lib.Cryptography_HMAC_CTX_copy(
+ copied_ctx, self._ctx
+ )
+ assert res != 0
+ return _HMACContext(
+ self._backend, self._key, self.algorithm, ctx=copied_ctx
+ )
+
+ def update(self, data):
+ res = self._backend._lib.Cryptography_HMAC_Update(
+ self._ctx, data, len(data)
+ )
+ assert res != 0
+
+ def finalize(self):
+ buf = self._backend._ffi.new("unsigned char[]",
+ self._backend._lib.EVP_MAX_MD_SIZE)
+ outlen = self._backend._ffi.new("unsigned int *")
+ res = self._backend._lib.Cryptography_HMAC_Final(
+ self._ctx, buf, outlen
+ )
+ assert res != 0
+ assert outlen[0] == self.algorithm.digest_size
+ self._backend._lib.HMAC_CTX_cleanup(self._ctx)
+ return self._backend._ffi.buffer(buf)[:outlen[0]]
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/rsa.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/rsa.py
new file mode 100644
index 0000000..6f28c54
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/backends/openssl/rsa.py
@@ -0,0 +1,603 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+import math
+
+from cryptography import utils
+from cryptography.exceptions import (
+ AlreadyFinalized, InvalidSignature, UnsupportedAlgorithm, _Reasons
+)
+from cryptography.hazmat.primitives import hashes, interfaces
+from cryptography.hazmat.primitives.asymmetric import rsa
+from cryptography.hazmat.primitives.asymmetric.padding import (
+ MGF1, OAEP, PKCS1v15, PSS
+)
+from cryptography.hazmat.primitives.interfaces import (
+ RSAPrivateKeyWithNumbers, RSAPublicKeyWithNumbers
+)
+
+
+def _get_rsa_pss_salt_length(pss, key_size, digest_size):
+ if pss._mgf._salt_length is not None:
+ salt = pss._mgf._salt_length
+ else:
+ salt = pss._salt_length
+
+ if salt is MGF1.MAX_LENGTH or salt is PSS.MAX_LENGTH:
+ # bit length - 1 per RFC 3447
+ emlen = int(math.ceil((key_size - 1) / 8.0))
+ salt_length = emlen - digest_size - 2
+ assert salt_length >= 0
+ return salt_length
+ else:
+ return salt
+
+
+def _enc_dec_rsa(backend, key, data, padding):
+ if isinstance(padding, PKCS1v15):
+ padding_enum = backend._lib.RSA_PKCS1_PADDING
+ elif isinstance(padding, OAEP):
+ padding_enum = backend._lib.RSA_PKCS1_OAEP_PADDING
+ if not isinstance(padding._mgf, MGF1):
+ raise UnsupportedAlgorithm(
+ "Only MGF1 is supported by this backend.",
+ _Reasons.UNSUPPORTED_MGF
+ )
+
+ if not isinstance(padding._mgf._algorithm, hashes.SHA1):
+ raise UnsupportedAlgorithm(
+ "This backend supports only SHA1 inside MGF1 when "
+ "using OAEP.",
+ _Reasons.UNSUPPORTED_HASH
+ )
+
+ if padding._label is not None and padding._label != b"":
+ raise ValueError("This backend does not support OAEP labels.")
+
+ if not isinstance(padding._algorithm, hashes.SHA1):
+ raise UnsupportedAlgorithm(
+ "This backend only supports SHA1 when using OAEP.",
+ _Reasons.UNSUPPORTED_HASH
+ )
+ else:
+ raise UnsupportedAlgorithm(
+ "{0} is not supported by this backend.".format(
+ padding.name
+ ),
+ _Reasons.UNSUPPORTED_PADDING
+ )
+
+ if backend._lib.Cryptography_HAS_PKEY_CTX:
+ return _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum)
+ else:
+ return _enc_dec_rsa_098(backend, key, data, padding_enum)
+
+
+def _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum):
+ if isinstance(key, _RSAPublicKey):
+ init = backend._lib.EVP_PKEY_encrypt_init
+ crypt = backend._lib.Cryptography_EVP_PKEY_encrypt
+ else:
+ init = backend._lib.EVP_PKEY_decrypt_init
+ crypt = backend._lib.Cryptography_EVP_PKEY_decrypt
+
+ pkey_ctx = backend._lib.EVP_PKEY_CTX_new(
+ key._evp_pkey, backend._ffi.NULL
+ )
+ assert pkey_ctx != backend._ffi.NULL
+ pkey_ctx = backend._ffi.gc(pkey_ctx, backend._lib.EVP_PKEY_CTX_free)
+ res = init(pkey_ctx)
+ assert res == 1
+ res = backend._lib.EVP_PKEY_CTX_set_rsa_padding(
+ pkey_ctx, padding_enum)
+ assert res > 0
+ buf_size = backend._lib.EVP_PKEY_size(key._evp_pkey)
+ assert buf_size > 0
+ outlen = backend._ffi.new("size_t *", buf_size)
+ buf = backend._ffi.new("char[]", buf_size)
+ res = crypt(pkey_ctx, buf, outlen, data, len(data))
+ if res <= 0:
+ _handle_rsa_enc_dec_error(backend, key)
+
+ return backend._ffi.buffer(buf)[:outlen[0]]
+
+
+def _enc_dec_rsa_098(backend, key, data, padding_enum):
+ if isinstance(key, _RSAPublicKey):
+ crypt = backend._lib.RSA_public_encrypt
+ else:
+ crypt = backend._lib.RSA_private_decrypt
+
+ key_size = backend._lib.RSA_size(key._rsa_cdata)
+ assert key_size > 0
+ buf = backend._ffi.new("unsigned char[]", key_size)
+ res = crypt(len(data), data, buf, key._rsa_cdata, padding_enum)
+ if res < 0:
+ _handle_rsa_enc_dec_error(backend, key)
+
+ return backend._ffi.buffer(buf)[:res]
+
+
+def _handle_rsa_enc_dec_error(backend, key):
+ errors = backend._consume_errors()
+ assert errors
+ assert errors[0].lib == backend._lib.ERR_LIB_RSA
+ if isinstance(key, _RSAPublicKey):
+ assert (errors[0].reason ==
+ backend._lib.RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE)
+ raise ValueError(
+ "Data too long for key size. Encrypt less data or use a "
+ "larger key size."
+ )
+ else:
+ assert (
+ errors[0].reason == backend._lib.RSA_R_BLOCK_TYPE_IS_NOT_01 or
+ errors[0].reason == backend._lib.RSA_R_BLOCK_TYPE_IS_NOT_02
+ )
+ raise ValueError("Decryption failed.")
+
+
+@utils.register_interface(interfaces.AsymmetricSignatureContext)
+class _RSASignatureContext(object):
+ def __init__(self, backend, private_key, padding, algorithm):
+ self._backend = backend
+ self._private_key = private_key
+
+ if not isinstance(padding, interfaces.AsymmetricPadding):
+ raise TypeError(
+ "Expected provider of interfaces.AsymmetricPadding.")
+
+ self._pkey_size = self._backend._lib.EVP_PKEY_size(
+ self._private_key._evp_pkey
+ )
+
+ if isinstance(padding, PKCS1v15):
+ if self._backend._lib.Cryptography_HAS_PKEY_CTX:
+ self._finalize_method = self._finalize_pkey_ctx
+ self._padding_enum = self._backend._lib.RSA_PKCS1_PADDING
+ else:
+ self._finalize_method = self._finalize_pkcs1
+ elif isinstance(padding, PSS):
+ if not isinstance(padding._mgf, MGF1):
+ raise UnsupportedAlgorithm(
+ "Only MGF1 is supported by this backend.",
+ _Reasons.UNSUPPORTED_MGF
+ )
+
+ # Size of key in bytes - 2 is the maximum
+ # PSS signature length (salt length is checked later)
+ assert self._pkey_size > 0
+ if self._pkey_size - algorithm.digest_size - 2 < 0:
+ raise ValueError("Digest too large for key size. Use a larger "
+ "key.")
+
+ if not self._backend._mgf1_hash_supported(padding._mgf._algorithm):
+ raise UnsupportedAlgorithm(
+ "When OpenSSL is older than 1.0.1 then only SHA1 is "
+ "supported with MGF1.",
+ _Reasons.UNSUPPORTED_HASH
+ )
+
+ if self._backend._lib.Cryptography_HAS_PKEY_CTX:
+ self._finalize_method = self._finalize_pkey_ctx
+ self._padding_enum = self._backend._lib.RSA_PKCS1_PSS_PADDING
+ else:
+ self._finalize_method = self._finalize_pss
+ else:
+ raise UnsupportedAlgorithm(
+ "{0} is not supported by this backend.".format(padding.name),
+ _Reasons.UNSUPPORTED_PADDING
+ )
+
+ self._padding = padding
+ self._algorithm = algorithm
+ self._hash_ctx = hashes.Hash(self._algorithm, self._backend)
+
+ def update(self, data):
+ self._hash_ctx.update(data)
+
+ def finalize(self):
+ evp_md = self._backend._lib.EVP_get_digestbyname(
+ self._algorithm.name.encode("ascii"))
+ assert evp_md != self._backend._ffi.NULL
+
+ return self._finalize_method(evp_md)
+
+ def _finalize_pkey_ctx(self, evp_md):
+ pkey_ctx = self._backend._lib.EVP_PKEY_CTX_new(
+ self._private_key._evp_pkey, self._backend._ffi.NULL
+ )
+ assert pkey_ctx != self._backend._ffi.NULL
+ pkey_ctx = self._backend._ffi.gc(pkey_ctx,
+ self._backend._lib.EVP_PKEY_CTX_free)
+ res = self._backend._lib.EVP_PKEY_sign_init(pkey_ctx)
+ assert res == 1
+ res = self._backend._lib.EVP_PKEY_CTX_set_signature_md(
+ pkey_ctx, evp_md)
+ assert res > 0
+
+ res = self._backend._lib.EVP_PKEY_CTX_set_rsa_padding(
+ pkey_ctx, self._padding_enum)
+ assert res > 0
+ if isinstance(self._padding, PSS):
+ res = self._backend._lib.EVP_PKEY_CTX_set_rsa_pss_saltlen(
+ pkey_ctx,
+ _get_rsa_pss_salt_length(
+ self._padding,
+ self._private_key.key_size,
+ self._hash_ctx.algorithm.digest_size
+ )
+ )
+ assert res > 0
+
+ if self._backend._lib.Cryptography_HAS_MGF1_MD:
+ # MGF1 MD is configurable in OpenSSL 1.0.1+
+ mgf1_md = self._backend._lib.EVP_get_digestbyname(
+ self._padding._mgf._algorithm.name.encode("ascii"))
+ assert mgf1_md != self._backend._ffi.NULL
+ res = self._backend._lib.EVP_PKEY_CTX_set_rsa_mgf1_md(
+ pkey_ctx, mgf1_md
+ )
+ assert res > 0
+ data_to_sign = self._hash_ctx.finalize()
+ buflen = self._backend._ffi.new("size_t *")
+ res = self._backend._lib.EVP_PKEY_sign(
+ pkey_ctx,
+ self._backend._ffi.NULL,
+ buflen,
+ data_to_sign,
+ len(data_to_sign)
+ )
+ assert res == 1
+ buf = self._backend._ffi.new("unsigned char[]", buflen[0])
+ res = self._backend._lib.EVP_PKEY_sign(
+ pkey_ctx, buf, buflen, data_to_sign, len(data_to_sign))
+ if res != 1:
+ errors = self._backend._consume_errors()
+ assert errors[0].lib == self._backend._lib.ERR_LIB_RSA
+ reason = None
+ if (errors[0].reason ==
+ self._backend._lib.RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE):
+ reason = ("Salt length too long for key size. Try using "
+ "MAX_LENGTH instead.")
+ elif (errors[0].reason ==
+ self._backend._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY):
+ reason = "Digest too large for key size. Use a larger key."
+ assert reason is not None
+ raise ValueError(reason)
+
+ return self._backend._ffi.buffer(buf)[:]
+
+ def _finalize_pkcs1(self, evp_md):
+ if self._hash_ctx._ctx is None:
+ raise AlreadyFinalized("Context has already been finalized.")
+
+ sig_buf = self._backend._ffi.new("char[]", self._pkey_size)
+ sig_len = self._backend._ffi.new("unsigned int *")
+ res = self._backend._lib.EVP_SignFinal(
+ self._hash_ctx._ctx._ctx,
+ sig_buf,
+ sig_len,
+ self._private_key._evp_pkey
+ )
+ self._hash_ctx.finalize()
+ if res == 0:
+ errors = self._backend._consume_errors()
+ assert errors[0].lib == self._backend._lib.ERR_LIB_RSA
+ assert (errors[0].reason ==
+ self._backend._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY)
+ raise ValueError("Digest too large for key size. Use a larger "
+ "key.")
+
+ return self._backend._ffi.buffer(sig_buf)[:sig_len[0]]
+
+ def _finalize_pss(self, evp_md):
+ data_to_sign = self._hash_ctx.finalize()
+ padded = self._backend._ffi.new("unsigned char[]", self._pkey_size)
+ res = self._backend._lib.RSA_padding_add_PKCS1_PSS(
+ self._private_key._rsa_cdata,
+ padded,
+ data_to_sign,
+ evp_md,
+ _get_rsa_pss_salt_length(
+ self._padding,
+ self._private_key.key_size,
+ len(data_to_sign)
+ )
+ )
+ if res != 1:
+ errors = self._backend._consume_errors()
+ assert errors[0].lib == self._backend._lib.ERR_LIB_RSA
+ assert (errors[0].reason ==
+ self._backend._lib.RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE)
+ raise ValueError("Salt length too long for key size. Try using "
+ "MAX_LENGTH instead.")
+
+ sig_buf = self._backend._ffi.new("char[]", self._pkey_size)
+ sig_len = self._backend._lib.RSA_private_encrypt(
+ self._pkey_size,
+ padded,
+ sig_buf,
+ self._private_key._rsa_cdata,
+ self._backend._lib.RSA_NO_PADDING
+ )
+ assert sig_len != -1
+ return self._backend._ffi.buffer(sig_buf)[:sig_len]
+
+
+@utils.register_interface(interfaces.AsymmetricVerificationContext)
+class _RSAVerificationContext(object):
+ def __init__(self, backend, public_key, signature, padding, algorithm):
+ self._backend = backend
+ self._public_key = public_key
+ self._signature = signature
+
+ if not isinstance(padding, interfaces.AsymmetricPadding):
+ raise TypeError(
+ "Expected provider of interfaces.AsymmetricPadding.")
+
+ self._pkey_size = self._backend._lib.EVP_PKEY_size(
+ self._public_key._evp_pkey
+ )
+
+ if isinstance(padding, PKCS1v15):
+ if self._backend._lib.Cryptography_HAS_PKEY_CTX:
+ self._verify_method = self._verify_pkey_ctx
+ self._padding_enum = self._backend._lib.RSA_PKCS1_PADDING
+ else:
+ self._verify_method = self._verify_pkcs1
+ elif isinstance(padding, PSS):
+ if not isinstance(padding._mgf, MGF1):
+ raise UnsupportedAlgorithm(
+ "Only MGF1 is supported by this backend.",
+ _Reasons.UNSUPPORTED_MGF
+ )
+
+ # Size of key in bytes - 2 is the maximum
+ # PSS signature length (salt length is checked later)
+ assert self._pkey_size > 0
+ if self._pkey_size - algorithm.digest_size - 2 < 0:
+ raise ValueError(
+ "Digest too large for key size. Check that you have the "
+ "correct key and digest algorithm."
+ )
+
+ if not self._backend._mgf1_hash_supported(padding._mgf._algorithm):
+ raise UnsupportedAlgorithm(
+ "When OpenSSL is older than 1.0.1 then only SHA1 is "
+ "supported with MGF1.",
+ _Reasons.UNSUPPORTED_HASH
+ )
+
+ if self._backend._lib.Cryptography_HAS_PKEY_CTX:
+ self._verify_method = self._verify_pkey_ctx
+ self._padding_enum = self._backend._lib.RSA_PKCS1_PSS_PADDING
+ else:
+ self._verify_method = self._verify_pss
+ else:
+ raise UnsupportedAlgorithm(
+ "{0} is not supported by this backend.".format(padding.name),
+ _Reasons.UNSUPPORTED_PADDING
+ )
+
+ self._padding = padding
+ self._algorithm = algorithm
+ self._hash_ctx = hashes.Hash(self._algorithm, self._backend)
+
+ def update(self, data):
+ self._hash_ctx.update(data)
+
+ def verify(self):
+ evp_md = self._backend._lib.EVP_get_digestbyname(
+ self._algorithm.name.encode("ascii"))
+ assert evp_md != self._backend._ffi.NULL
+
+ self._verify_method(evp_md)
+
+ def _verify_pkey_ctx(self, evp_md):
+ pkey_ctx = self._backend._lib.EVP_PKEY_CTX_new(
+ self._public_key._evp_pkey, self._backend._ffi.NULL
+ )
+ assert pkey_ctx != self._backend._ffi.NULL
+ pkey_ctx = self._backend._ffi.gc(pkey_ctx,
+ self._backend._lib.EVP_PKEY_CTX_free)
+ res = self._backend._lib.EVP_PKEY_verify_init(pkey_ctx)
+ assert res == 1
+ res = self._backend._lib.EVP_PKEY_CTX_set_signature_md(
+ pkey_ctx, evp_md)
+ assert res > 0
+
+ res = self._backend._lib.EVP_PKEY_CTX_set_rsa_padding(
+ pkey_ctx, self._padding_enum)
+ assert res > 0
+ if isinstance(self._padding, PSS):
+ res = self._backend._lib.EVP_PKEY_CTX_set_rsa_pss_saltlen(
+ pkey_ctx,
+ _get_rsa_pss_salt_length(
+ self._padding,
+ self._public_key.key_size,
+ self._hash_ctx.algorithm.digest_size
+ )
+ )
+ assert res > 0
+ if self._backend._lib.Cryptography_HAS_MGF1_MD:
+ # MGF1 MD is configurable in OpenSSL 1.0.1+
+ mgf1_md = self._backend._lib.EVP_get_digestbyname(
+ self._padding._mgf._algorithm.name.encode("ascii"))
+ assert mgf1_md != self._backend._ffi.NULL
+ res = self._backend._lib.EVP_PKEY_CTX_set_rsa_mgf1_md(
+ pkey_ctx, mgf1_md
+ )
+ assert res > 0
+
+ data_to_verify = self._hash_ctx.finalize()
+ res = self._backend._lib.EVP_PKEY_verify(
+ pkey_ctx,
+ self._signature,
+ len(self._signature),
+ data_to_verify,
+ len(data_to_verify)
+ )
+ # The previous call can return negative numbers in the event of an
+ # error. This is not a signature failure but we need to fail if it
+ # occurs.
+ assert res >= 0
+ if res == 0:
+ errors = self._backend._consume_errors()
+ assert errors
+ raise InvalidSignature
+
+ def _verify_pkcs1(self, evp_md):
+ if self._hash_ctx._ctx is None:
+ raise AlreadyFinalized("Context has already been finalized.")
+
+ res = self._backend._lib.EVP_VerifyFinal(
+ self._hash_ctx._ctx._ctx,
+ self._signature,
+ len(self._signature),
+ self._public_key._evp_pkey
+ )
+ self._hash_ctx.finalize()
+ # The previous call can return negative numbers in the event of an
+ # error. This is not a signature failure but we need to fail if it
+ # occurs.
+ assert res >= 0
+ if res == 0:
+ errors = self._backend._consume_errors()
+ assert errors
+ raise InvalidSignature
+
+ def _verify_pss(self, evp_md):
+ buf = self._backend._ffi.new("unsigned char[]", self._pkey_size)
+ res = self._backend._lib.RSA_public_decrypt(
+ len(self._signature),
+ self._signature,
+ buf,
+ self._public_key._rsa_cdata,
+ self._backend._lib.RSA_NO_PADDING
+ )
+ if res != self._pkey_size:
+ errors = self._backend._consume_errors()
+ assert errors
+ raise InvalidSignature
+
+ data_to_verify = self._hash_ctx.finalize()
+ res = self._backend._lib.RSA_verify_PKCS1_PSS(
+ self._public_key._rsa_cdata,
+ data_to_verify,
+ evp_md,
+ buf,
+ _get_rsa_pss_salt_length(
+ self._padding,
+ self._public_key.key_size,
+ len(data_to_verify)
+ )
+ )
+ if res != 1:
+ errors = self._backend._consume_errors()
+ assert errors
+ raise InvalidSignature
+
+
+@utils.register_interface(RSAPrivateKeyWithNumbers)
+class _RSAPrivateKey(object):
+ def __init__(self, backend, rsa_cdata):
+ self._backend = backend
+ self._rsa_cdata = rsa_cdata
+
+ evp_pkey = self._backend._lib.EVP_PKEY_new()
+ assert evp_pkey != self._backend._ffi.NULL
+ evp_pkey = self._backend._ffi.gc(
+ evp_pkey, self._backend._lib.EVP_PKEY_free
+ )
+ res = self._backend._lib.EVP_PKEY_set1_RSA(evp_pkey, rsa_cdata)
+ assert res == 1
+ self._evp_pkey = evp_pkey
+
+ self._key_size = self._backend._lib.BN_num_bits(self._rsa_cdata.n)
+
+ @property
+ def key_size(self):
+ return self._key_size
+
+ def signer(self, padding, algorithm):
+ return _RSASignatureContext(self._backend, self, padding, algorithm)
+
+ def decrypt(self, ciphertext, padding):
+ key_size_bytes = int(math.ceil(self.key_size / 8.0))
+ if key_size_bytes != len(ciphertext):
+ raise ValueError("Ciphertext length must be equal to key size.")
+
+ return _enc_dec_rsa(self._backend, self, ciphertext, padding)
+
+ def public_key(self):
+ ctx = self._backend._lib.RSA_new()
+ assert ctx != self._backend._ffi.NULL
+ ctx = self._backend._ffi.gc(ctx, self._backend._lib.RSA_free)
+ ctx.e = self._backend._lib.BN_dup(self._rsa_cdata.e)
+ ctx.n = self._backend._lib.BN_dup(self._rsa_cdata.n)
+ res = self._backend._lib.RSA_blinding_on(ctx, self._backend._ffi.NULL)
+ assert res == 1
+ return _RSAPublicKey(self._backend, ctx)
+
+ def private_numbers(self):
+ return rsa.RSAPrivateNumbers(
+ p=self._backend._bn_to_int(self._rsa_cdata.p),
+ q=self._backend._bn_to_int(self._rsa_cdata.q),
+ d=self._backend._bn_to_int(self._rsa_cdata.d),
+ dmp1=self._backend._bn_to_int(self._rsa_cdata.dmp1),
+ dmq1=self._backend._bn_to_int(self._rsa_cdata.dmq1),
+ iqmp=self._backend._bn_to_int(self._rsa_cdata.iqmp),
+ public_numbers=rsa.RSAPublicNumbers(
+ e=self._backend._bn_to_int(self._rsa_cdata.e),
+ n=self._backend._bn_to_int(self._rsa_cdata.n),
+ )
+ )
+
+
+@utils.register_interface(RSAPublicKeyWithNumbers)
+class _RSAPublicKey(object):
+ def __init__(self, backend, rsa_cdata):
+ self._backend = backend
+ self._rsa_cdata = rsa_cdata
+
+ evp_pkey = self._backend._lib.EVP_PKEY_new()
+ assert evp_pkey != self._backend._ffi.NULL
+ evp_pkey = self._backend._ffi.gc(
+ evp_pkey, self._backend._lib.EVP_PKEY_free
+ )
+ res = self._backend._lib.EVP_PKEY_set1_RSA(evp_pkey, rsa_cdata)
+ assert res == 1
+ self._evp_pkey = evp_pkey
+
+ self._key_size = self._backend._lib.BN_num_bits(self._rsa_cdata.n)
+
+ @property
+ def key_size(self):
+ return self._key_size
+
+ def verifier(self, signature, padding, algorithm):
+ return _RSAVerificationContext(
+ self._backend, self, signature, padding, algorithm
+ )
+
+ def encrypt(self, plaintext, padding):
+ return _enc_dec_rsa(self._backend, self, plaintext, padding)
+
+ def public_numbers(self):
+ return rsa.RSAPublicNumbers(
+ e=self._backend._bn_to_int(self._rsa_cdata.e),
+ n=self._backend._bn_to_int(self._rsa_cdata.n),
+ )
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/binding.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/binding.py
index 144bb09..ee7378a 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/binding.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/binding.py
@@ -25,10 +25,16 @@ class Binding(object):
"""
_module_prefix = "cryptography.hazmat.bindings.commoncrypto."
_modules = [
+ "cf",
"common_digest",
"common_hmac",
"common_key_derivation",
"common_cryptor",
+ "secimport",
+ "secitem",
+ "seckey",
+ "seckeychain",
+ "sectransform",
]
ffi = None
@@ -45,6 +51,7 @@ class Binding(object):
cls.ffi, cls.lib = build_ffi(
module_prefix=cls._module_prefix,
modules=cls._modules,
+ extra_link_args=["-framework", "Security"]
)
@classmethod
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/cf.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/cf.py
new file mode 100644
index 0000000..671963a
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/cf.py
@@ -0,0 +1,114 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+INCLUDES = """
+#include
+"""
+
+TYPES = """
+typedef bool Boolean;
+typedef signed long OSStatus;
+typedef unsigned char UInt8;
+typedef uint32_t UInt32;
+
+typedef const void * CFAllocatorRef;
+const CFAllocatorRef kCFAllocatorDefault;
+typedef const void * CFDataRef;
+typedef signed long long CFIndex;
+typedef ... *CFStringRef;
+typedef ... *CFArrayRef;
+typedef ... *CFBooleanRef;
+typedef ... *CFErrorRef;
+typedef ... *CFNumberRef;
+typedef ... *CFTypeRef;
+typedef ... *CFDictionaryRef;
+typedef ... *CFMutableDictionaryRef;
+typedef struct {
+ ...;
+} CFDictionaryKeyCallBacks;
+typedef struct {
+ ...;
+} CFDictionaryValueCallBacks;
+typedef struct {
+ ...;
+} CFRange;
+
+typedef UInt32 CFStringEncoding;
+enum {
+ kCFStringEncodingASCII = 0x0600
+};
+
+enum {
+ kCFNumberSInt8Type = 1,
+ kCFNumberSInt16Type = 2,
+ kCFNumberSInt32Type = 3,
+ kCFNumberSInt64Type = 4,
+ kCFNumberFloat32Type = 5,
+ kCFNumberFloat64Type = 6,
+ kCFNumberCharType = 7,
+ kCFNumberShortType = 8,
+ kCFNumberIntType = 9,
+ kCFNumberLongType = 10,
+ kCFNumberLongLongType = 11,
+ kCFNumberFloatType = 12,
+ kCFNumberDoubleType = 13,
+ kCFNumberCFIndexType = 14,
+ kCFNumberNSIntegerType = 15,
+ kCFNumberCGFloatType = 16,
+ kCFNumberMaxType = 16
+};
+typedef int CFNumberType;
+
+const CFDictionaryKeyCallBacks kCFTypeDictionaryKeyCallBacks;
+const CFDictionaryValueCallBacks kCFTypeDictionaryValueCallBacks;
+
+const CFBooleanRef kCFBooleanTrue;
+const CFBooleanRef kCFBooleanFalse;
+"""
+
+FUNCTIONS = """
+CFDataRef CFDataCreate(CFAllocatorRef, const UInt8 *, CFIndex);
+CFStringRef CFStringCreateWithCString(CFAllocatorRef, const char *,
+ CFStringEncoding);
+CFDictionaryRef CFDictionaryCreate(CFAllocatorRef, const void **,
+ const void **, CFIndex,
+ const CFDictionaryKeyCallBacks *,
+ const CFDictionaryValueCallBacks *);
+CFMutableDictionaryRef CFDictionaryCreateMutable(
+ CFAllocatorRef,
+ CFIndex,
+ const CFDictionaryKeyCallBacks *,
+ const CFDictionaryValueCallBacks *
+);
+void CFDictionarySetValue(CFMutableDictionaryRef, const void *, const void *);
+CFIndex CFArrayGetCount(CFArrayRef);
+const void *CFArrayGetValueAtIndex(CFArrayRef, CFIndex);
+CFIndex CFDataGetLength(CFDataRef);
+void CFDataGetBytes(CFDataRef, CFRange, UInt8 *);
+CFRange CFRangeMake(CFIndex, CFIndex);
+void CFShow(CFTypeRef);
+Boolean CFBooleanGetValue(CFBooleanRef);
+CFNumberRef CFNumberCreate(CFAllocatorRef, CFNumberType, const void *);
+void CFRelease(CFTypeRef);
+CFTypeRef CFRetain(CFTypeRef);
+"""
+
+MACROS = """
+"""
+
+CUSTOMIZATIONS = """
+"""
+
+CONDITIONAL_NAMES = {}
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/common_cryptor.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/common_cryptor.py
index 9bd03a7..713bc56 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/common_cryptor.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/common_cryptor.py
@@ -101,7 +101,7 @@ MACROS = """
"""
CUSTOMIZATIONS = """
-// Not defined in the public header
+/* Not defined in the public header */
enum {
kCCModeGCM = 11
};
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/secimport.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/secimport.py
new file mode 100644
index 0000000..add62c7
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/secimport.py
@@ -0,0 +1,95 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+INCLUDES = """
+#include
+"""
+
+TYPES = """
+typedef ... *SecAccessRef;
+
+CFStringRef kSecImportExportPassphrase;
+CFStringRef kSecImportExportKeychain;
+CFStringRef kSecImportExportAccess;
+
+typedef uint32_t SecExternalItemType;
+enum {
+ kSecItemTypeUnknown,
+ kSecItemTypePrivateKey,
+ kSecItemTypePublicKey,
+ kSecItemTypeSessionKey,
+ kSecItemTypeCertificate,
+ kSecItemTypeAggregate
+};
+
+
+typedef uint32_t SecExternalFormat;
+enum {
+ kSecFormatUnknown = 0,
+ kSecFormatOpenSSL,
+ kSecFormatSSH,
+ kSecFormatBSAFE,
+ kSecFormatRawKey,
+ kSecFormatWrappedPKCS8,
+ kSecFormatWrappedOpenSSL,
+ kSecFormatWrappedSSH,
+ kSecFormatWrappedLSH,
+ kSecFormatX509Cert,
+ kSecFormatPEMSequence,
+ kSecFormatPKCS7,
+ kSecFormatPKCS12,
+ kSecFormatNetscapeCertSequence,
+ kSecFormatSSHv2
+};
+
+typedef uint32_t SecItemImportExportFlags;
+enum {
+ kSecKeyImportOnlyOne = 0x00000001,
+ kSecKeySecurePassphrase = 0x00000002,
+ kSecKeyNoAccessControl = 0x00000004
+};
+typedef uint32_t SecKeyImportExportFlags;
+
+typedef struct {
+ /* for import and export */
+ uint32_t version;
+ SecKeyImportExportFlags flags;
+ CFTypeRef passphrase;
+ CFStringRef alertTitle;
+ CFStringRef alertPrompt;
+
+ /* for import only */
+ SecAccessRef accessRef;
+ CFArrayRef keyUsage;
+
+ CFArrayRef keyAttributes;
+} SecItemImportExportKeyParameters;
+"""
+
+FUNCTIONS = """
+OSStatus SecItemImport(CFDataRef, CFStringRef, SecExternalFormat *,
+ SecExternalItemType *, SecItemImportExportFlags,
+ const SecItemImportExportKeyParameters *,
+ SecKeychainRef, CFArrayRef *);
+OSStatus SecPKCS12Import(CFDataRef, CFDictionaryRef, CFArrayRef *);
+"""
+
+MACROS = """
+"""
+
+CUSTOMIZATIONS = """
+"""
+
+CONDITIONAL_NAMES = {}
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/secitem.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/secitem.py
new file mode 100644
index 0000000..ac3dad3
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/secitem.py
@@ -0,0 +1,38 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+INCLUDES = """
+#include
+"""
+
+TYPES = """
+const CFTypeRef kSecAttrKeyType;
+const CFTypeRef kSecAttrKeySizeInBits;
+const CFTypeRef kSecAttrIsPermanent;
+const CFTypeRef kSecAttrKeyTypeRSA;
+const CFTypeRef kSecAttrKeyTypeDSA;
+const CFTypeRef kSecUseKeychain;
+"""
+
+FUNCTIONS = """
+"""
+
+MACROS = """
+"""
+
+CUSTOMIZATIONS = """
+"""
+
+CONDITIONAL_NAMES = {}
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/seckey.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/seckey.py
new file mode 100644
index 0000000..5e4b6da
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/seckey.py
@@ -0,0 +1,35 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+INCLUDES = """
+#include
+"""
+
+TYPES = """
+typedef ... *SecKeyRef;
+"""
+
+FUNCTIONS = """
+OSStatus SecKeyGeneratePair(CFDictionaryRef, SecKeyRef *, SecKeyRef *);
+size_t SecKeyGetBlockSize(SecKeyRef);
+"""
+
+MACROS = """
+"""
+
+CUSTOMIZATIONS = """
+"""
+
+CONDITIONAL_NAMES = {}
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/seckeychain.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/seckeychain.py
new file mode 100644
index 0000000..c045c34
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/seckeychain.py
@@ -0,0 +1,36 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+INCLUDES = """
+#include
+"""
+
+TYPES = """
+typedef ... *SecKeychainRef;
+"""
+
+FUNCTIONS = """
+OSStatus SecKeychainCreate(const char *, UInt32, const void *, Boolean,
+ SecAccessRef, SecKeychainRef *);
+OSStatus SecKeychainDelete(SecKeychainRef);
+"""
+
+MACROS = """
+"""
+
+CUSTOMIZATIONS = """
+"""
+
+CONDITIONAL_NAMES = {}
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/sectransform.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/sectransform.py
new file mode 100644
index 0000000..d6dbc5f
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/commoncrypto/sectransform.py
@@ -0,0 +1,79 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+INCLUDES = """
+#include
+#include
+#include
+"""
+
+TYPES = """
+typedef ... *SecTransformRef;
+
+CFStringRef kSecImportExportPassphrase;
+CFStringRef kSecImportExportKeychain;
+CFStringRef kSecImportExportAccess;
+
+CFStringRef kSecEncryptionMode;
+CFStringRef kSecEncryptKey;
+CFStringRef kSecIVKey;
+CFStringRef kSecModeCBCKey;
+CFStringRef kSecModeCFBKey;
+CFStringRef kSecModeECBKey;
+CFStringRef kSecModeNoneKey;
+CFStringRef kSecModeOFBKey;
+CFStringRef kSecOAEPEncodingParametersAttributeName;
+CFStringRef kSecPaddingKey;
+CFStringRef kSecPaddingNoneKey;
+CFStringRef kSecPaddingOAEPKey;
+CFStringRef kSecPaddingPKCS1Key;
+CFStringRef kSecPaddingPKCS5Key;
+CFStringRef kSecPaddingPKCS7Key;
+
+const CFStringRef kSecTransformInputAttributeName;
+const CFStringRef kSecTransformOutputAttributeName;
+const CFStringRef kSecTransformDebugAttributeName;
+const CFStringRef kSecTransformTransformName;
+const CFStringRef kSecTransformAbortAttributeName;
+
+CFStringRef kSecInputIsAttributeName;
+CFStringRef kSecInputIsPlainText;
+CFStringRef kSecInputIsDigest;
+CFStringRef kSecInputIsRaw;
+
+const CFStringRef kSecDigestTypeAttribute;
+const CFStringRef kSecDigestLengthAttribute;
+const CFStringRef kSecDigestMD5;
+const CFStringRef kSecDigestSHA1;
+const CFStringRef kSecDigestSHA2;
+"""
+
+FUNCTIONS = """
+Boolean SecTransformSetAttribute(SecTransformRef, CFStringRef, CFTypeRef,
+ CFErrorRef *);
+SecTransformRef SecDecryptTransformCreate(SecKeyRef, CFErrorRef *);
+SecTransformRef SecEncryptTransformCreate(SecKeyRef, CFErrorRef *);
+SecTransformRef SecVerifyTransformCreate(SecKeyRef, CFDataRef, CFErrorRef *);
+SecTransformRef SecSignTransformCreate(SecKeyRef, CFErrorRef *) ;
+CFTypeRef SecTransformExecute(SecTransformRef, CFErrorRef *);
+"""
+
+MACROS = """
+"""
+
+CUSTOMIZATIONS = """
+"""
+
+CONDITIONAL_NAMES = {}
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/aes.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/aes.py
index 17c154c..e407152 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/aes.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/aes.py
@@ -38,10 +38,18 @@ int AES_wrap_key(AES_KEY *, const unsigned char *, unsigned char *,
const unsigned char *, unsigned int);
int AES_unwrap_key(AES_KEY *, const unsigned char *, unsigned char *,
const unsigned char *, unsigned int);
+
+/* The ctr128_encrypt function is only useful in 0.9.8. You should use EVP for
+ this in 1.0.0+. It is defined in macros because the function signature
+ changed after 0.9.8 */
+void AES_ctr128_encrypt(const unsigned char *, unsigned char *,
+ const size_t, const AES_KEY *,
+ unsigned char[], unsigned char[], unsigned int *);
+
"""
CUSTOMIZATIONS = """
-// OpenSSL 0.9.8h+
+/* OpenSSL 0.9.8h+ */
#if OPENSSL_VERSION_NUMBER >= 0x0090808fL
static const long Cryptography_HAS_AES_WRAP = 1;
#else
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/asn1.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/asn1.py
index dfdf1bf..2edfd2d 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/asn1.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/asn1.py
@@ -141,6 +141,9 @@ ASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *, ASN1_INTEGER *);
/* These isn't a macro the arg is const on openssl 1.0.2+ */
int ASN1_GENERALIZEDTIME_check(ASN1_GENERALIZEDTIME *);
+
+/* Not a macro, const on openssl 1.0 */
+int ASN1_STRING_set_default_mask_asc(char *);
"""
CUSTOMIZATIONS = """
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py
index aa0525f..4cd1b89 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py
@@ -13,6 +13,7 @@
from __future__ import absolute_import, division, print_function
+import os
import sys
import threading
@@ -74,6 +75,7 @@ class Binding(object):
"x509",
"x509name",
"x509v3",
+ "x509_vfy"
]
_locks = None
@@ -96,7 +98,8 @@ class Binding(object):
if sys.platform != "win32":
libraries = ["crypto", "ssl"]
else: # pragma: no cover
- libraries = ["libeay32", "ssleay32", "advapi32"]
+ link_type = os.environ.get("PYCA_WINDOWS_LINK_TYPE", "static")
+ libraries = _get_windows_libraries(link_type)
cls.ffi, cls.lib = build_ffi(
module_prefix=cls._module_prefix,
@@ -149,7 +152,19 @@ class Binding(object):
lock.release()
else:
raise RuntimeError(
- "Unknown lock mode {0}: lock={1}, file={2}, line={3}".format(
+ "Unknown lock mode {0}: lock={1}, file={2}, line={3}.".format(
mode, n, file, line
)
)
+
+
+def _get_windows_libraries(link_type):
+ if link_type == "dynamic":
+ return ["libeay32", "ssleay32", "advapi32"]
+ elif link_type == "static" or link_type == "":
+ return ["libeay32mt", "ssleay32mt", "advapi32",
+ "crypt32", "gdi32", "user32", "ws2_32"]
+ else:
+ raise ValueError(
+ "PYCA_WINDOWS_LINK_TYPE must be 'static' or 'dynamic'"
+ )
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/cms.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/cms.py
index a3760f2..cbf4b28 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/cms.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/cms.py
@@ -15,8 +15,8 @@ from __future__ import absolute_import, division, print_function
INCLUDES = """
#if !defined(OPENSSL_NO_CMS) && OPENSSL_VERSION_NUMBER >= 0x0090808fL
-// The next define should really be in the OpenSSL header, but it is missing.
-// Failing to include this on Windows causes compilation failures.
+/* The next define should really be in the OpenSSL header, but it is missing.
+ Failing to include this on Windows causes compilation failures. */
#if defined(OPENSSL_SYS_WINDOWS)
#include
#endif
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/conf.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/conf.py
index dda35e8..001a070 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/conf.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/conf.py
@@ -22,6 +22,8 @@ typedef ... CONF;
"""
FUNCTIONS = """
+void OPENSSL_config(const char *);
+void OPENSSL_no_config(void);
"""
MACROS = """
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/dh.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/dh.py
index a0f9947..e2e8976 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/dh.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/dh.py
@@ -19,13 +19,13 @@ INCLUDES = """
TYPES = """
typedef struct dh_st {
- // prime number (shared)
+ /* Prime number (shared) */
BIGNUM *p;
- // generator of Z_p (shared)
+ /* Generator of Z_p (shared) */
BIGNUM *g;
- // private DH value x
+ /* Private DH value x */
BIGNUM *priv_key;
- // public DH value g^x
+ /* Public DH value g^x */
BIGNUM *pub_key;
...;
} DH;
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/dsa.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/dsa.py
index 7db0332..c9aa888 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/dsa.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/dsa.py
@@ -19,15 +19,15 @@ INCLUDES = """
TYPES = """
typedef struct dsa_st {
- // prime number (public)
+ /* Prime number (public) */
BIGNUM *p;
- // 160-bit subprime, q | p-1 (public)
+ /* Subprime (160-bit, q | p-1, public) */
BIGNUM *q;
- // generator of subgroup (public)
+ /* Generator of subgroup (public) */
BIGNUM *g;
- // private key x
+ /* Private key x */
BIGNUM *priv_key;
- // public key y = g^x
+ /* Public key y = g^x */
BIGNUM *pub_key;
...;
} DSA;
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/ec.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/ec.py
index 45c17c2..26fc8ff 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/ec.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/ec.py
@@ -27,6 +27,8 @@ static const int Cryptography_HAS_EC_1_0_1;
static const int Cryptography_HAS_EC_NISTP_64_GCC_128;
static const int Cryptography_HAS_EC2M;
+static const int OPENSSL_EC_NAMED_CURVE;
+
typedef ... EC_KEY;
typedef ... EC_GROUP;
typedef ... EC_POINT;
@@ -61,6 +63,8 @@ int EC_GROUP_set_curve_GF2m(
int EC_GROUP_get_curve_GF2m(
const EC_GROUP *, BIGNUM *, BIGNUM *, BIGNUM *, BN_CTX *);
+int EC_GROUP_get_degree(const EC_GROUP *);
+
const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *);
const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *);
int EC_GROUP_get_curve_name(const EC_GROUP *);
@@ -198,6 +202,7 @@ int EC_METHOD_get_field_type(const EC_METHOD *);
CUSTOMIZATIONS = """
#ifdef OPENSSL_NO_EC
static const long Cryptography_HAS_EC = 0;
+
typedef void EC_KEY;
typedef void EC_GROUP;
typedef void EC_POINT;
@@ -208,6 +213,8 @@ typedef struct {
} EC_builtin_curve;
typedef long point_conversion_form_t;
+static const int OPENSSL_EC_NAMED_CURVE = 0;
+
void (*EC_KEY_free)(EC_KEY *) = NULL;
size_t (*EC_get_builtin_curves)(EC_builtin_curve *, size_t) = NULL;
EC_KEY *(*EC_KEY_new_by_curve_name)(int) = NULL;
@@ -250,6 +257,8 @@ int (*EC_GROUP_set_curve_GFp)(
int (*EC_GROUP_get_curve_GFp)(
const EC_GROUP *, BIGNUM *, BIGNUM *, BIGNUM *, BN_CTX *);
+int (*EC_GROUP_get_degree)(const EC_GROUP *) = NULL;
+
const EC_METHOD *(*EC_GROUP_method_of)(const EC_GROUP *) = NULL;
const EC_POINT *(*EC_GROUP_get0_generator)(const EC_GROUP *) = NULL;
int (*EC_GROUP_get_curve_name)(const EC_GROUP *) = NULL;
@@ -389,6 +398,7 @@ static const long Cryptography_HAS_EC2M = 1;
CONDITIONAL_NAMES = {
"Cryptography_HAS_EC": [
+ "OPENSSL_EC_NAMED_CURVE",
"EC_GROUP_new",
"EC_GROUP_free",
"EC_GROUP_clear_free",
@@ -399,6 +409,7 @@ CONDITIONAL_NAMES = {
"EC_GROUP_method_of",
"EC_GROUP_get0_generator",
"EC_GROUP_get_curve_name",
+ "EC_GROUP_get_degree",
"EC_KEY_free",
"EC_get_builtin_curves",
"EC_KEY_new_by_curve_name",
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/err.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/err.py
index f6456d6..232060a 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/err.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/err.py
@@ -21,6 +21,7 @@ TYPES = """
static const int Cryptography_HAS_REMOVE_THREAD_STATE;
static const int Cryptography_HAS_098H_ERROR_CODES;
static const int Cryptography_HAS_098C_CAMELLIA_CODES;
+static const int Cryptography_HAS_EC_CODES;
struct ERR_string_data_st {
unsigned long error;
@@ -28,8 +29,8 @@ struct ERR_string_data_st {
};
typedef struct ERR_string_data_st ERR_STRING_DATA;
-
static const int ERR_LIB_EVP;
+static const int ERR_LIB_EC;
static const int ERR_LIB_PEM;
static const int ERR_LIB_ASN1;
static const int ERR_LIB_RSA;
@@ -135,6 +136,7 @@ static const int EVP_F_PKCS5_V2_PBE_KEYIVGEN;
static const int EVP_F_PKCS8_SET_BROKEN;
static const int EVP_F_RC2_MAGIC_TO_METH;
static const int EVP_F_RC5_CTRL;
+
static const int EVP_R_AES_KEY_SETUP_FAILED;
static const int EVP_R_ASN1_LIB;
static const int EVP_R_BAD_BLOCK_LENGTH;
@@ -168,9 +170,14 @@ static const int EVP_R_UNSUPPORTED_CIPHER;
static const int EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION;
static const int EVP_R_UNSUPPORTED_KEYLENGTH;
static const int EVP_R_UNSUPPORTED_SALT_TYPE;
+static const int EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM;
static const int EVP_R_WRONG_FINAL_BLOCK_LENGTH;
static const int EVP_R_WRONG_PUBLIC_KEY_TYPE;
+static const int EC_F_EC_GROUP_NEW_BY_CURVE_NAME;
+
+static const int EC_R_UNKNOWN_GROUP;
+
static const int PEM_F_D2I_PKCS8PRIVATEKEY_BIO;
static const int PEM_F_D2I_PKCS8PRIVATEKEY_FP;
static const int PEM_F_DO_PK8PKEY;
@@ -283,7 +290,7 @@ typedef uint32_t CRYPTO_THREADID;
void (*ERR_remove_thread_state)(const CRYPTO_THREADID *) = NULL;
#endif
-// OpenSSL 0.9.8h+
+/* OpenSSL 0.9.8h+ */
#if OPENSSL_VERSION_NUMBER >= 0x0090808fL
static const long Cryptography_HAS_098H_ERROR_CODES = 1;
#else
@@ -297,7 +304,7 @@ static const int ASN1_R_NO_MULTIPART_BODY_FAILURE = 0;
static const int ASN1_R_NO_MULTIPART_BOUNDARY = 0;
#endif
-// OpenSSL 0.9.8c+
+/* OpenSSL 0.9.8c+ */
#ifdef EVP_F_CAMELLIA_INIT_KEY
static const long Cryptography_HAS_098C_CAMELLIA_CODES = 1;
#else
@@ -306,6 +313,14 @@ static const int EVP_F_CAMELLIA_INIT_KEY = 0;
static const int EVP_R_CAMELLIA_KEY_SETUP_FAILED = 0;
#endif
+// OpenSSL without EC. e.g. RHEL
+#ifndef OPENSSL_NO_EC
+static const long Cryptography_HAS_EC_CODES = 1;
+#else
+static const long Cryptography_HAS_EC_CODES = 0;
+static const int EC_R_UNKNOWN_GROUP = 0;
+static const int EC_F_EC_GROUP_NEW_BY_CURVE_NAME = 0;
+#endif
"""
CONDITIONAL_NAMES = {
@@ -324,5 +339,9 @@ CONDITIONAL_NAMES = {
"Cryptography_HAS_098C_CAMELLIA_CODES": [
"EVP_F_CAMELLIA_INIT_KEY",
"EVP_R_CAMELLIA_KEY_SETUP_FAILED"
+ ],
+ "Cryptography_HAS_EC_CODES": [
+ "EC_R_UNKNOWN_GROUP",
+ "EC_F_EC_GROUP_NEW_BY_CURVE_NAME"
]
}
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/evp.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/evp.py
index b3d958e..1183450 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/evp.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/evp.py
@@ -139,7 +139,8 @@ int PKCS5_PBKDF2_HMAC(const char *, int, const unsigned char *, int, int,
int EVP_PKEY_CTX_set_signature_md(EVP_PKEY_CTX *, const EVP_MD *);
-// not macros but must be in this section since they're not available in 0.9.8
+/* These aren't macros, but must be in this section because they're not
+ available in 0.9.8. */
EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *, ENGINE *);
EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int, ENGINE *);
EVP_PKEY_CTX *EVP_PKEY_CTX_dup(EVP_PKEY_CTX *);
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/nid.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/nid.py
index ea6fd4d..133d2ca 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/nid.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/nid.py
@@ -42,6 +42,7 @@ static const int NID_ecdsa_with_SHA512;
static const int NID_crl_reason;
static const int NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
static const int NID_subject_alt_name;
+static const int NID_issuer_alt_name;
static const int NID_X9_62_c2pnb163v1;
static const int NID_X9_62_c2pnb163v2;
static const int NID_X9_62_c2pnb163v3;
@@ -193,7 +194,7 @@ MACROS = """
"""
CUSTOMIZATIONS = """
-// OpenSSL 0.9.8g+
+/* OpenSSL 0.9.8g+ */
#if OPENSSL_VERSION_NUMBER >= 0x0090807fL
static const long Cryptography_HAS_ECDSA_SHA2_NIDS = 1;
#else
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/opensslv.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/opensslv.py
index e4aa621..ef6e057 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/opensslv.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/opensslv.py
@@ -18,6 +18,8 @@ INCLUDES = """
"""
TYPES = """
+/* Note that these will be resolved when cryptography is compiled and are NOT
+ guaranteed to be the version that it actually loads. */
static const int OPENSSL_VERSION_NUMBER;
static const char *const OPENSSL_VERSION_TEXT;
"""
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/pem.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/pem.py
index e42fc6f..752f198 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/pem.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/pem.py
@@ -41,6 +41,7 @@ int i2d_PKCS8PrivateKey_bio(BIO *, EVP_PKEY *, const EVP_CIPHER *,
int i2d_PKCS8PrivateKey_nid_bio(BIO *, EVP_PKEY *, int,
char *, int, pem_password_cb *, void *);
+PKCS7 *d2i_PKCS7_bio(BIO *, PKCS7 **);
EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *, EVP_PKEY **, pem_password_cb *,
void *);
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/rsa.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/rsa.py
index c635610..cb8e701 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/rsa.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/rsa.py
@@ -80,7 +80,7 @@ CUSTOMIZATIONS = """
#if OPENSSL_VERSION_NUMBER >= 0x10000000
static const long Cryptography_HAS_PSS_PADDING = 1;
#else
-// see evp.py for the definition of Cryptography_HAS_PKEY_CTX
+/* see evp.py for the definition of Cryptography_HAS_PKEY_CTX */
static const long Cryptography_HAS_PSS_PADDING = 0;
int (*EVP_PKEY_CTX_set_rsa_padding)(EVP_PKEY_CTX *, int) = NULL;
int (*EVP_PKEY_CTX_set_rsa_pss_saltlen)(EVP_PKEY_CTX *, int) = NULL;
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/ssl.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/ssl.py
index 0b15411..7d805e7 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/ssl.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/ssl.py
@@ -15,6 +15,8 @@ from __future__ import absolute_import, division, print_function
INCLUDES = """
#include
+
+typedef STACK_OF(SSL_CIPHER) Cryptography_STACK_OF_SSL_CIPHER;
"""
TYPES = """
@@ -24,6 +26,7 @@ TYPES = """
static const long Cryptography_HAS_SSL2;
static const long Cryptography_HAS_TLSv1_1;
static const long Cryptography_HAS_TLSv1_2;
+static const long Cryptography_HAS_SECURE_RENEGOTIATION;
/* Internally invented symbol to tell us if SNI is supported */
static const long Cryptography_HAS_TLSEXT_HOSTNAME;
@@ -43,6 +46,7 @@ static const long Cryptography_HAS_SSL_SET_SSL_CTX;
static const long Cryptography_HAS_SSL_OP_NO_TICKET;
static const long Cryptography_HAS_NETBSD_D1_METH;
static const long Cryptography_HAS_NEXTPROTONEG;
+static const long Cryptography_HAS_ALPN;
static const long SSL_FILETYPE_PEM;
static const long SSL_FILETYPE_ASN1;
@@ -84,6 +88,8 @@ static const long SSL_OP_COOKIE_EXCHANGE;
static const long SSL_OP_NO_TICKET;
static const long SSL_OP_ALL;
static const long SSL_OP_SINGLE_ECDH_USE;
+static const long SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION;
+static const long SSL_OP_LEGACY_SERVER_CONNECT;
static const long SSL_VERIFY_PEER;
static const long SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
static const long SSL_VERIFY_CLIENT_ONCE;
@@ -121,9 +127,6 @@ static const long SSL_MODE_ENABLE_PARTIAL_WRITE;
static const long SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
static const long SSL_MODE_AUTO_RETRY;
static const long SSL3_RANDOM_SIZE;
-typedef ... X509_STORE_CTX;
-static const long X509_V_OK;
-static const long X509_V_ERR_APPLICATION_VERIFICATION;
typedef ... SSL_METHOD;
typedef struct ssl_st {
int version;
@@ -153,6 +156,8 @@ typedef struct {
static const long TLSEXT_NAMETYPE_host_name;
typedef ... SSL_CIPHER;
+typedef ... Cryptography_STACK_OF_SSL_CIPHER;
+typedef ... COMP_METHOD;
"""
FUNCTIONS = """
@@ -190,6 +195,11 @@ int SSL_get_error(const SSL *, int);
int SSL_do_handshake(SSL *);
int SSL_shutdown(SSL *);
const char *SSL_get_cipher_list(const SSL *, int);
+Cryptography_STACK_OF_SSL_CIPHER *SSL_get_ciphers(const SSL *);
+
+const COMP_METHOD *SSL_get_current_compression(SSL *);
+const COMP_METHOD *SSL_get_current_expansion(SSL *);
+const char *SSL_COMP_get_name(const COMP_METHOD *);
/* context */
void SSL_CTX_free(SSL_CTX *);
@@ -215,16 +225,6 @@ int SSL_CTX_add_client_CA(SSL_CTX *, X509 *);
void SSL_CTX_set_client_CA_list(SSL_CTX *, Cryptography_STACK_OF_X509_NAME *);
-
-/* X509_STORE_CTX */
-int X509_STORE_CTX_get_error(X509_STORE_CTX *);
-void X509_STORE_CTX_set_error(X509_STORE_CTX *, int);
-int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *);
-X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *);
-int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *, int, void *);
-void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *, int);
-
-
/* SSL_SESSION */
void SSL_SESSION_free(SSL_SESSION *);
@@ -248,6 +248,7 @@ int SSL_want_read(const SSL *);
int SSL_want_write(const SSL *);
long SSL_total_renegotiations(SSL *);
+long SSL_get_secure_renegotiation_support(SSL *);
/* Defined as unsigned long because SSL_OP_ALL is greater than signed 32-bit
and Windows defines long as 32-bit. */
@@ -351,9 +352,38 @@ int SSL_select_next_proto(unsigned char **, unsigned char *,
const unsigned char *, unsigned int);
void SSL_get0_next_proto_negotiated(const SSL *,
const unsigned char **, unsigned *);
+
+int sk_SSL_CIPHER_num(Cryptography_STACK_OF_SSL_CIPHER *);
+SSL_CIPHER *sk_SSL_CIPHER_value(Cryptography_STACK_OF_SSL_CIPHER *, int);
+
+/* ALPN APIs were introduced in OpenSSL 1.0.2. To continue to support earlier
+ * versions some special handling of these is necessary.
+ */
+int SSL_CTX_set_alpn_protos(SSL_CTX *, const unsigned char*, unsigned);
+int SSL_set_alpn_protos(SSL *, const unsigned char*, unsigned);
+void SSL_CTX_set_alpn_select_cb(SSL_CTX *,
+ int (*) (SSL *,
+ const unsigned char **,
+ unsigned char *,
+ const unsigned char *,
+ unsigned int,
+ void *),
+ void *);
+void SSL_get0_alpn_selected(const SSL *, const unsigned char **, unsigned *);
"""
CUSTOMIZATIONS = """
+/** Secure renegotiation is supported in OpenSSL >= 0.9.8m
+ * But some Linux distributions have back ported some features.
+ */
+#ifndef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
+static const long Cryptography_HAS_SECURE_RENEGOTIATION = 0;
+long (*SSL_get_secure_renegotiation_support)(SSL *) = NULL;
+const long SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = 0;
+const long SSL_OP_LEGACY_SERVER_CONNECT = 0;
+#else
+static const long Cryptography_HAS_SECURE_RENEGOTIATION = 1;
+#endif
#ifdef OPENSSL_NO_SSL2
static const long Cryptography_HAS_SSL2 = 0;
SSL_METHOD* (*SSLv2_method)(void) = NULL;
@@ -426,7 +456,7 @@ static const long Cryptography_HAS_SSL_OP_NO_TICKET = 0;
const long SSL_OP_NO_TICKET = 0;
#endif
-// OpenSSL 0.9.8f+
+/* OpenSSL 0.9.8f+ */
#if OPENSSL_VERSION_NUMBER >= 0x00908070L
static const long Cryptography_HAS_SSL_SET_SSL_CTX = 1;
#else
@@ -453,7 +483,7 @@ static const long Cryptography_HAS_NETBSD_D1_METH = 1;
static const long Cryptography_HAS_NETBSD_D1_METH = 1;
#endif
-// Workaround for #794 caused by cffi const** bug.
+/* Workaround for #794 caused by cffi const** bug. */
const SSL_METHOD* Cryptography_SSL_CTX_get_method(const SSL_CTX* ctx) {
return ctx->method;
}
@@ -488,6 +518,28 @@ void (*SSL_get0_next_proto_negotiated)(const SSL *,
#else
static const long Cryptography_HAS_NEXTPROTONEG = 1;
#endif
+
+/* ALPN was added in OpenSSL 1.0.2. */
+#if OPENSSL_VERSION_NUMBER < 0x10002001L
+int (*SSL_CTX_set_alpn_protos)(SSL_CTX *,
+ const unsigned char*,
+ unsigned) = NULL;
+int (*SSL_set_alpn_protos)(SSL *, const unsigned char*, unsigned) = NULL;
+void (*SSL_CTX_set_alpn_select_cb)(SSL_CTX *,
+ int (*) (SSL *,
+ const unsigned char **,
+ unsigned char *,
+ const unsigned char *,
+ unsigned int,
+ void *),
+ void *) = NULL;
+void (*SSL_get0_alpn_selected)(const SSL *,
+ const unsigned char **,
+ unsigned *) = NULL;
+static const long Cryptography_HAS_ALPN = 0;
+#else
+static const long Cryptography_HAS_ALPN = 1;
+#endif
"""
CONDITIONAL_NAMES = {
@@ -551,5 +603,18 @@ CONDITIONAL_NAMES = {
"SSL_CTX_set_next_proto_select_cb",
"SSL_select_next_proto",
"SSL_get0_next_proto_negotiated",
+ ],
+
+ "Cryptography_HAS_SECURE_RENEGOTIATION": [
+ "SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION",
+ "SSL_OP_LEGACY_SERVER_CONNECT",
+ "SSL_get_secure_renegotiation_support",
+ ],
+
+ "Cryptography_HAS_ALPN": [
+ "SSL_CTX_set_alpn_protos",
+ "SSL_set_alpn_protos",
+ "SSL_CTX_set_alpn_select_cb",
+ "SSL_get0_alpn_selected",
]
}
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509.py
index 36a15e4..b74c118 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509.py
@@ -24,11 +24,13 @@ INCLUDES = """
* Note that the result is an opaque type.
*/
typedef STACK_OF(X509) Cryptography_STACK_OF_X509;
+typedef STACK_OF(X509_CRL) Cryptography_STACK_OF_X509_CRL;
typedef STACK_OF(X509_REVOKED) Cryptography_STACK_OF_X509_REVOKED;
"""
TYPES = """
typedef ... Cryptography_STACK_OF_X509;
+typedef ... Cryptography_STACK_OF_X509_CRL;
typedef ... Cryptography_STACK_OF_X509_REVOKED;
typedef struct {
@@ -76,7 +78,6 @@ typedef struct {
...;
} X509;
-typedef ... X509_STORE;
typedef ... NETSCAPE_SPKI;
"""
@@ -166,12 +167,6 @@ EVP_PKEY *d2i_PUBKEY_bio(BIO *, EVP_PKEY **);
ASN1_INTEGER *X509_get_serialNumber(X509 *);
int X509_set_serialNumber(X509 *, ASN1_INTEGER *);
-/* X509_STORE */
-X509_STORE *X509_STORE_new(void);
-void X509_STORE_free(X509_STORE *);
-int X509_STORE_add_cert(X509_STORE *, X509 *);
-int X509_verify_cert(X509_STORE_CTX *);
-
const char *X509_verify_cert_error_string(long);
const char *X509_get_default_cert_area(void);
@@ -190,7 +185,6 @@ DSA *d2i_DSA_PUBKEY(DSA **, const unsigned char **, long);
DSA *d2i_DSAPublicKey(DSA **, const unsigned char **, long);
DSA *d2i_DSAPrivateKey(DSA **, const unsigned char **, long);
-
RSA *d2i_RSAPrivateKey_bio(BIO *, RSA **);
int i2d_RSAPrivateKey_bio(BIO *, RSA *);
RSA *d2i_RSAPublicKey_bio(BIO *, RSA **);
@@ -237,7 +231,7 @@ int i2d_DSAPrivateKey(DSA *, unsigned char **);
int X509_CRL_set_lastUpdate(X509_CRL *, ASN1_TIME *);
int X509_CRL_set_nextUpdate(X509_CRL *, ASN1_TIME *);
-/* these use STACK_OF(X509_EXTENSION) in 0.9.8e. Once we drop support for
+/* These use STACK_OF(X509_EXTENSION) in 0.9.8e. Once we drop support for
RHEL/CentOS 5 we should move these back to FUNCTIONS. */
int X509_REQ_add_extensions(X509_REQ *, X509_EXTENSIONS *);
X509_EXTENSIONS *X509_REQ_get_extensions(X509_REQ *);
@@ -251,7 +245,7 @@ int i2d_ECPrivateKey_bio(BIO *, EC_KEY *);
"""
CUSTOMIZATIONS = """
-// OpenSSL 0.9.8e does not have this definition
+/* OpenSSL 0.9.8e does not have this definition. */
#if OPENSSL_VERSION_NUMBER <= 0x0090805fL
typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS;
#endif
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509_vfy.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509_vfy.py
new file mode 100644
index 0000000..601926c
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509_vfy.py
@@ -0,0 +1,336 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+INCLUDES = """
+#include
+
+/*
+ * This is part of a work-around for the difficulty cffi has in dealing with
+ * `STACK_OF(foo)` as the name of a type. We invent a new, simpler name that
+ * will be an alias for this type and use the alias throughout. This works
+ * together with another opaque typedef for the same name in the TYPES section.
+ * Note that the result is an opaque type.
+ */
+typedef STACK_OF(ASN1_OBJECT) Cryptography_STACK_OF_ASN1_OBJECT;
+"""
+
+TYPES = """
+static const long Cryptography_HAS_102_VERIFICATION_ERROR_CODES;
+static const long Cryptography_HAS_102_VERIFICATION_PARAMS;
+static const long Cryptography_HAS_X509_V_FLAG_TRUSTED_FIRST;
+static const long Cryptography_HAS_X509_V_FLAG_PARTIAL_CHAIN;
+static const long Cryptography_HAS_100_VERIFICATION_ERROR_CODES;
+static const long Cryptography_HAS_100_VERIFICATION_PARAMS;
+static const long Cryptography_HAS_X509_V_FLAG_CHECK_SS_SIGNATURE;
+
+typedef ... Cryptography_STACK_OF_ASN1_OBJECT;
+
+typedef ... X509_STORE;
+typedef ... X509_STORE_CTX;
+typedef ... X509_VERIFY_PARAM;
+
+/* While these are defined in the source as ints, they're tagged here
+ as longs, just in case they ever grow to large, such as what we saw
+ with OP_ALL. */
+
+/* Verification error codes */
+static const int X509_V_OK;
+static const int X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT;
+static const int X509_V_ERR_UNABLE_TO_GET_CRL;
+static const int X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE;
+static const int X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE;
+static const int X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY;
+static const int X509_V_ERR_CERT_SIGNATURE_FAILURE;
+static const int X509_V_ERR_CRL_SIGNATURE_FAILURE;
+static const int X509_V_ERR_CERT_NOT_YET_VALID;
+static const int X509_V_ERR_CERT_HAS_EXPIRED;
+static const int X509_V_ERR_CRL_NOT_YET_VALID;
+static const int X509_V_ERR_CRL_HAS_EXPIRED;
+static const int X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD;
+static const int X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD;
+static const int X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD;
+static const int X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD;
+static const int X509_V_ERR_OUT_OF_MEM;
+static const int X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT;
+static const int X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
+static const int X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY;
+static const int X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE;
+static const int X509_V_ERR_CERT_CHAIN_TOO_LONG;
+static const int X509_V_ERR_CERT_REVOKED;
+static const int X509_V_ERR_INVALID_CA;
+static const int X509_V_ERR_PATH_LENGTH_EXCEEDED;
+static const int X509_V_ERR_INVALID_PURPOSE;
+static const int X509_V_ERR_CERT_UNTRUSTED;
+static const int X509_V_ERR_CERT_REJECTED;
+static const int X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
+static const int X509_V_ERR_AKID_SKID_MISMATCH;
+static const int X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
+static const int X509_V_ERR_KEYUSAGE_NO_CERTSIGN;
+static const int X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER;
+static const int X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION;
+static const int X509_V_ERR_KEYUSAGE_NO_CRL_SIGN;
+static const int X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION;
+static const int X509_V_ERR_INVALID_NON_CA;
+static const int X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED;
+static const int X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
+static const int X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED;
+static const int X509_V_ERR_INVALID_EXTENSION;
+static const int X509_V_ERR_INVALID_POLICY_EXTENSION;
+static const int X509_V_ERR_NO_EXPLICIT_POLICY;
+static const int X509_V_ERR_DIFFERENT_CRL_SCOPE;
+static const int X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE;
+static const int X509_V_ERR_UNNESTED_RESOURCE;
+static const int X509_V_ERR_PERMITTED_VIOLATION;
+static const int X509_V_ERR_EXCLUDED_VIOLATION;
+static const int X509_V_ERR_SUBTREE_MINMAX;
+static const int X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE;
+static const int X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX;
+static const int X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
+static const int X509_V_ERR_CRL_PATH_VALIDATION_ERROR;
+static const int X509_V_ERR_SUITE_B_INVALID_VERSION;
+static const int X509_V_ERR_SUITE_B_INVALID_ALGORITHM;
+static const int X509_V_ERR_SUITE_B_INVALID_CURVE;
+static const int X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM;
+static const int X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED;
+static const int X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256;
+static const int X509_V_ERR_HOSTNAME_MISMATCH;
+static const int X509_V_ERR_EMAIL_MISMATCH;
+static const int X509_V_ERR_IP_ADDRESS_MISMATCH;
+static const int X509_V_ERR_APPLICATION_VERIFICATION;
+
+/* Verification parameters */
+static const long X509_V_FLAG_CB_ISSUER_CHECK;
+static const long X509_V_FLAG_USE_CHECK_TIME;
+static const long X509_V_FLAG_CRL_CHECK;
+static const long X509_V_FLAG_CRL_CHECK_ALL;
+static const long X509_V_FLAG_IGNORE_CRITICAL;
+static const long X509_V_FLAG_X509_STRICT;
+static const long X509_V_FLAG_ALLOW_PROXY_CERTS;
+static const long X509_V_FLAG_POLICY_CHECK;
+static const long X509_V_FLAG_EXPLICIT_POLICY;
+static const long X509_V_FLAG_INHIBIT_ANY;
+static const long X509_V_FLAG_INHIBIT_MAP;
+static const long X509_V_FLAG_NOTIFY_POLICY;
+static const long X509_V_FLAG_EXTENDED_CRL_SUPPORT;
+static const long X509_V_FLAG_USE_DELTAS;
+static const long X509_V_FLAG_CHECK_SS_SIGNATURE;
+static const long X509_V_FLAG_TRUSTED_FIRST;
+static const long X509_V_FLAG_SUITEB_128_LOS_ONLY;
+static const long X509_V_FLAG_SUITEB_192_LOS;
+static const long X509_V_FLAG_SUITEB_128_LOS;
+static const long X509_V_FLAG_PARTIAL_CHAIN;
+"""
+
+FUNCTIONS = """
+int X509_verify_cert(X509_STORE_CTX *);
+
+/* X509_STORE */
+X509_STORE *X509_STORE_new(void);
+void X509_STORE_free(X509_STORE *);
+int X509_STORE_add_cert(X509_STORE *, X509 *);
+
+/* X509_STORE_CTX */
+X509_STORE_CTX *X509_STORE_CTX_new(void);
+void X509_STORE_CTX_cleanup(X509_STORE_CTX *);
+void X509_STORE_CTX_free(X509_STORE_CTX *);
+int X509_STORE_CTX_init(X509_STORE_CTX *, X509_STORE *, X509 *,
+ Cryptography_STACK_OF_X509 *);
+void X509_STORE_CTX_trusted_stack(X509_STORE_CTX *,
+ Cryptography_STACK_OF_X509 *);
+void X509_STORE_CTX_set_cert(X509_STORE_CTX *, X509 *);
+void X509_STORE_CTX_set_chain(X509_STORE_CTX *,Cryptography_STACK_OF_X509 *);
+X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(X509_STORE_CTX *);
+void X509_STORE_CTX_set0_param(X509_STORE_CTX *, X509_VERIFY_PARAM *);
+int X509_STORE_CTX_set_default(X509_STORE_CTX *, const char *);
+void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *,
+ int (*)(int, X509_STORE_CTX *));
+Cryptography_STACK_OF_X509 *X509_STORE_CTX_get_chain(X509_STORE_CTX *);
+Cryptography_STACK_OF_X509 *X509_STORE_CTX_get1_chain(X509_STORE_CTX *);
+int X509_STORE_CTX_get_error(X509_STORE_CTX *);
+void X509_STORE_CTX_set_error(X509_STORE_CTX *, int);
+int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *);
+X509 *X509_STORE_CTX_get_current_cert(X509_STORE_CTX *);
+int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *, int, void *);
+void *X509_STORE_CTX_get_ex_data(X509_STORE_CTX *, int);
+
+/* X509_VERIFY_PARAM */
+X509_VERIFY_PARAM *X509_VERIFY_PARAM_new(void);
+int X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *, unsigned long);
+int X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *, unsigned long);
+unsigned long X509_VERIFY_PARAM_get_flags(X509_VERIFY_PARAM *);
+int X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *, int);
+int X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *, int);
+void X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *, time_t);
+int X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *, ASN1_OBJECT *);
+int X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *,
+ Cryptography_STACK_OF_ASN1_OBJECT *);
+void X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *, int);
+int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *);
+"""
+
+MACROS = """
+/* X509_STORE_CTX */
+void X509_STORE_CTX_set0_crls(X509_STORE_CTX *,
+ Cryptography_STACK_OF_X509_CRL *);
+
+/* X509_VERIFY_PARAM */
+int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *, const char *,
+ size_t);
+void X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *, unsigned int);
+int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *, const char *,
+ size_t);
+int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *, const unsigned char *,
+ size_t);
+int X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *, const char *);
+"""
+
+CUSTOMIZATIONS = """
+/* OpenSSL 1.0.2+ verification error codes */
+#if OPENSSL_VERSION_NUMBER >= 0x10002000L
+static const long Cryptography_HAS_102_VERIFICATION_ERROR_CODES = 1;
+#else
+static const long Cryptography_HAS_102_VERIFICATION_ERROR_CODES = 0;
+static const long X509_V_ERR_SUITE_B_INVALID_VERSION = 0;
+static const long X509_V_ERR_SUITE_B_INVALID_ALGORITHM = 0;
+static const long X509_V_ERR_SUITE_B_INVALID_CURVE = 0;
+static const long X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM = 0;
+static const long X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED = 0;
+static const long X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 = 0;
+static const long X509_V_ERR_HOSTNAME_MISMATCH = 0;
+static const long X509_V_ERR_EMAIL_MISMATCH = 0;
+static const long X509_V_ERR_IP_ADDRESS_MISMATCH = 0;
+#endif
+
+/* OpenSSL 1.0.2+ verification parameters */
+#if OPENSSL_VERSION_NUMBER >= 0x10002000L
+static const long Cryptography_HAS_102_VERIFICATION_PARAMS = 1;
+#else
+static const long Cryptography_HAS_102_VERIFICATION_PARAMS = 0;
+/* X509_V_FLAG_TRUSTED_FIRST is also new in 1.0.2+, but it is added separately
+ below because it shows up in some earlier 3rd party OpenSSL packages. */
+static const long X509_V_FLAG_SUITEB_128_LOS_ONLY = 0;
+static const long X509_V_FLAG_SUITEB_192_LOS = 0;
+static const long X509_V_FLAG_SUITEB_128_LOS = 0;
+
+int (*X509_VERIFY_PARAM_set1_host)(X509_VERIFY_PARAM *, const char *,
+ size_t) = NULL;
+int (*X509_VERIFY_PARAM_set1_email)(X509_VERIFY_PARAM *, const char *,
+ size_t) = NULL;
+int (*X509_VERIFY_PARAM_set1_ip)(X509_VERIFY_PARAM *, const unsigned char *,
+ size_t) = NULL;
+int (*X509_VERIFY_PARAM_set1_ip_asc)(X509_VERIFY_PARAM *, const char *) = NULL;
+void (*X509_VERIFY_PARAM_set_hostflags)(X509_VERIFY_PARAM *,
+ unsigned int) = NULL;
+#endif
+
+/* OpenSSL 1.0.2+ or Solaris's backport */
+#ifdef X509_V_FLAG_PARTIAL_CHAIN
+static const long Cryptography_HAS_X509_V_FLAG_PARTIAL_CHAIN = 1;
+#else
+static const long Cryptography_HAS_X509_V_FLAG_PARTIAL_CHAIN = 0;
+static const long X509_V_FLAG_PARTIAL_CHAIN = 0;
+#endif
+
+/* OpenSSL 1.0.2+, *or* Fedora 20's flavor of OpenSSL 1.0.1e... */
+#ifdef X509_V_FLAG_TRUSTED_FIRST
+static const long Cryptography_HAS_X509_V_FLAG_TRUSTED_FIRST = 1;
+#else
+static const long Cryptography_HAS_X509_V_FLAG_TRUSTED_FIRST = 0;
+static const long X509_V_FLAG_TRUSTED_FIRST = 0;
+#endif
+
+/* OpenSSL 1.0.0+ verification error codes */
+#if OPENSSL_VERSION_NUMBER >= 0x10000000L
+static const long Cryptography_HAS_100_VERIFICATION_ERROR_CODES = 1;
+#else
+static const long Cryptography_HAS_100_VERIFICATION_ERROR_CODES = 0;
+static const long X509_V_ERR_DIFFERENT_CRL_SCOPE = 0;
+static const long X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE = 0;
+static const long X509_V_ERR_PERMITTED_VIOLATION = 0;
+static const long X509_V_ERR_EXCLUDED_VIOLATION = 0;
+static const long X509_V_ERR_SUBTREE_MINMAX = 0;
+static const long X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE = 0;
+static const long X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX = 0;
+static const long X509_V_ERR_UNSUPPORTED_NAME_SYNTAX = 0;
+static const long X509_V_ERR_CRL_PATH_VALIDATION_ERROR = 0;
+#endif
+
+/* OpenSSL 1.0.0+ verification parameters */
+#if OPENSSL_VERSION_NUMBER >= 0x10000000L
+static const long Cryptography_HAS_100_VERIFICATION_PARAMS = 1;
+#else
+static const long Cryptography_HAS_100_VERIFICATION_PARAMS = 0;
+static const long X509_V_FLAG_EXTENDED_CRL_SUPPORT = 0;
+static const long X509_V_FLAG_USE_DELTAS = 0;
+#endif
+
+/* OpenSSL 0.9.8recent+ */
+#ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
+static const long Cryptography_HAS_X509_V_FLAG_CHECK_SS_SIGNATURE = 1;
+#else
+static const long Cryptography_HAS_X509_V_FLAG_CHECK_SS_SIGNATURE = 0;
+static const long X509_V_FLAG_CHECK_SS_SIGNATURE = 0;
+#endif
+"""
+
+CONDITIONAL_NAMES = {
+ "Cryptography_HAS_102_VERIFICATION_ERROR_CODES": [
+ 'X509_V_ERR_SUITE_B_INVALID_VERSION',
+ 'X509_V_ERR_SUITE_B_INVALID_ALGORITHM',
+ 'X509_V_ERR_SUITE_B_INVALID_CURVE',
+ 'X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM',
+ 'X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED',
+ 'X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256',
+ 'X509_V_ERR_HOSTNAME_MISMATCH',
+ 'X509_V_ERR_EMAIL_MISMATCH',
+ 'X509_V_ERR_IP_ADDRESS_MISMATCH'
+ ],
+ "Cryptography_HAS_102_VERIFICATION_PARAMS": [
+ "X509_V_FLAG_SUITEB_128_LOS_ONLY",
+ "X509_V_FLAG_SUITEB_192_LOS",
+ "X509_V_FLAG_SUITEB_128_LOS",
+ "X509_VERIFY_PARAM_set1_host",
+ "X509_VERIFY_PARAM_set1_email",
+ "X509_VERIFY_PARAM_set1_ip",
+ "X509_VERIFY_PARAM_set1_ip_asc",
+ "X509_VERIFY_PARAM_set_hostflags",
+ ],
+ "Cryptography_HAS_X509_V_FLAG_TRUSTED_FIRST": [
+ "X509_V_FLAG_TRUSTED_FIRST",
+ ],
+ "Cryptography_HAS_X509_V_FLAG_PARTIAL_CHAIN": [
+ "X509_V_FLAG_PARTIAL_CHAIN",
+ ],
+ "Cryptography_HAS_100_VERIFICATION_ERROR_CODES": [
+ 'X509_V_ERR_DIFFERENT_CRL_SCOPE',
+ 'X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE',
+ 'X509_V_ERR_UNNESTED_RESOURCE',
+ 'X509_V_ERR_PERMITTED_VIOLATION',
+ 'X509_V_ERR_EXCLUDED_VIOLATION',
+ 'X509_V_ERR_SUBTREE_MINMAX',
+ 'X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE',
+ 'X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX',
+ 'X509_V_ERR_UNSUPPORTED_NAME_SYNTAX',
+ 'X509_V_ERR_CRL_PATH_VALIDATION_ERROR',
+ ],
+ "Cryptography_HAS_100_VERIFICATION_PARAMS": [
+ "Cryptography_HAS_100_VERIFICATION_PARAMS",
+ "X509_V_FLAG_EXTENDED_CRL_SUPPORT",
+ "X509_V_FLAG_USE_DELTAS",
+ ],
+ "Cryptography_HAS_X509_V_FLAG_CHECK_SS_SIGNATURE": [
+ "X509_V_FLAG_CHECK_SS_SIGNATURE",
+ ]
+}
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509v3.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509v3.py
index 02ec250..cf4be1f 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509v3.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/x509v3.py
@@ -82,6 +82,8 @@ FUNCTIONS = """
void X509V3_set_ctx(X509V3_CTX *, X509 *, X509 *, X509_REQ *, X509_CRL *, int);
X509_EXTENSION *X509V3_EXT_nconf(CONF *, X509V3_CTX *, char *, char *);
int GENERAL_NAME_print(BIO *, GENERAL_NAME *);
+void GENERAL_NAMES_free(GENERAL_NAMES *);
+void *X509V3_EXT_d2i(X509_EXTENSION *);
"""
MACROS = """
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py
index aa3cdc9..04b2272 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py
@@ -13,6 +13,8 @@
from __future__ import absolute_import, division, print_function
+import warnings
+
import six
from cryptography import utils
@@ -21,31 +23,54 @@ from cryptography.hazmat.backends.interfaces import DSABackend
from cryptography.hazmat.primitives import interfaces
-def _check_dsa_parameters(modulus, subgroup_order, generator):
- if (
- not isinstance(modulus, six.integer_types) or
- not isinstance(subgroup_order, six.integer_types) or
- not isinstance(generator, six.integer_types)
- ):
- raise TypeError("DSA parameters must be integers")
+def generate_parameters(key_size, backend):
+ return backend.generate_dsa_parameters(key_size)
- if (utils.bit_length(modulus),
- utils.bit_length(subgroup_order)) not in (
+
+def generate_private_key(key_size, backend):
+ return backend.generate_dsa_private_key_and_parameters(key_size)
+
+
+def _check_dsa_parameters(parameters):
+ if (utils.bit_length(parameters.p),
+ utils.bit_length(parameters.q)) not in (
(1024, 160),
(2048, 256),
(3072, 256)):
- raise ValueError("modulus and subgroup_order lengths must be "
+ raise ValueError("p and q lengths must be "
"one of these pairs (1024, 160) or (2048, 256) "
- "or (3072, 256)")
+ "or (3072, 256).")
- if generator <= 1 or generator >= modulus:
- raise ValueError("generator must be > 1 and < modulus")
+ if not (1 < parameters.g < parameters.p):
+ raise ValueError("g, p don't satisfy 1 < g < p.")
+
+
+def _check_dsa_private_numbers(numbers):
+ parameters = numbers.public_numbers.parameter_numbers
+ _check_dsa_parameters(parameters)
+ if numbers.x <= 0 or numbers.x >= parameters.q:
+ raise ValueError("x must be > 0 and < q.")
+
+ if numbers.public_numbers.y != pow(parameters.g, numbers.x, parameters.p):
+ raise ValueError("y must be equal to (g ** x % p).")
@utils.register_interface(interfaces.DSAParameters)
class DSAParameters(object):
def __init__(self, modulus, subgroup_order, generator):
- _check_dsa_parameters(modulus, subgroup_order, generator)
+ warnings.warn(
+ "The DSAParameters class is deprecated and will be removed in a "
+ "future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
+ _check_dsa_parameters(
+ DSAParameterNumbers(
+ p=modulus,
+ q=subgroup_order,
+ g=generator
+ )
+ )
self._modulus = modulus
self._subgroup_order = subgroup_order
@@ -53,13 +78,24 @@ class DSAParameters(object):
@classmethod
def generate(cls, key_size, backend):
+ warnings.warn(
+ "generate is deprecated and will be removed in a future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
if not isinstance(backend, DSABackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement DSABackend",
+ "Backend object does not implement DSABackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
- return backend.generate_dsa_parameters(key_size)
+ parameters = backend.generate_dsa_parameters(key_size)
+ numbers = parameters.parameter_numbers()
+ return cls(
+ modulus=numbers.p,
+ subgroup_order=numbers.q,
+ generator=numbers.g
+ )
@property
def modulus(self):
@@ -89,18 +125,31 @@ class DSAParameters(object):
@utils.register_interface(interfaces.DSAPrivateKey)
class DSAPrivateKey(object):
def __init__(self, modulus, subgroup_order, generator, x, y):
- _check_dsa_parameters(modulus, subgroup_order, generator)
+ warnings.warn(
+ "The DSAPrivateKey class is deprecated and will be removed in a "
+ "future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
if (
not isinstance(x, six.integer_types) or
not isinstance(y, six.integer_types)
):
- raise TypeError("DSAPrivateKey arguments must be integers")
+ raise TypeError("DSAPrivateKey arguments must be integers.")
- if x <= 0 or x >= subgroup_order:
- raise ValueError("x must be > 0 and < subgroup_order")
-
- if y != pow(generator, x, modulus):
- raise ValueError("y must be equal to (generator ** x % modulus)")
+ _check_dsa_private_numbers(
+ DSAPrivateNumbers(
+ public_numbers=DSAPublicNumbers(
+ parameter_numbers=DSAParameterNumbers(
+ p=modulus,
+ q=subgroup_order,
+ g=generator
+ ),
+ y=y
+ ),
+ x=x
+ )
+ )
self._modulus = modulus
self._subgroup_order = subgroup_order
@@ -110,18 +159,31 @@ class DSAPrivateKey(object):
@classmethod
def generate(cls, parameters, backend):
+ warnings.warn(
+ "generate is deprecated and will be removed in a future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
if not isinstance(backend, DSABackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement DSABackend",
+ "Backend object does not implement DSABackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
- return backend.generate_dsa_private_key(parameters)
+ key = backend.generate_dsa_private_key(parameters)
+ private_numbers = key.private_numbers()
+ return cls(
+ modulus=private_numbers.public_numbers.parameter_numbers.p,
+ subgroup_order=private_numbers.public_numbers.parameter_numbers.q,
+ generator=private_numbers.public_numbers.parameter_numbers.g,
+ x=private_numbers.x,
+ y=private_numbers.public_numbers.y
+ )
def signer(self, algorithm, backend):
if not isinstance(backend, DSABackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement DSABackend",
+ "Backend object does not implement DSABackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
@@ -151,9 +213,21 @@ class DSAPrivateKey(object):
@utils.register_interface(interfaces.DSAPublicKey)
class DSAPublicKey(object):
def __init__(self, modulus, subgroup_order, generator, y):
- _check_dsa_parameters(modulus, subgroup_order, generator)
+ warnings.warn(
+ "The DSAPublicKey class is deprecated and will be removed in a "
+ "future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
+ _check_dsa_parameters(
+ DSAParameterNumbers(
+ p=modulus,
+ q=subgroup_order,
+ g=generator
+ )
+ )
if not isinstance(y, six.integer_types):
- raise TypeError("y must be an integer")
+ raise TypeError("y must be an integer.")
self._modulus = modulus
self._subgroup_order = subgroup_order
@@ -163,7 +237,7 @@ class DSAPublicKey(object):
def verifier(self, signature, algorithm, backend):
if not isinstance(backend, DSABackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement DSABackend",
+ "Backend object does not implement DSABackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
@@ -181,3 +255,83 @@ class DSAPublicKey(object):
def parameters(self):
return DSAParameters(self._modulus, self._subgroup_order,
self._generator)
+
+
+class DSAParameterNumbers(object):
+ def __init__(self, p, q, g):
+ if (
+ not isinstance(p, six.integer_types) or
+ not isinstance(q, six.integer_types) or
+ not isinstance(g, six.integer_types)
+ ):
+ raise TypeError(
+ "DSAParameterNumbers p, q, and g arguments must be integers."
+ )
+
+ self._p = p
+ self._q = q
+ self._g = g
+
+ @property
+ def p(self):
+ return self._p
+
+ @property
+ def q(self):
+ return self._q
+
+ @property
+ def g(self):
+ return self._g
+
+ def parameters(self, backend):
+ return backend.load_dsa_parameter_numbers(self)
+
+
+class DSAPublicNumbers(object):
+ def __init__(self, y, parameter_numbers):
+ if not isinstance(y, six.integer_types):
+ raise TypeError("DSAPublicNumbers y argument must be an integer.")
+
+ if not isinstance(parameter_numbers, DSAParameterNumbers):
+ raise TypeError(
+ "parameter_numbers must be a DSAParameterNumbers instance."
+ )
+
+ self._y = y
+ self._parameter_numbers = parameter_numbers
+
+ @property
+ def y(self):
+ return self._y
+
+ @property
+ def parameter_numbers(self):
+ return self._parameter_numbers
+
+ def public_key(self, backend):
+ return backend.load_dsa_public_numbers(self)
+
+
+class DSAPrivateNumbers(object):
+ def __init__(self, x, public_numbers):
+ if not isinstance(x, six.integer_types):
+ raise TypeError("DSAPrivateNumbers x argument must be an integer.")
+
+ if not isinstance(public_numbers, DSAPublicNumbers):
+ raise TypeError(
+ "public_numbers must be a DSAPublicNumbers instance."
+ )
+ self._public_numbers = public_numbers
+ self._x = x
+
+ @property
+ def x(self):
+ return self._x
+
+ @property
+ def public_numbers(self):
+ return self._public_numbers
+
+ def private_key(self, backend):
+ return backend.load_dsa_private_numbers(self)
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py
new file mode 100644
index 0000000..220a419
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py
@@ -0,0 +1,255 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+import six
+
+from cryptography import utils
+from cryptography.hazmat.primitives import interfaces
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECT571R1(object):
+ @property
+ def name(self):
+ return "sect571r1"
+
+ @property
+ def key_size(self):
+ return 571
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECT409R1(object):
+ @property
+ def name(self):
+ return "sect409r1"
+
+ @property
+ def key_size(self):
+ return 409
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECT283R1(object):
+ @property
+ def name(self):
+ return "sect283r1"
+
+ @property
+ def key_size(self):
+ return 283
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECT233R1(object):
+ @property
+ def name(self):
+ return "sect233r1"
+
+ @property
+ def key_size(self):
+ return 233
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECT163R2(object):
+ @property
+ def name(self):
+ return "sect163r2"
+
+ @property
+ def key_size(self):
+ return 163
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECT571K1(object):
+ @property
+ def name(self):
+ return "sect571k1"
+
+ @property
+ def key_size(self):
+ return 571
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECT409K1(object):
+ @property
+ def name(self):
+ return "sect409k1"
+
+ @property
+ def key_size(self):
+ return 409
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECT283K1(object):
+ @property
+ def name(self):
+ return "sect283k1"
+
+ @property
+ def key_size(self):
+ return 283
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECT233K1(object):
+ @property
+ def name(self):
+ return "sect233k1"
+
+ @property
+ def key_size(self):
+ return 233
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECT163K1(object):
+ @property
+ def name(self):
+ return "sect163k1"
+
+ @property
+ def key_size(self):
+ return 163
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECP521R1(object):
+ @property
+ def name(self):
+ return "secp521r1"
+
+ @property
+ def key_size(self):
+ return 521
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECP384R1(object):
+ @property
+ def name(self):
+ return "secp384r1"
+
+ @property
+ def key_size(self):
+ return 384
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECP256R1(object):
+ @property
+ def name(self):
+ return "secp256r1"
+
+ @property
+ def key_size(self):
+ return 256
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECP224R1(object):
+ @property
+ def name(self):
+ return "secp224r1"
+
+ @property
+ def key_size(self):
+ return 224
+
+
+@utils.register_interface(interfaces.EllipticCurve)
+class SECP192R1(object):
+ @property
+ def name(self):
+ return "secp192r1"
+
+ @property
+ def key_size(self):
+ return 192
+
+
+@utils.register_interface(interfaces.EllipticCurveSignatureAlgorithm)
+class ECDSA(object):
+ def __init__(self, algorithm):
+ self._algorithm = algorithm
+
+ @property
+ def algorithm(self):
+ return self._algorithm
+
+
+def generate_private_key(curve, backend):
+ return backend.generate_elliptic_curve_private_key(curve)
+
+
+class EllipticCurvePublicNumbers(object):
+ def __init__(self, x, y, curve):
+ if (
+ not isinstance(x, six.integer_types) or
+ not isinstance(y, six.integer_types)
+ ):
+ raise TypeError("x and y must be integers.")
+
+ if not isinstance(curve, interfaces.EllipticCurve):
+ raise TypeError("curve must provide the EllipticCurve interface.")
+
+ self._y = y
+ self._x = x
+ self._curve = curve
+
+ def public_key(self, backend):
+ return backend.elliptic_curve_public_key_from_numbers(self)
+
+ @property
+ def curve(self):
+ return self._curve
+
+ @property
+ def x(self):
+ return self._x
+
+ @property
+ def y(self):
+ return self._y
+
+
+class EllipticCurvePrivateNumbers(object):
+ def __init__(self, private_value, public_numbers):
+ if not isinstance(private_value, six.integer_types):
+ raise TypeError("private_value must be an integer.")
+
+ if not isinstance(public_numbers, EllipticCurvePublicNumbers):
+ raise TypeError(
+ "public_numbers must be an EllipticCurvePublicNumbers "
+ "instance."
+ )
+
+ self._private_value = private_value
+ self._public_numbers = public_numbers
+
+ def private_key(self, backend):
+ return backend.elliptic_curve_private_key_from_numbers(self)
+
+ @property
+ def private_value(self):
+ return self._private_value
+
+ @property
+ def public_numbers(self):
+ return self._public_numbers
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py
index dcc6fe0..d44bbda 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py
@@ -38,18 +38,19 @@ class PSS(object):
warnings.warn(
"salt_length is deprecated on MGF1 and should be added via the"
" PSS constructor.",
- utils.DeprecatedIn04
+ utils.DeprecatedIn04,
+ stacklevel=2
)
else:
if (not isinstance(salt_length, six.integer_types) and
salt_length is not self.MAX_LENGTH):
- raise TypeError("salt_length must be an integer")
+ raise TypeError("salt_length must be an integer.")
if salt_length is not self.MAX_LENGTH and salt_length < 0:
- raise ValueError("salt_length must be zero or greater")
+ raise ValueError("salt_length must be zero or greater.")
if salt_length is None and self._mgf._salt_length is None:
- raise ValueError("You must supply salt_length")
+ raise ValueError("You must supply salt_length.")
self._salt_length = salt_length
@@ -80,13 +81,14 @@ class MGF1(object):
warnings.warn(
"salt_length is deprecated on MGF1 and should be passed to "
"the PSS constructor instead.",
- utils.DeprecatedIn04
+ utils.DeprecatedIn04,
+ stacklevel=2
)
if (not isinstance(salt_length, six.integer_types) and
salt_length is not self.MAX_LENGTH):
- raise TypeError("salt_length must be an integer")
+ raise TypeError("salt_length must be an integer.")
if salt_length is not self.MAX_LENGTH and salt_length < 0:
- raise ValueError("salt_length must be zero or greater")
+ raise ValueError("salt_length must be zero or greater.")
self._salt_length = salt_length
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py
index 5d3bb36..15ec52a 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py
@@ -13,31 +13,102 @@
from __future__ import absolute_import, division, print_function
+import warnings
+
import six
from cryptography import utils
from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
from cryptography.hazmat.backends.interfaces import RSABackend
-from cryptography.hazmat.primitives import interfaces
-@utils.register_interface(interfaces.RSAPublicKey)
+def generate_private_key(public_exponent, key_size, backend):
+ if not isinstance(backend, RSABackend):
+ raise UnsupportedAlgorithm(
+ "Backend object does not implement RSABackend.",
+ _Reasons.BACKEND_MISSING_INTERFACE
+ )
+
+ _verify_rsa_parameters(public_exponent, key_size)
+ return backend.generate_rsa_private_key(public_exponent, key_size)
+
+
+def _verify_rsa_parameters(public_exponent, key_size):
+ if public_exponent < 3:
+ raise ValueError("public_exponent must be >= 3.")
+
+ if public_exponent & 1 == 0:
+ raise ValueError("public_exponent must be odd.")
+
+ if key_size < 512:
+ raise ValueError("key_size must be at least 512-bits.")
+
+
+def _check_private_key_components(p, q, private_exponent, dmp1, dmq1, iqmp,
+ public_exponent, modulus):
+ if modulus < 3:
+ raise ValueError("modulus must be >= 3.")
+
+ if p >= modulus:
+ raise ValueError("p must be < modulus.")
+
+ if q >= modulus:
+ raise ValueError("q must be < modulus.")
+
+ if dmp1 >= modulus:
+ raise ValueError("dmp1 must be < modulus.")
+
+ if dmq1 >= modulus:
+ raise ValueError("dmq1 must be < modulus.")
+
+ if iqmp >= modulus:
+ raise ValueError("iqmp must be < modulus.")
+
+ if private_exponent >= modulus:
+ raise ValueError("private_exponent must be < modulus.")
+
+ if public_exponent < 3 or public_exponent >= modulus:
+ raise ValueError("public_exponent must be >= 3 and < modulus.")
+
+ if public_exponent & 1 == 0:
+ raise ValueError("public_exponent must be odd.")
+
+ if dmp1 & 1 == 0:
+ raise ValueError("dmp1 must be odd.")
+
+ if dmq1 & 1 == 0:
+ raise ValueError("dmq1 must be odd.")
+
+ if p * q != modulus:
+ raise ValueError("p*q must equal modulus.")
+
+
+def _check_public_key_components(e, n):
+ if n < 3:
+ raise ValueError("n must be >= 3.")
+
+ if e < 3 or e >= n:
+ raise ValueError("e must be >= 3 and < n.")
+
+ if e & 1 == 0:
+ raise ValueError("e must be odd.")
+
+
class RSAPublicKey(object):
def __init__(self, public_exponent, modulus):
+ warnings.warn(
+ "The RSAPublicKey class is deprecated and will be removed in a "
+ "future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
if (
not isinstance(public_exponent, six.integer_types) or
not isinstance(modulus, six.integer_types)
):
- raise TypeError("RSAPublicKey arguments must be integers")
+ raise TypeError("RSAPublicKey arguments must be integers.")
- if modulus < 3:
- raise ValueError("modulus must be >= 3")
-
- if public_exponent < 3 or public_exponent >= modulus:
- raise ValueError("public_exponent must be >= 3 and < modulus")
-
- if public_exponent & 1 == 0:
- raise ValueError("public_exponent must be odd")
+ _check_public_key_components(public_exponent, modulus)
self._public_exponent = public_exponent
self._modulus = modulus
@@ -45,7 +116,7 @@ class RSAPublicKey(object):
def verifier(self, signature, padding, algorithm, backend):
if not isinstance(backend, RSABackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement RSABackend",
+ "Backend object does not implement RSABackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
@@ -55,7 +126,7 @@ class RSAPublicKey(object):
def encrypt(self, plaintext, padding, backend):
if not isinstance(backend, RSABackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement RSABackend",
+ "Backend object does not implement RSABackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
@@ -118,10 +189,15 @@ def rsa_crt_dmq1(private_exponent, q):
return private_exponent % (q - 1)
-@utils.register_interface(interfaces.RSAPrivateKey)
class RSAPrivateKey(object):
def __init__(self, p, q, private_exponent, dmp1, dmq1, iqmp,
public_exponent, modulus):
+ warnings.warn(
+ "The RSAPrivateKey class is deprecated and will be removed in a "
+ "future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
if (
not isinstance(p, six.integer_types) or
not isinstance(q, six.integer_types) or
@@ -132,43 +208,10 @@ class RSAPrivateKey(object):
not isinstance(public_exponent, six.integer_types) or
not isinstance(modulus, six.integer_types)
):
- raise TypeError("RSAPrivateKey arguments must be integers")
+ raise TypeError("RSAPrivateKey arguments must be integers.")
- if modulus < 3:
- raise ValueError("modulus must be >= 3")
-
- if p >= modulus:
- raise ValueError("p must be < modulus")
-
- if q >= modulus:
- raise ValueError("q must be < modulus")
-
- if dmp1 >= modulus:
- raise ValueError("dmp1 must be < modulus")
-
- if dmq1 >= modulus:
- raise ValueError("dmq1 must be < modulus")
-
- if iqmp >= modulus:
- raise ValueError("iqmp must be < modulus")
-
- if private_exponent >= modulus:
- raise ValueError("private_exponent must be < modulus")
-
- if public_exponent < 3 or public_exponent >= modulus:
- raise ValueError("public_exponent must be >= 3 and < modulus")
-
- if public_exponent & 1 == 0:
- raise ValueError("public_exponent must be odd")
-
- if dmp1 & 1 == 0:
- raise ValueError("dmp1 must be odd")
-
- if dmq1 & 1 == 0:
- raise ValueError("dmq1 must be odd")
-
- if p * q != modulus:
- raise ValueError("p*q must equal modulus")
+ _check_private_key_components(p, q, private_exponent, dmp1, dmq1, iqmp,
+ public_exponent, modulus)
self._p = p
self._q = q
@@ -181,18 +224,35 @@ class RSAPrivateKey(object):
@classmethod
def generate(cls, public_exponent, key_size, backend):
+ warnings.warn(
+ "generate is deprecated and will be removed in a future version.",
+ utils.DeprecatedIn05,
+ stacklevel=2
+ )
if not isinstance(backend, RSABackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement RSABackend",
+ "Backend object does not implement RSABackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
- return backend.generate_rsa_private_key(public_exponent, key_size)
+ _verify_rsa_parameters(public_exponent, key_size)
+ key = backend.generate_rsa_private_key(public_exponent, key_size)
+ private_numbers = key.private_numbers()
+ return RSAPrivateKey(
+ p=private_numbers.p,
+ q=private_numbers.q,
+ dmp1=private_numbers.dmp1,
+ dmq1=private_numbers.dmq1,
+ iqmp=private_numbers.iqmp,
+ private_exponent=private_numbers.d,
+ public_exponent=private_numbers.public_numbers.e,
+ modulus=private_numbers.public_numbers.n
+ )
def signer(self, padding, algorithm, backend):
if not isinstance(backend, RSABackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement RSABackend",
+ "Backend object does not implement RSABackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
@@ -201,7 +261,7 @@ class RSAPrivateKey(object):
def decrypt(self, ciphertext, padding, backend):
if not isinstance(backend, RSABackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement RSABackend",
+ "Backend object does not implement RSABackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
@@ -257,3 +317,88 @@ class RSAPrivateKey(object):
@property
def n(self):
return self.modulus
+
+
+class RSAPrivateNumbers(object):
+ def __init__(self, p, q, d, dmp1, dmq1, iqmp,
+ public_numbers):
+ if (
+ not isinstance(p, six.integer_types) or
+ not isinstance(q, six.integer_types) or
+ not isinstance(d, six.integer_types) or
+ not isinstance(dmp1, six.integer_types) or
+ not isinstance(dmq1, six.integer_types) or
+ not isinstance(iqmp, six.integer_types)
+ ):
+ raise TypeError(
+ "RSAPrivateNumbers p, q, d, dmp1, dmq1, iqmp arguments must"
+ " all be an integers."
+ )
+
+ if not isinstance(public_numbers, RSAPublicNumbers):
+ raise TypeError(
+ "RSAPrivateNumbers public_numbers must be an RSAPublicNumbers"
+ " instance."
+ )
+
+ self._p = p
+ self._q = q
+ self._d = d
+ self._dmp1 = dmp1
+ self._dmq1 = dmq1
+ self._iqmp = iqmp
+ self._public_numbers = public_numbers
+
+ @property
+ def p(self):
+ return self._p
+
+ @property
+ def q(self):
+ return self._q
+
+ @property
+ def d(self):
+ return self._d
+
+ @property
+ def dmp1(self):
+ return self._dmp1
+
+ @property
+ def dmq1(self):
+ return self._dmq1
+
+ @property
+ def iqmp(self):
+ return self._iqmp
+
+ @property
+ def public_numbers(self):
+ return self._public_numbers
+
+ def private_key(self, backend):
+ return backend.load_rsa_private_numbers(self)
+
+
+class RSAPublicNumbers(object):
+ def __init__(self, e, n):
+ if (
+ not isinstance(e, six.integer_types) or
+ not isinstance(n, six.integer_types)
+ ):
+ raise TypeError("RSAPublicNumbers arguments must be integers.")
+
+ self._e = e
+ self._n = n
+
+ @property
+ def e(self):
+ return self._e
+
+ @property
+ def n(self):
+ return self._n
+
+ def public_key(self, backend):
+ return backend.load_rsa_public_numbers(self)
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py
index 52daf17..bd8437c 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py
@@ -20,7 +20,7 @@ from cryptography.hazmat.primitives import interfaces
def _verify_key_size(algorithm, key):
# Verify that the key size matches the expected key size
if len(key) * 8 not in algorithm.key_sizes:
- raise ValueError("Invalid key size ({0}) for {1}".format(
+ raise ValueError("Invalid key size ({0}) for {1}.".format(
len(key) * 8, algorithm.name
))
return key
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/base.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/base.py
index 2274e94..e3fe5ad 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/base.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/base.py
@@ -26,12 +26,14 @@ class Cipher(object):
def __init__(self, algorithm, mode, backend):
if not isinstance(backend, CipherBackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement CipherBackend",
+ "Backend object does not implement CipherBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
if not isinstance(algorithm, interfaces.CipherAlgorithm):
- raise TypeError("Expected interface of interfaces.CipherAlgorithm")
+ raise TypeError(
+ "Expected interface of interfaces.CipherAlgorithm."
+ )
if mode is not None:
mode.validate_for_algorithm(algorithm)
@@ -44,7 +46,7 @@ class Cipher(object):
if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):
if self.mode.tag is not None:
raise ValueError(
- "Authentication tag must be None when encrypting"
+ "Authentication tag must be None when encrypting."
)
ctx = self._backend.create_symmetric_encryption_ctx(
self.algorithm, self.mode
@@ -55,7 +57,7 @@ class Cipher(object):
if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):
if self.mode.tag is None:
raise ValueError(
- "Authentication tag must be provided when decrypting"
+ "Authentication tag must be provided when decrypting."
)
ctx = self._backend.create_symmetric_decryption_ctx(
self.algorithm, self.mode
@@ -79,12 +81,12 @@ class _CipherContext(object):
def update(self, data):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
return self._ctx.update(data)
def finalize(self):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
data = self._ctx.finalize()
self._ctx = None
return data
@@ -100,13 +102,13 @@ class _AEADCipherContext(object):
def update(self, data):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
self._updated = True
return self._ctx.update(data)
def finalize(self):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
data = self._ctx.finalize()
self._tag = self._ctx.tag
self._ctx = None
@@ -114,9 +116,9 @@ class _AEADCipherContext(object):
def authenticate_additional_data(self, data):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
if self._updated:
- raise AlreadyUpdated("Update has been called on this context")
+ raise AlreadyUpdated("Update has been called on this context.")
self._ctx.authenticate_additional_data(data)
@@ -126,5 +128,5 @@ class _AEADEncryptionContext(_AEADCipherContext):
def tag(self):
if self._ctx is not None:
raise NotYetFinalized("You must finalize encryption before "
- "getting the tag")
+ "getting the tag.")
return self._tag
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/modes.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/modes.py
index 739f23d..509b4de 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/modes.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/ciphers/modes.py
@@ -17,6 +17,13 @@ from cryptography import utils
from cryptography.hazmat.primitives import interfaces
+def _check_iv_length(mode, algorithm):
+ if len(mode.initialization_vector) * 8 != algorithm.block_size:
+ raise ValueError("Invalid IV size ({0}) for {1}.".format(
+ len(mode.initialization_vector), mode.name
+ ))
+
+
@utils.register_interface(interfaces.Mode)
@utils.register_interface(interfaces.ModeWithInitializationVector)
class CBC(object):
@@ -25,11 +32,7 @@ class CBC(object):
def __init__(self, initialization_vector):
self.initialization_vector = initialization_vector
- def validate_for_algorithm(self, algorithm):
- if len(self.initialization_vector) * 8 != algorithm.block_size:
- raise ValueError("Invalid iv size ({0}) for {1}".format(
- len(self.initialization_vector), self.name
- ))
+ validate_for_algorithm = _check_iv_length
@utils.register_interface(interfaces.Mode)
@@ -48,11 +51,7 @@ class OFB(object):
def __init__(self, initialization_vector):
self.initialization_vector = initialization_vector
- def validate_for_algorithm(self, algorithm):
- if len(self.initialization_vector) * 8 != algorithm.block_size:
- raise ValueError("Invalid iv size ({0}) for {1}".format(
- len(self.initialization_vector), self.name
- ))
+ validate_for_algorithm = _check_iv_length
@utils.register_interface(interfaces.Mode)
@@ -63,11 +62,18 @@ class CFB(object):
def __init__(self, initialization_vector):
self.initialization_vector = initialization_vector
- def validate_for_algorithm(self, algorithm):
- if len(self.initialization_vector) * 8 != algorithm.block_size:
- raise ValueError("Invalid iv size ({0}) for {1}".format(
- len(self.initialization_vector), self.name
- ))
+ validate_for_algorithm = _check_iv_length
+
+
+@utils.register_interface(interfaces.Mode)
+@utils.register_interface(interfaces.ModeWithInitializationVector)
+class CFB8(object):
+ name = "CFB8"
+
+ def __init__(self, initialization_vector):
+ self.initialization_vector = initialization_vector
+
+ validate_for_algorithm = _check_iv_length
@utils.register_interface(interfaces.Mode)
@@ -80,7 +86,7 @@ class CTR(object):
def validate_for_algorithm(self, algorithm):
if len(self.nonce) * 8 != algorithm.block_size:
- raise ValueError("Invalid nonce size ({0}) for {1}".format(
+ raise ValueError("Invalid nonce size ({0}) for {1}.".format(
len(self.nonce), self.name
))
@@ -91,13 +97,16 @@ class CTR(object):
class GCM(object):
name = "GCM"
- def __init__(self, initialization_vector, tag=None):
+ def __init__(self, initialization_vector, tag=None, min_tag_length=16):
# len(initialization_vector) must in [1, 2 ** 64), but it's impossible
# to actually construct a bytes object that large, so we don't check
# for it
- if tag is not None and len(tag) < 4:
+ if min_tag_length < 4:
+ raise ValueError("min_tag_length must be >= 4")
+ if tag is not None and len(tag) < min_tag_length:
raise ValueError(
- "Authentication tag must be 4 bytes or longer"
+ "Authentication tag must be {0} bytes or longer.".format(
+ min_tag_length)
)
self.initialization_vector = initialization_vector
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/cmac.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/cmac.py
index 7e7f65a..fa463ae 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/cmac.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/cmac.py
@@ -13,8 +13,6 @@
from __future__ import absolute_import, division, print_function
-import six
-
from cryptography import utils
from cryptography.exceptions import (
AlreadyFinalized, InvalidSignature, UnsupportedAlgorithm, _Reasons
@@ -28,13 +26,13 @@ class CMAC(object):
def __init__(self, algorithm, backend, ctx=None):
if not isinstance(backend, CMACBackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement CMACBackend",
+ "Backend object does not implement CMACBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
if not isinstance(algorithm, interfaces.BlockCipherAlgorithm):
raise TypeError(
- "Expected instance of interfaces.BlockCipherAlgorithm"
+ "Expected instance of interfaces.BlockCipherAlgorithm."
)
self._algorithm = algorithm
@@ -46,28 +44,28 @@ class CMAC(object):
def update(self, data):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
- if isinstance(data, six.text_type):
- raise TypeError("Unicode-objects must be encoded before hashing")
+ raise AlreadyFinalized("Context was already finalized.")
+ if not isinstance(data, bytes):
+ raise TypeError("data must be bytes.")
self._ctx.update(data)
def finalize(self):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
digest = self._ctx.finalize()
self._ctx = None
return digest
def verify(self, signature):
- if isinstance(signature, six.text_type):
- raise TypeError("Unicode-objects must be encoded before verifying")
+ if not isinstance(signature, bytes):
+ raise TypeError("signature must be bytes.")
digest = self.finalize()
if not constant_time.bytes_eq(digest, signature):
raise InvalidSignature("Signature did not match digest.")
def copy(self):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
return CMAC(
self._algorithm,
backend=self._backend,
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/constant_time.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/constant_time.py
index e0e9aa3..9789851 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/constant_time.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/constant_time.py
@@ -13,12 +13,11 @@
from __future__ import absolute_import, division, print_function
+import hmac
import sys
import cffi
-import six
-
from cryptography.hazmat.bindings.utils import _create_modulename
TYPES = """
@@ -55,9 +54,18 @@ _lib = _ffi.verify(
ext_package="cryptography",
)
+if hasattr(hmac, "compare_digest"):
+ def bytes_eq(a, b):
+ if not isinstance(a, bytes) or not isinstance(b, bytes):
+ raise TypeError("a and b must be bytes.")
-def bytes_eq(a, b):
- if isinstance(a, six.text_type) or isinstance(b, six.text_type):
- raise TypeError("Unicode-objects must be encoded before comparing")
+ return hmac.compare_digest(a, b)
- return _lib.Cryptography_constant_time_bytes_eq(a, len(a), b, len(b)) == 1
+else:
+ def bytes_eq(a, b):
+ if not isinstance(a, bytes) or not isinstance(b, bytes):
+ raise TypeError("a and b must be bytes.")
+
+ return _lib.Cryptography_constant_time_bytes_eq(
+ a, len(a), b, len(b)
+ ) == 1
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/hashes.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/hashes.py
index 35b677b..04f7620 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/hashes.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/hashes.py
@@ -13,8 +13,6 @@
from __future__ import absolute_import, division, print_function
-import six
-
from cryptography import utils
from cryptography.exceptions import (
AlreadyFinalized, UnsupportedAlgorithm, _Reasons
@@ -28,7 +26,7 @@ class Hash(object):
def __init__(self, algorithm, backend, ctx=None):
if not isinstance(backend, HashBackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement HashBackend",
+ "Backend object does not implement HashBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
@@ -45,21 +43,21 @@ class Hash(object):
def update(self, data):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
- if isinstance(data, six.text_type):
- raise TypeError("Unicode-objects must be encoded before hashing")
+ raise AlreadyFinalized("Context was already finalized.")
+ if not isinstance(data, bytes):
+ raise TypeError("data must be bytes.")
self._ctx.update(data)
def copy(self):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
return Hash(
self.algorithm, backend=self._backend, ctx=self._ctx.copy()
)
def finalize(self):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
digest = self._ctx.finalize()
self._ctx = None
return digest
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/hmac.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/hmac.py
index afbb2f7..026ad3b 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/hmac.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/hmac.py
@@ -13,8 +13,6 @@
from __future__ import absolute_import, division, print_function
-import six
-
from cryptography import utils
from cryptography.exceptions import (
AlreadyFinalized, InvalidSignature, UnsupportedAlgorithm, _Reasons
@@ -28,7 +26,7 @@ class HMAC(object):
def __init__(self, key, algorithm, backend, ctx=None):
if not isinstance(backend, HMACBackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement HMACBackend",
+ "Backend object does not implement HMACBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
@@ -45,14 +43,14 @@ class HMAC(object):
def update(self, msg):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
- if isinstance(msg, six.text_type):
- raise TypeError("Unicode-objects must be encoded before hashing")
+ raise AlreadyFinalized("Context was already finalized.")
+ if not isinstance(msg, bytes):
+ raise TypeError("msg must be bytes.")
self._ctx.update(msg)
def copy(self):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
return HMAC(
self._key,
self.algorithm,
@@ -62,14 +60,14 @@ class HMAC(object):
def finalize(self):
if self._ctx is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
digest = self._ctx.finalize()
self._ctx = None
return digest
def verify(self, signature):
- if isinstance(signature, six.text_type):
- raise TypeError("Unicode-objects must be encoded before verifying")
+ if not isinstance(signature, bytes):
+ raise TypeError("signature must be bytes.")
digest = self.finalize()
if not constant_time.bytes_eq(digest, signature):
raise InvalidSignature("Signature did not match digest.")
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/interfaces.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/interfaces.py
index 810a67a..d60f9e0 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/interfaces.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/interfaces.py
@@ -186,27 +186,15 @@ class HashContext(object):
@six.add_metaclass(abc.ABCMeta)
class RSAPrivateKey(object):
@abc.abstractmethod
- def signer(self, padding, algorithm, backend):
+ def signer(self, padding, algorithm):
"""
Returns an AsymmetricSignatureContext used for signing data.
"""
- @abc.abstractproperty
- def modulus(self):
+ @abc.abstractmethod
+ def decrypt(self, ciphertext, padding):
"""
- The public modulus of the RSA key.
- """
-
- @abc.abstractproperty
- def public_exponent(self):
- """
- The public exponent of the RSA key.
- """
-
- @abc.abstractproperty
- def private_exponent(self):
- """
- The private exponent of the RSA key.
+ Decrypts the provided ciphertext.
"""
@abc.abstractproperty
@@ -221,77 +209,28 @@ class RSAPrivateKey(object):
The RSAPublicKey associated with this private key.
"""
- @abc.abstractproperty
- def n(self):
- """
- The public modulus of the RSA key. Alias for modulus.
- """
- @abc.abstractproperty
- def p(self):
+@six.add_metaclass(abc.ABCMeta)
+class RSAPrivateKeyWithNumbers(RSAPrivateKey):
+ @abc.abstractmethod
+ def private_numbers(self):
"""
- One of the two primes used to generate d.
- """
-
- @abc.abstractproperty
- def q(self):
- """
- One of the two primes used to generate d.
- """
-
- @abc.abstractproperty
- def d(self):
- """
- The private exponent. This can be calculated using p and q. Alias for
- private_exponent.
- """
-
- @abc.abstractproperty
- def dmp1(self):
- """
- A Chinese remainder theorem coefficient used to speed up RSA
- calculations. Calculated as: d mod (p-1)
- """
-
- @abc.abstractproperty
- def dmq1(self):
- """
- A Chinese remainder theorem coefficient used to speed up RSA
- calculations. Calculated as: d mod (q-1)
- """
-
- @abc.abstractproperty
- def iqmp(self):
- """
- A Chinese remainder theorem coefficient used to speed up RSA
- calculations. The modular inverse of q modulo p
- """
-
- @abc.abstractproperty
- def e(self):
- """
- The public exponent of the RSA key. Alias for public_exponent.
+ Returns an RSAPrivateNumbers.
"""
@six.add_metaclass(abc.ABCMeta)
class RSAPublicKey(object):
@abc.abstractmethod
- def verifier(self, signature, padding, algorithm, backend):
+ def verifier(self, signature, padding, algorithm):
"""
Returns an AsymmetricVerificationContext used for verifying signatures.
"""
- @abc.abstractproperty
- def modulus(self):
+ @abc.abstractmethod
+ def encrypt(self, plaintext, padding):
"""
- The public modulus of the RSA key.
- """
-
- @abc.abstractproperty
- def public_exponent(self):
- """
- The public exponent of the RSA key.
+ Encrypts the given plaintext.
"""
@abc.abstractproperty
@@ -300,63 +239,31 @@ class RSAPublicKey(object):
The bit length of the public modulus.
"""
- @abc.abstractproperty
- def n(self):
- """
- The public modulus of the RSA key. Alias for modulus.
- """
- @abc.abstractproperty
- def e(self):
+@six.add_metaclass(abc.ABCMeta)
+class RSAPublicKeyWithNumbers(RSAPublicKey):
+ @abc.abstractmethod
+ def public_numbers(self):
"""
- The public exponent of the RSA key. Alias for public_exponent.
+ Returns an RSAPublicNumbers
"""
@six.add_metaclass(abc.ABCMeta)
class DSAParameters(object):
- @abc.abstractproperty
- def modulus(self):
+ @abc.abstractmethod
+ def generate_private_key(self):
"""
- The prime modulus that's used in generating the DSA keypair and used
- in the DSA signing and verification processes.
+ Generates and returns a DSAPrivateKey.
"""
- @abc.abstractproperty
- def subgroup_order(self):
- """
- The subgroup order that's used in generating the DSA keypair
- by the generator and used in the DSA signing and verification
- processes.
- """
- @abc.abstractproperty
- def generator(self):
+@six.add_metaclass(abc.ABCMeta)
+class DSAParametersWithNumbers(DSAParameters):
+ @abc.abstractmethod
+ def parameter_numbers(self):
"""
- The generator that is used in generating the DSA keypair and used
- in the DSA signing and verification processes.
- """
-
- @abc.abstractproperty
- def p(self):
- """
- The prime modulus that's used in generating the DSA keypair and used
- in the DSA signing and verification processes. Alias for modulus.
- """
-
- @abc.abstractproperty
- def q(self):
- """
- The subgroup order that's used in generating the DSA keypair
- by the generator and used in the DSA signing and verification
- processes. Alias for subgroup_order.
- """
-
- @abc.abstractproperty
- def g(self):
- """
- The generator that is used in generating the DSA keypair and used
- in the DSA signing and verification processes. Alias for generator.
+ Returns a DSAParameterNumbers.
"""
@@ -374,18 +281,6 @@ class DSAPrivateKey(object):
The DSAPublicKey associated with this private key.
"""
- @abc.abstractproperty
- def x(self):
- """
- The private key "x" in the DSA structure.
- """
-
- @abc.abstractproperty
- def y(self):
- """
- The public key.
- """
-
@abc.abstractmethod
def parameters(self):
"""
@@ -393,6 +288,15 @@ class DSAPrivateKey(object):
"""
+@six.add_metaclass(abc.ABCMeta)
+class DSAPrivateKeyWithNumbers(DSAPrivateKey):
+ @abc.abstractmethod
+ def private_numbers(self):
+ """
+ Returns a DSAPrivateNumbers.
+ """
+
+
@six.add_metaclass(abc.ABCMeta)
class DSAPublicKey(object):
@abc.abstractproperty
@@ -401,12 +305,6 @@ class DSAPublicKey(object):
The bit length of the prime modulus.
"""
- @abc.abstractproperty
- def y(self):
- """
- The public key.
- """
-
@abc.abstractmethod
def parameters(self):
"""
@@ -414,6 +312,15 @@ class DSAPublicKey(object):
"""
+@six.add_metaclass(abc.ABCMeta)
+class DSAPublicKeyWithNumbers(DSAPublicKey):
+ @abc.abstractmethod
+ def public_numbers(self):
+ """
+ Returns a DSAPublicNumbers.
+ """
+
+
@six.add_metaclass(abc.ABCMeta)
class AsymmetricSignatureContext(object):
@abc.abstractmethod
@@ -489,3 +396,63 @@ class CMACContext(object):
"""
Return a CMACContext that is a copy of the current context.
"""
+
+
+@six.add_metaclass(abc.ABCMeta)
+class EllipticCurve(object):
+ @abc.abstractproperty
+ def name(self):
+ """
+ The name of the curve. e.g. secp256r1.
+ """
+
+ @abc.abstractproperty
+ def key_size(self):
+ """
+ The bit length of the base point of the curve.
+ """
+
+
+@six.add_metaclass(abc.ABCMeta)
+class EllipticCurveSignatureAlgorithm(object):
+ @abc.abstractproperty
+ def algorithm(self):
+ """
+ The digest algorithm used with this signature.
+ """
+
+
+@six.add_metaclass(abc.ABCMeta)
+class EllipticCurvePrivateKey(object):
+ @abc.abstractmethod
+ def signer(self, signature_algorithm):
+ """
+ Returns an AsymmetricSignatureContext used for signing data.
+ """
+
+ @abc.abstractmethod
+ def public_key(self):
+ """
+ The EllipticCurvePublicKey for this private key.
+ """
+
+ @abc.abstractproperty
+ def curve(self):
+ """
+ The EllipticCurve that this key is on.
+ """
+
+
+@six.add_metaclass(abc.ABCMeta)
+class EllipticCurvePublicKey(object):
+ @abc.abstractmethod
+ def verifier(self, signature, signature_algorithm):
+ """
+ Returns an AsymmetricVerificationContext used for signing data.
+ """
+
+ @abc.abstractproperty
+ def curve(self):
+ """
+ The EllipticCurve that this key is on.
+ """
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py
index 03500aa..04d02b2 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py
@@ -28,12 +28,53 @@ class HKDF(object):
def __init__(self, algorithm, length, salt, info, backend):
if not isinstance(backend, HMACBackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement HMACBackend",
+ "Backend object does not implement HMACBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
self._algorithm = algorithm
+ if not isinstance(salt, bytes) and salt is not None:
+ raise TypeError("salt must be bytes.")
+
+ if salt is None:
+ salt = b"\x00" * (self._algorithm.digest_size // 8)
+
+ self._salt = salt
+
+ self._backend = backend
+
+ self._hkdf_expand = HKDFExpand(self._algorithm, length, info, backend)
+
+ def _extract(self, key_material):
+ h = hmac.HMAC(self._salt, self._algorithm, backend=self._backend)
+ h.update(key_material)
+ return h.finalize()
+
+ def derive(self, key_material):
+ if not isinstance(key_material, bytes):
+ raise TypeError("key_material must be bytes.")
+
+ return self._hkdf_expand.derive(self._extract(key_material))
+
+ def verify(self, key_material, expected_key):
+ if not constant_time.bytes_eq(self.derive(key_material), expected_key):
+ raise InvalidKey
+
+
+@utils.register_interface(interfaces.KeyDerivationFunction)
+class HKDFExpand(object):
+ def __init__(self, algorithm, length, info, backend):
+ if not isinstance(backend, HMACBackend):
+ raise UnsupportedAlgorithm(
+ "Backend object does not implement HMACBackend.",
+ _Reasons.BACKEND_MISSING_INTERFACE
+ )
+
+ self._algorithm = algorithm
+
+ self._backend = backend
+
max_length = 255 * (algorithm.digest_size // 8)
if length > max_length:
@@ -44,32 +85,16 @@ class HKDF(object):
self._length = length
- if isinstance(salt, six.text_type):
- raise TypeError(
- "Unicode-objects must be encoded before using them as a salt.")
-
- if salt is None:
- salt = b"\x00" * (self._algorithm.digest_size // 8)
-
- self._salt = salt
-
- if isinstance(info, six.text_type):
- raise TypeError(
- "Unicode-objects must be encoded before using them as info.")
+ if not isinstance(info, bytes) and info is not None:
+ raise TypeError("info must be bytes.")
if info is None:
info = b""
self._info = info
- self._backend = backend
self._used = False
- def _extract(self, key_material):
- h = hmac.HMAC(self._salt, self._algorithm, backend=self._backend)
- h.update(key_material)
- return h.finalize()
-
def _expand(self, key_material):
output = [b""]
counter = 1
@@ -85,17 +110,14 @@ class HKDF(object):
return b"".join(output)[:self._length]
def derive(self, key_material):
- if isinstance(key_material, six.text_type):
- raise TypeError(
- "Unicode-objects must be encoded before using them as key "
- "material."
- )
+ if not isinstance(key_material, bytes):
+ raise TypeError("key_material must be bytes.")
if self._used:
raise AlreadyFinalized
self._used = True
- return self._expand(self._extract(key_material))
+ return self._expand(key_material)
def verify(self, key_material, expected_key):
if not constant_time.bytes_eq(self.derive(key_material), expected_key):
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py
index bec35bb..97b6408 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py
@@ -13,8 +13,6 @@
from __future__ import absolute_import, division, print_function
-import six
-
from cryptography import utils
from cryptography.exceptions import (
AlreadyFinalized, InvalidKey, UnsupportedAlgorithm, _Reasons
@@ -28,38 +26,32 @@ class PBKDF2HMAC(object):
def __init__(self, algorithm, length, salt, iterations, backend):
if not isinstance(backend, PBKDF2HMACBackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement PBKDF2HMACBackend",
+ "Backend object does not implement PBKDF2HMACBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
if not backend.pbkdf2_hmac_supported(algorithm):
raise UnsupportedAlgorithm(
- "{0} is not supported for PBKDF2 by this backend".format(
+ "{0} is not supported for PBKDF2 by this backend.".format(
algorithm.name),
_Reasons.UNSUPPORTED_HASH
)
self._used = False
self._algorithm = algorithm
self._length = length
- if isinstance(salt, six.text_type):
- raise TypeError(
- "Unicode-objects must be encoded before using them as key "
- "material."
- )
+ if not isinstance(salt, bytes):
+ raise TypeError("salt must be bytes.")
self._salt = salt
self._iterations = iterations
self._backend = backend
def derive(self, key_material):
if self._used:
- raise AlreadyFinalized("PBKDF2 instances can only be used once")
+ raise AlreadyFinalized("PBKDF2 instances can only be used once.")
self._used = True
- if isinstance(key_material, six.text_type):
- raise TypeError(
- "Unicode-objects must be encoded before using them as key "
- "material."
- )
+ if not isinstance(key_material, bytes):
+ raise TypeError("key_material must be bytes.")
return self._backend.derive_pbkdf2_hmac(
self._algorithm,
self._length,
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/padding.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/padding.py
index c1a763b..74f1ef2 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/padding.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/padding.py
@@ -79,10 +79,10 @@ _lib = _ffi.verify(
class PKCS7(object):
def __init__(self, block_size):
if not (0 <= block_size < 256):
- raise ValueError("block_size must be in range(0, 256)")
+ raise ValueError("block_size must be in range(0, 256).")
if block_size % 8 != 0:
- raise ValueError("block_size must be a multiple of 8")
+ raise ValueError("block_size must be a multiple of 8.")
self.block_size = block_size
@@ -102,10 +102,10 @@ class _PKCS7PaddingContext(object):
def update(self, data):
if self._buffer is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
- if isinstance(data, six.text_type):
- raise TypeError("Unicode-objects must be encoded before padding")
+ if not isinstance(data, bytes):
+ raise TypeError("data must be bytes.")
self._buffer += data
@@ -118,7 +118,7 @@ class _PKCS7PaddingContext(object):
def finalize(self):
if self._buffer is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
pad_size = self.block_size // 8 - len(self._buffer)
result = self._buffer + six.int2byte(pad_size) * pad_size
@@ -135,10 +135,10 @@ class _PKCS7UnpaddingContext(object):
def update(self, data):
if self._buffer is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
- if isinstance(data, six.text_type):
- raise TypeError("Unicode-objects must be encoded before unpadding")
+ if not isinstance(data, bytes):
+ raise TypeError("data must be bytes.")
self._buffer += data
@@ -154,17 +154,17 @@ class _PKCS7UnpaddingContext(object):
def finalize(self):
if self._buffer is None:
- raise AlreadyFinalized("Context was already finalized")
+ raise AlreadyFinalized("Context was already finalized.")
if len(self._buffer) != self.block_size // 8:
- raise ValueError("Invalid padding bytes")
+ raise ValueError("Invalid padding bytes.")
valid = _lib.Cryptography_check_pkcs7_padding(
self._buffer, self.block_size // 8
)
if not valid:
- raise ValueError("Invalid padding bytes")
+ raise ValueError("Invalid padding bytes.")
pad_size = six.indexbytes(self._buffer, -1)
res = self._buffer[:-pad_size]
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/serialization.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/serialization.py
new file mode 100644
index 0000000..ed73c4c
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/serialization.py
@@ -0,0 +1,26 @@
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+# implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import absolute_import, division, print_function
+
+
+def load_pem_traditional_openssl_private_key(data, password, backend):
+ return backend.load_traditional_openssl_pem_private_key(
+ data, password
+ )
+
+
+def load_pem_pkcs8_private_key(data, password, backend):
+ return backend.load_pkcs8_pem_private_key(
+ data, password
+ )
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py
index 41c467c..d0b476a 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py
@@ -29,7 +29,7 @@ class HOTP(object):
def __init__(self, key, length, algorithm, backend):
if not isinstance(backend, HMACBackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement HMACBackend",
+ "Backend object does not implement HMACBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
@@ -37,13 +37,13 @@ class HOTP(object):
raise ValueError("Key length has to be at least 128 bits.")
if not isinstance(length, six.integer_types):
- raise TypeError("Length parameter must be an integer type")
+ raise TypeError("Length parameter must be an integer type.")
if length < 6 or length > 8:
raise ValueError("Length of HOTP has to be between 6 to 8.")
if not isinstance(algorithm, (SHA1, SHA256, SHA512)):
- raise TypeError("Algorithm must be SHA1, SHA256 or SHA512")
+ raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.")
self._key = key
self._length = length
@@ -57,15 +57,13 @@ class HOTP(object):
def verify(self, hotp, counter):
if not constant_time.bytes_eq(self.generate(counter), hotp):
- raise InvalidToken("Supplied HOTP value does not match")
+ raise InvalidToken("Supplied HOTP value does not match.")
def _dynamic_truncate(self, counter):
ctx = hmac.HMAC(self._key, self._algorithm, self._backend)
ctx.update(struct.pack(">Q", counter))
hmac_value = ctx.finalize()
- offset_bits = six.indexbytes(hmac_value, len(hmac_value) - 1) & 0b1111
-
- offset = int(offset_bits)
+ offset = six.indexbytes(hmac_value, len(hmac_value) - 1) & 0b1111
p = hmac_value[offset:offset + 4]
return struct.unpack(">I", p)[0] & 0x7fffffff
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/twofactor/totp.py b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/twofactor/totp.py
index e55ba00..854c516 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/twofactor/totp.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/hazmat/primitives/twofactor/totp.py
@@ -25,7 +25,7 @@ class TOTP(object):
def __init__(self, key, length, algorithm, time_step, backend):
if not isinstance(backend, HMACBackend):
raise UnsupportedAlgorithm(
- "Backend object does not implement HMACBackend",
+ "Backend object does not implement HMACBackend.",
_Reasons.BACKEND_MISSING_INTERFACE
)
@@ -38,4 +38,4 @@ class TOTP(object):
def verify(self, totp, time):
if not constant_time.bytes_eq(self.generate(time), totp):
- raise InvalidToken("Supplied TOTP value does not match")
+ raise InvalidToken("Supplied TOTP value does not match.")
diff --git a/Darwin/lib/python2.7/site-packages/cryptography/utils.py b/Darwin/lib/python2.7/site-packages/cryptography/utils.py
index 5566d12..1db1615 100644
--- a/Darwin/lib/python2.7/site-packages/cryptography/utils.py
+++ b/Darwin/lib/python2.7/site-packages/cryptography/utils.py
@@ -16,7 +16,8 @@ from __future__ import absolute_import, division, print_function
import sys
-DeprecatedIn04 = PendingDeprecationWarning
+DeprecatedIn04 = DeprecationWarning
+DeprecatedIn05 = PendingDeprecationWarning
def register_interface(iface):
diff --git a/Darwin/lib/python2.7/site-packages/easy-install.pth b/Darwin/lib/python2.7/site-packages/easy-install.pth
index e1d80ad..b467a92 100644
--- a/Darwin/lib/python2.7/site-packages/easy-install.pth
+++ b/Darwin/lib/python2.7/site-packages/easy-install.pth
@@ -1,4 +1,4 @@
import sys; sys.__plen = len(sys.path)
./setuptools-3.6-py2.7.egg
-./pip-1.5.5-py2.7.egg
+./pip-1.5.6-py2.7.egg
import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)
diff --git a/Darwin/lib/python2.7/site-packages/ed25519/_ed25519.so b/Darwin/lib/python2.7/site-packages/ed25519/_ed25519.so
index dbd4661..8693acb 100755
Binary files a/Darwin/lib/python2.7/site-packages/ed25519/_ed25519.so and b/Darwin/lib/python2.7/site-packages/ed25519/_ed25519.so differ
diff --git a/Darwin/lib/python2.7/site-packages/flask/__init__.py b/Darwin/lib/python2.7/site-packages/flask/__init__.py
deleted file mode 100644
index 3fd8908..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/__init__.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask
- ~~~~~
-
- A microframework based on Werkzeug. It's extensively documented
- and follows best practice patterns.
-
- :copyright: (c) 2011 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-
-__version__ = '0.10.1'
-
-# utilities we import from Werkzeug and Jinja2 that are unused
-# in the module but are exported as public interface.
-from werkzeug.exceptions import abort
-from werkzeug.utils import redirect
-from jinja2 import Markup, escape
-
-from .app import Flask, Request, Response
-from .config import Config
-from .helpers import url_for, flash, send_file, send_from_directory, \
- get_flashed_messages, get_template_attribute, make_response, safe_join, \
- stream_with_context
-from .globals import current_app, g, request, session, _request_ctx_stack, \
- _app_ctx_stack
-from .ctx import has_request_context, has_app_context, \
- after_this_request, copy_current_request_context
-from .module import Module
-from .blueprints import Blueprint
-from .templating import render_template, render_template_string
-
-# the signals
-from .signals import signals_available, template_rendered, request_started, \
- request_finished, got_request_exception, request_tearing_down, \
- appcontext_tearing_down, appcontext_pushed, \
- appcontext_popped, message_flashed
-
-# We're not exposing the actual json module but a convenient wrapper around
-# it.
-from . import json
-
-# This was the only thing that flask used to export at one point and it had
-# a more generic name.
-jsonify = json.jsonify
-
-# backwards compat, goes away in 1.0
-from .sessions import SecureCookieSession as Session
-json_available = True
diff --git a/Darwin/lib/python2.7/site-packages/flask/_compat.py b/Darwin/lib/python2.7/site-packages/flask/_compat.py
deleted file mode 100644
index c342884..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/_compat.py
+++ /dev/null
@@ -1,73 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask._compat
- ~~~~~~~~~~~~~
-
- Some py2/py3 compatibility support based on a stripped down
- version of six so we don't have to depend on a specific version
- of it.
-
- :copyright: (c) 2013 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-import sys
-
-PY2 = sys.version_info[0] == 2
-_identity = lambda x: x
-
-
-if not PY2:
- text_type = str
- string_types = (str,)
- integer_types = (int, )
-
- iterkeys = lambda d: iter(d.keys())
- itervalues = lambda d: iter(d.values())
- iteritems = lambda d: iter(d.items())
-
- from io import StringIO
-
- def reraise(tp, value, tb=None):
- if value.__traceback__ is not tb:
- raise value.with_traceback(tb)
- raise value
-
- implements_to_string = _identity
-
-else:
- text_type = unicode
- string_types = (str, unicode)
- integer_types = (int, long)
-
- iterkeys = lambda d: d.iterkeys()
- itervalues = lambda d: d.itervalues()
- iteritems = lambda d: d.iteritems()
-
- from cStringIO import StringIO
-
- exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
-
- def implements_to_string(cls):
- cls.__unicode__ = cls.__str__
- cls.__str__ = lambda x: x.__unicode__().encode('utf-8')
- return cls
-
-
-def with_metaclass(meta, *bases):
- # This requires a bit of explanation: the basic idea is to make a
- # dummy metaclass for one level of class instantiation that replaces
- # itself with the actual metaclass. Because of internal type checks
- # we also need to make sure that we downgrade the custom metaclass
- # for one level to something closer to type (that's why __call__ and
- # __init__ comes back from type etc.).
- #
- # This has the advantage over six.with_metaclass in that it does not
- # introduce dummy classes into the final MRO.
- class metaclass(meta):
- __call__ = type.__call__
- __init__ = type.__init__
- def __new__(cls, name, this_bases, d):
- if this_bases is None:
- return type.__new__(cls, name, (), d)
- return meta(name, bases, d)
- return metaclass('temporary_class', None, {})
diff --git a/Darwin/lib/python2.7/site-packages/flask/app.py b/Darwin/lib/python2.7/site-packages/flask/app.py
deleted file mode 100644
index addc40b..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/app.py
+++ /dev/null
@@ -1,1842 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask.app
- ~~~~~~~~~
-
- This module implements the central WSGI application object.
-
- :copyright: (c) 2011 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-
-import os
-import sys
-from threading import Lock
-from datetime import timedelta
-from itertools import chain
-from functools import update_wrapper
-
-from werkzeug.datastructures import ImmutableDict
-from werkzeug.routing import Map, Rule, RequestRedirect, BuildError
-from werkzeug.exceptions import HTTPException, InternalServerError, \
- MethodNotAllowed, BadRequest
-
-from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \
- locked_cached_property, _endpoint_from_view_func, find_package
-from . import json
-from .wrappers import Request, Response
-from .config import ConfigAttribute, Config
-from .ctx import RequestContext, AppContext, _AppCtxGlobals
-from .globals import _request_ctx_stack, request, session, g
-from .sessions import SecureCookieSessionInterface
-from .module import blueprint_is_module
-from .templating import DispatchingJinjaLoader, Environment, \
- _default_template_ctx_processor
-from .signals import request_started, request_finished, got_request_exception, \
- request_tearing_down, appcontext_tearing_down
-from ._compat import reraise, string_types, text_type, integer_types
-
-# a lock used for logger initialization
-_logger_lock = Lock()
-
-
-def _make_timedelta(value):
- if not isinstance(value, timedelta):
- return timedelta(seconds=value)
- return value
-
-
-def setupmethod(f):
- """Wraps a method so that it performs a check in debug mode if the
- first request was already handled.
- """
- def wrapper_func(self, *args, **kwargs):
- if self.debug and self._got_first_request:
- raise AssertionError('A setup function was called after the '
- 'first request was handled. This usually indicates a bug '
- 'in the application where a module was not imported '
- 'and decorators or other functionality was called too late.\n'
- 'To fix this make sure to import all your view modules, '
- 'database models and everything related at a central place '
- 'before the application starts serving requests.')
- return f(self, *args, **kwargs)
- return update_wrapper(wrapper_func, f)
-
-
-class Flask(_PackageBoundObject):
- """The flask object implements a WSGI application and acts as the central
- object. It is passed the name of the module or package of the
- application. Once it is created it will act as a central registry for
- the view functions, the URL rules, template configuration and much more.
-
- The name of the package is used to resolve resources from inside the
- package or the folder the module is contained in depending on if the
- package parameter resolves to an actual python package (a folder with
- an `__init__.py` file inside) or a standard module (just a `.py` file).
-
- For more information about resource loading, see :func:`open_resource`.
-
- Usually you create a :class:`Flask` instance in your main module or
- in the `__init__.py` file of your package like this::
-
- from flask import Flask
- app = Flask(__name__)
-
- .. admonition:: About the First Parameter
-
- The idea of the first parameter is to give Flask an idea what
- belongs to your application. This name is used to find resources
- on the file system, can be used by extensions to improve debugging
- information and a lot more.
-
- So it's important what you provide there. If you are using a single
- module, `__name__` is always the correct value. If you however are
- using a package, it's usually recommended to hardcode the name of
- your package there.
-
- For example if your application is defined in `yourapplication/app.py`
- you should create it with one of the two versions below::
-
- app = Flask('yourapplication')
- app = Flask(__name__.split('.')[0])
-
- Why is that? The application will work even with `__name__`, thanks
- to how resources are looked up. However it will make debugging more
- painful. Certain extensions can make assumptions based on the
- import name of your application. For example the Flask-SQLAlchemy
- extension will look for the code in your application that triggered
- an SQL query in debug mode. If the import name is not properly set
- up, that debugging information is lost. (For example it would only
- pick up SQL queries in `yourapplication.app` and not
- `yourapplication.views.frontend`)
-
- .. versionadded:: 0.7
- The `static_url_path`, `static_folder`, and `template_folder`
- parameters were added.
-
- .. versionadded:: 0.8
- The `instance_path` and `instance_relative_config` parameters were
- added.
-
- :param import_name: the name of the application package
- :param static_url_path: can be used to specify a different path for the
- static files on the web. Defaults to the name
- of the `static_folder` folder.
- :param static_folder: the folder with static files that should be served
- at `static_url_path`. Defaults to the ``'static'``
- folder in the root path of the application.
- :param template_folder: the folder that contains the templates that should
- be used by the application. Defaults to
- ``'templates'`` folder in the root path of the
- application.
- :param instance_path: An alternative instance path for the application.
- By default the folder ``'instance'`` next to the
- package or module is assumed to be the instance
- path.
- :param instance_relative_config: if set to `True` relative filenames
- for loading the config are assumed to
- be relative to the instance path instead
- of the application root.
- """
-
- #: The class that is used for request objects. See :class:`~flask.Request`
- #: for more information.
- request_class = Request
-
- #: The class that is used for response objects. See
- #: :class:`~flask.Response` for more information.
- response_class = Response
-
- #: The class that is used for the :data:`~flask.g` instance.
- #:
- #: Example use cases for a custom class:
- #:
- #: 1. Store arbitrary attributes on flask.g.
- #: 2. Add a property for lazy per-request database connectors.
- #: 3. Return None instead of AttributeError on expected attributes.
- #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.
- #:
- #: In Flask 0.9 this property was called `request_globals_class` but it
- #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the
- #: flask.g object is not application context scoped.
- #:
- #: .. versionadded:: 0.10
- app_ctx_globals_class = _AppCtxGlobals
-
- # Backwards compatibility support
- def _get_request_globals_class(self):
- return self.app_ctx_globals_class
- def _set_request_globals_class(self, value):
- from warnings import warn
- warn(DeprecationWarning('request_globals_class attribute is now '
- 'called app_ctx_globals_class'))
- self.app_ctx_globals_class = value
- request_globals_class = property(_get_request_globals_class,
- _set_request_globals_class)
- del _get_request_globals_class, _set_request_globals_class
-
- #: The debug flag. Set this to `True` to enable debugging of the
- #: application. In debug mode the debugger will kick in when an unhandled
- #: exception occurs and the integrated server will automatically reload
- #: the application if changes in the code are detected.
- #:
- #: This attribute can also be configured from the config with the `DEBUG`
- #: configuration key. Defaults to `False`.
- debug = ConfigAttribute('DEBUG')
-
- #: The testing flag. Set this to `True` to enable the test mode of
- #: Flask extensions (and in the future probably also Flask itself).
- #: For example this might activate unittest helpers that have an
- #: additional runtime cost which should not be enabled by default.
- #:
- #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
- #: default it's implicitly enabled.
- #:
- #: This attribute can also be configured from the config with the
- #: `TESTING` configuration key. Defaults to `False`.
- testing = ConfigAttribute('TESTING')
-
- #: If a secret key is set, cryptographic components can use this to
- #: sign cookies and other things. Set this to a complex random value
- #: when you want to use the secure cookie for instance.
- #:
- #: This attribute can also be configured from the config with the
- #: `SECRET_KEY` configuration key. Defaults to `None`.
- secret_key = ConfigAttribute('SECRET_KEY')
-
- #: The secure cookie uses this for the name of the session cookie.
- #:
- #: This attribute can also be configured from the config with the
- #: `SESSION_COOKIE_NAME` configuration key. Defaults to ``'session'``
- session_cookie_name = ConfigAttribute('SESSION_COOKIE_NAME')
-
- #: A :class:`~datetime.timedelta` which is used to set the expiration
- #: date of a permanent session. The default is 31 days which makes a
- #: permanent session survive for roughly one month.
- #:
- #: This attribute can also be configured from the config with the
- #: `PERMANENT_SESSION_LIFETIME` configuration key. Defaults to
- #: ``timedelta(days=31)``
- permanent_session_lifetime = ConfigAttribute('PERMANENT_SESSION_LIFETIME',
- get_converter=_make_timedelta)
-
- #: Enable this if you want to use the X-Sendfile feature. Keep in
- #: mind that the server has to support this. This only affects files
- #: sent with the :func:`send_file` method.
- #:
- #: .. versionadded:: 0.2
- #:
- #: This attribute can also be configured from the config with the
- #: `USE_X_SENDFILE` configuration key. Defaults to `False`.
- use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')
-
- #: The name of the logger to use. By default the logger name is the
- #: package name passed to the constructor.
- #:
- #: .. versionadded:: 0.4
- logger_name = ConfigAttribute('LOGGER_NAME')
-
- #: Enable the deprecated module support? This is active by default
- #: in 0.7 but will be changed to False in 0.8. With Flask 1.0 modules
- #: will be removed in favor of Blueprints
- enable_modules = True
-
- #: The logging format used for the debug logger. This is only used when
- #: the application is in debug mode, otherwise the attached logging
- #: handler does the formatting.
- #:
- #: .. versionadded:: 0.3
- debug_log_format = (
- '-' * 80 + '\n' +
- '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +
- '%(message)s\n' +
- '-' * 80
- )
-
- #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.
- #:
- #: .. versionadded:: 0.10
- json_encoder = json.JSONEncoder
-
- #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.
- #:
- #: .. versionadded:: 0.10
- json_decoder = json.JSONDecoder
-
- #: Options that are passed directly to the Jinja2 environment.
- jinja_options = ImmutableDict(
- extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']
- )
-
- #: Default configuration parameters.
- default_config = ImmutableDict({
- 'DEBUG': False,
- 'TESTING': False,
- 'PROPAGATE_EXCEPTIONS': None,
- 'PRESERVE_CONTEXT_ON_EXCEPTION': None,
- 'SECRET_KEY': None,
- 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),
- 'USE_X_SENDFILE': False,
- 'LOGGER_NAME': None,
- 'SERVER_NAME': None,
- 'APPLICATION_ROOT': None,
- 'SESSION_COOKIE_NAME': 'session',
- 'SESSION_COOKIE_DOMAIN': None,
- 'SESSION_COOKIE_PATH': None,
- 'SESSION_COOKIE_HTTPONLY': True,
- 'SESSION_COOKIE_SECURE': False,
- 'MAX_CONTENT_LENGTH': None,
- 'SEND_FILE_MAX_AGE_DEFAULT': 12 * 60 * 60, # 12 hours
- 'TRAP_BAD_REQUEST_ERRORS': False,
- 'TRAP_HTTP_EXCEPTIONS': False,
- 'PREFERRED_URL_SCHEME': 'http',
- 'JSON_AS_ASCII': True,
- 'JSON_SORT_KEYS': True,
- 'JSONIFY_PRETTYPRINT_REGULAR': True,
- })
-
- #: The rule object to use for URL rules created. This is used by
- #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.
- #:
- #: .. versionadded:: 0.7
- url_rule_class = Rule
-
- #: the test client that is used with when `test_client` is used.
- #:
- #: .. versionadded:: 0.7
- test_client_class = None
-
- #: the session interface to use. By default an instance of
- #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.
- #:
- #: .. versionadded:: 0.8
- session_interface = SecureCookieSessionInterface()
-
- def __init__(self, import_name, static_path=None, static_url_path=None,
- static_folder='static', template_folder='templates',
- instance_path=None, instance_relative_config=False):
- _PackageBoundObject.__init__(self, import_name,
- template_folder=template_folder)
- if static_path is not None:
- from warnings import warn
- warn(DeprecationWarning('static_path is now called '
- 'static_url_path'), stacklevel=2)
- static_url_path = static_path
-
- if static_url_path is not None:
- self.static_url_path = static_url_path
- if static_folder is not None:
- self.static_folder = static_folder
- if instance_path is None:
- instance_path = self.auto_find_instance_path()
- elif not os.path.isabs(instance_path):
- raise ValueError('If an instance path is provided it must be '
- 'absolute. A relative path was given instead.')
-
- #: Holds the path to the instance folder.
- #:
- #: .. versionadded:: 0.8
- self.instance_path = instance_path
-
- #: The configuration dictionary as :class:`Config`. This behaves
- #: exactly like a regular dictionary but supports additional methods
- #: to load a config from files.
- self.config = self.make_config(instance_relative_config)
-
- # Prepare the deferred setup of the logger.
- self._logger = None
- self.logger_name = self.import_name
-
- #: A dictionary of all view functions registered. The keys will
- #: be function names which are also used to generate URLs and
- #: the values are the function objects themselves.
- #: To register a view function, use the :meth:`route` decorator.
- self.view_functions = {}
-
- # support for the now deprecated `error_handlers` attribute. The
- # :attr:`error_handler_spec` shall be used now.
- self._error_handlers = {}
-
- #: A dictionary of all registered error handlers. The key is `None`
- #: for error handlers active on the application, otherwise the key is
- #: the name of the blueprint. Each key points to another dictionary
- #: where they key is the status code of the http exception. The
- #: special key `None` points to a list of tuples where the first item
- #: is the class for the instance check and the second the error handler
- #: function.
- #:
- #: To register a error handler, use the :meth:`errorhandler`
- #: decorator.
- self.error_handler_spec = {None: self._error_handlers}
-
- #: A list of functions that are called when :meth:`url_for` raises a
- #: :exc:`~werkzeug.routing.BuildError`. Each function registered here
- #: is called with `error`, `endpoint` and `values`. If a function
- #: returns `None` or raises a `BuildError` the next function is
- #: tried.
- #:
- #: .. versionadded:: 0.9
- self.url_build_error_handlers = []
-
- #: A dictionary with lists of functions that should be called at the
- #: beginning of the request. The key of the dictionary is the name of
- #: the blueprint this function is active for, `None` for all requests.
- #: This can for example be used to open database connections or
- #: getting hold of the currently logged in user. To register a
- #: function here, use the :meth:`before_request` decorator.
- self.before_request_funcs = {}
-
- #: A lists of functions that should be called at the beginning of the
- #: first request to this instance. To register a function here, use
- #: the :meth:`before_first_request` decorator.
- #:
- #: .. versionadded:: 0.8
- self.before_first_request_funcs = []
-
- #: A dictionary with lists of functions that should be called after
- #: each request. The key of the dictionary is the name of the blueprint
- #: this function is active for, `None` for all requests. This can for
- #: example be used to open database connections or getting hold of the
- #: currently logged in user. To register a function here, use the
- #: :meth:`after_request` decorator.
- self.after_request_funcs = {}
-
- #: A dictionary with lists of functions that are called after
- #: each request, even if an exception has occurred. The key of the
- #: dictionary is the name of the blueprint this function is active for,
- #: `None` for all requests. These functions are not allowed to modify
- #: the request, and their return values are ignored. If an exception
- #: occurred while processing the request, it gets passed to each
- #: teardown_request function. To register a function here, use the
- #: :meth:`teardown_request` decorator.
- #:
- #: .. versionadded:: 0.7
- self.teardown_request_funcs = {}
-
- #: A list of functions that are called when the application context
- #: is destroyed. Since the application context is also torn down
- #: if the request ends this is the place to store code that disconnects
- #: from databases.
- #:
- #: .. versionadded:: 0.9
- self.teardown_appcontext_funcs = []
-
- #: A dictionary with lists of functions that can be used as URL
- #: value processor functions. Whenever a URL is built these functions
- #: are called to modify the dictionary of values in place. The key
- #: `None` here is used for application wide
- #: callbacks, otherwise the key is the name of the blueprint.
- #: Each of these functions has the chance to modify the dictionary
- #:
- #: .. versionadded:: 0.7
- self.url_value_preprocessors = {}
-
- #: A dictionary with lists of functions that can be used as URL value
- #: preprocessors. The key `None` here is used for application wide
- #: callbacks, otherwise the key is the name of the blueprint.
- #: Each of these functions has the chance to modify the dictionary
- #: of URL values before they are used as the keyword arguments of the
- #: view function. For each function registered this one should also
- #: provide a :meth:`url_defaults` function that adds the parameters
- #: automatically again that were removed that way.
- #:
- #: .. versionadded:: 0.7
- self.url_default_functions = {}
-
- #: A dictionary with list of functions that are called without argument
- #: to populate the template context. The key of the dictionary is the
- #: name of the blueprint this function is active for, `None` for all
- #: requests. Each returns a dictionary that the template context is
- #: updated with. To register a function here, use the
- #: :meth:`context_processor` decorator.
- self.template_context_processors = {
- None: [_default_template_ctx_processor]
- }
-
- #: all the attached blueprints in a dictionary by name. Blueprints
- #: can be attached multiple times so this dictionary does not tell
- #: you how often they got attached.
- #:
- #: .. versionadded:: 0.7
- self.blueprints = {}
-
- #: a place where extensions can store application specific state. For
- #: example this is where an extension could store database engines and
- #: similar things. For backwards compatibility extensions should register
- #: themselves like this::
- #:
- #: if not hasattr(app, 'extensions'):
- #: app.extensions = {}
- #: app.extensions['extensionname'] = SomeObject()
- #:
- #: The key must match the name of the `flaskext` module. For example in
- #: case of a "Flask-Foo" extension in `flaskext.foo`, the key would be
- #: ``'foo'``.
- #:
- #: .. versionadded:: 0.7
- self.extensions = {}
-
- #: The :class:`~werkzeug.routing.Map` for this instance. You can use
- #: this to change the routing converters after the class was created
- #: but before any routes are connected. Example::
- #:
- #: from werkzeug.routing import BaseConverter
- #:
- #: class ListConverter(BaseConverter):
- #: def to_python(self, value):
- #: return value.split(',')
- #: def to_url(self, values):
- #: return ','.join(BaseConverter.to_url(value)
- #: for value in values)
- #:
- #: app = Flask(__name__)
- #: app.url_map.converters['list'] = ListConverter
- self.url_map = Map()
-
- # tracks internally if the application already handled at least one
- # request.
- self._got_first_request = False
- self._before_request_lock = Lock()
-
- # register the static folder for the application. Do that even
- # if the folder does not exist. First of all it might be created
- # while the server is running (usually happens during development)
- # but also because google appengine stores static files somewhere
- # else when mapped with the .yml file.
- if self.has_static_folder:
- self.add_url_rule(self.static_url_path + '/',
- endpoint='static',
- view_func=self.send_static_file)
-
- def _get_error_handlers(self):
- from warnings import warn
- warn(DeprecationWarning('error_handlers is deprecated, use the '
- 'new error_handler_spec attribute instead.'), stacklevel=1)
- return self._error_handlers
- def _set_error_handlers(self, value):
- self._error_handlers = value
- self.error_handler_spec[None] = value
- error_handlers = property(_get_error_handlers, _set_error_handlers)
- del _get_error_handlers, _set_error_handlers
-
- @locked_cached_property
- def name(self):
- """The name of the application. This is usually the import name
- with the difference that it's guessed from the run file if the
- import name is main. This name is used as a display name when
- Flask needs the name of the application. It can be set and overridden
- to change the value.
-
- .. versionadded:: 0.8
- """
- if self.import_name == '__main__':
- fn = getattr(sys.modules['__main__'], '__file__', None)
- if fn is None:
- return '__main__'
- return os.path.splitext(os.path.basename(fn))[0]
- return self.import_name
-
- @property
- def propagate_exceptions(self):
- """Returns the value of the `PROPAGATE_EXCEPTIONS` configuration
- value in case it's set, otherwise a sensible default is returned.
-
- .. versionadded:: 0.7
- """
- rv = self.config['PROPAGATE_EXCEPTIONS']
- if rv is not None:
- return rv
- return self.testing or self.debug
-
- @property
- def preserve_context_on_exception(self):
- """Returns the value of the `PRESERVE_CONTEXT_ON_EXCEPTION`
- configuration value in case it's set, otherwise a sensible default
- is returned.
-
- .. versionadded:: 0.7
- """
- rv = self.config['PRESERVE_CONTEXT_ON_EXCEPTION']
- if rv is not None:
- return rv
- return self.debug
-
- @property
- def logger(self):
- """A :class:`logging.Logger` object for this application. The
- default configuration is to log to stderr if the application is
- in debug mode. This logger can be used to (surprise) log messages.
- Here some examples::
-
- app.logger.debug('A value for debugging')
- app.logger.warning('A warning occurred (%d apples)', 42)
- app.logger.error('An error occurred')
-
- .. versionadded:: 0.3
- """
- if self._logger and self._logger.name == self.logger_name:
- return self._logger
- with _logger_lock:
- if self._logger and self._logger.name == self.logger_name:
- return self._logger
- from flask.logging import create_logger
- self._logger = rv = create_logger(self)
- return rv
-
- @locked_cached_property
- def jinja_env(self):
- """The Jinja2 environment used to load templates."""
- return self.create_jinja_environment()
-
- @property
- def got_first_request(self):
- """This attribute is set to `True` if the application started
- handling the first request.
-
- .. versionadded:: 0.8
- """
- return self._got_first_request
-
- def make_config(self, instance_relative=False):
- """Used to create the config attribute by the Flask constructor.
- The `instance_relative` parameter is passed in from the constructor
- of Flask (there named `instance_relative_config`) and indicates if
- the config should be relative to the instance path or the root path
- of the application.
-
- .. versionadded:: 0.8
- """
- root_path = self.root_path
- if instance_relative:
- root_path = self.instance_path
- return Config(root_path, self.default_config)
-
- def auto_find_instance_path(self):
- """Tries to locate the instance path if it was not provided to the
- constructor of the application class. It will basically calculate
- the path to a folder named ``instance`` next to your main file or
- the package.
-
- .. versionadded:: 0.8
- """
- prefix, package_path = find_package(self.import_name)
- if prefix is None:
- return os.path.join(package_path, 'instance')
- return os.path.join(prefix, 'var', self.name + '-instance')
-
- def open_instance_resource(self, resource, mode='rb'):
- """Opens a resource from the application's instance folder
- (:attr:`instance_path`). Otherwise works like
- :meth:`open_resource`. Instance resources can also be opened for
- writing.
-
- :param resource: the name of the resource. To access resources within
- subfolders use forward slashes as separator.
- :param mode: resource file opening mode, default is 'rb'.
- """
- return open(os.path.join(self.instance_path, resource), mode)
-
- def create_jinja_environment(self):
- """Creates the Jinja2 environment based on :attr:`jinja_options`
- and :meth:`select_jinja_autoescape`. Since 0.7 this also adds
- the Jinja2 globals and filters after initialization. Override
- this function to customize the behavior.
-
- .. versionadded:: 0.5
- """
- options = dict(self.jinja_options)
- if 'autoescape' not in options:
- options['autoescape'] = self.select_jinja_autoescape
- rv = Environment(self, **options)
- rv.globals.update(
- url_for=url_for,
- get_flashed_messages=get_flashed_messages,
- config=self.config,
- # request, session and g are normally added with the
- # context processor for efficiency reasons but for imported
- # templates we also want the proxies in there.
- request=request,
- session=session,
- g=g
- )
- rv.filters['tojson'] = json.tojson_filter
- return rv
-
- def create_global_jinja_loader(self):
- """Creates the loader for the Jinja2 environment. Can be used to
- override just the loader and keeping the rest unchanged. It's
- discouraged to override this function. Instead one should override
- the :meth:`jinja_loader` function instead.
-
- The global loader dispatches between the loaders of the application
- and the individual blueprints.
-
- .. versionadded:: 0.7
- """
- return DispatchingJinjaLoader(self)
-
- def init_jinja_globals(self):
- """Deprecated. Used to initialize the Jinja2 globals.
-
- .. versionadded:: 0.5
- .. versionchanged:: 0.7
- This method is deprecated with 0.7. Override
- :meth:`create_jinja_environment` instead.
- """
-
- def select_jinja_autoescape(self, filename):
- """Returns `True` if autoescaping should be active for the given
- template name.
-
- .. versionadded:: 0.5
- """
- if filename is None:
- return False
- return filename.endswith(('.html', '.htm', '.xml', '.xhtml'))
-
- def update_template_context(self, context):
- """Update the template context with some commonly used variables.
- This injects request, session, config and g into the template
- context as well as everything template context processors want
- to inject. Note that the as of Flask 0.6, the original values
- in the context will not be overridden if a context processor
- decides to return a value with the same key.
-
- :param context: the context as a dictionary that is updated in place
- to add extra variables.
- """
- funcs = self.template_context_processors[None]
- reqctx = _request_ctx_stack.top
- if reqctx is not None:
- bp = reqctx.request.blueprint
- if bp is not None and bp in self.template_context_processors:
- funcs = chain(funcs, self.template_context_processors[bp])
- orig_ctx = context.copy()
- for func in funcs:
- context.update(func())
- # make sure the original values win. This makes it possible to
- # easier add new variables in context processors without breaking
- # existing views.
- context.update(orig_ctx)
-
- def run(self, host=None, port=None, debug=None, **options):
- """Runs the application on a local development server. If the
- :attr:`debug` flag is set the server will automatically reload
- for code changes and show a debugger in case an exception happened.
-
- If you want to run the application in debug mode, but disable the
- code execution on the interactive debugger, you can pass
- ``use_evalex=False`` as parameter. This will keep the debugger's
- traceback screen active, but disable code execution.
-
- .. admonition:: Keep in Mind
-
- Flask will suppress any server error with a generic error page
- unless it is in debug mode. As such to enable just the
- interactive debugger without the code reloading, you have to
- invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
- Setting ``use_debugger`` to `True` without being in debug mode
- won't catch any exceptions because there won't be any to
- catch.
-
- .. versionchanged:: 0.10
- The default port is now picked from the ``SERVER_NAME`` variable.
-
- :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
- have the server available externally as well. Defaults to
- ``'127.0.0.1'``.
- :param port: the port of the webserver. Defaults to ``5000`` or the
- port defined in the ``SERVER_NAME`` config variable if
- present.
- :param debug: if given, enable or disable debug mode.
- See :attr:`debug`.
- :param options: the options to be forwarded to the underlying
- Werkzeug server. See
- :func:`werkzeug.serving.run_simple` for more
- information.
- """
- from werkzeug.serving import run_simple
- if host is None:
- host = '127.0.0.1'
- if port is None:
- server_name = self.config['SERVER_NAME']
- if server_name and ':' in server_name:
- port = int(server_name.rsplit(':', 1)[1])
- else:
- port = 5000
- if debug is not None:
- self.debug = bool(debug)
- options.setdefault('use_reloader', self.debug)
- options.setdefault('use_debugger', self.debug)
- try:
- run_simple(host, port, self, **options)
- finally:
- # reset the first request information if the development server
- # resetted normally. This makes it possible to restart the server
- # without reloader and that stuff from an interactive shell.
- self._got_first_request = False
-
- def test_client(self, use_cookies=True):
- """Creates a test client for this application. For information
- about unit testing head over to :ref:`testing`.
-
- Note that if you are testing for assertions or exceptions in your
- application code, you must set ``app.testing = True`` in order for the
- exceptions to propagate to the test client. Otherwise, the exception
- will be handled by the application (not visible to the test client) and
- the only indication of an AssertionError or other exception will be a
- 500 status code response to the test client. See the :attr:`testing`
- attribute. For example::
-
- app.testing = True
- client = app.test_client()
-
- The test client can be used in a `with` block to defer the closing down
- of the context until the end of the `with` block. This is useful if
- you want to access the context locals for testing::
-
- with app.test_client() as c:
- rv = c.get('/?vodka=42')
- assert request.args['vodka'] == '42'
-
- See :class:`~flask.testing.FlaskClient` for more information.
-
- .. versionchanged:: 0.4
- added support for `with` block usage for the client.
-
- .. versionadded:: 0.7
- The `use_cookies` parameter was added as well as the ability
- to override the client to be used by setting the
- :attr:`test_client_class` attribute.
- """
- cls = self.test_client_class
- if cls is None:
- from flask.testing import FlaskClient as cls
- return cls(self, self.response_class, use_cookies=use_cookies)
-
- def open_session(self, request):
- """Creates or opens a new session. Default implementation stores all
- session data in a signed cookie. This requires that the
- :attr:`secret_key` is set. Instead of overriding this method
- we recommend replacing the :class:`session_interface`.
-
- :param request: an instance of :attr:`request_class`.
- """
- return self.session_interface.open_session(self, request)
-
- def save_session(self, session, response):
- """Saves the session if it needs updates. For the default
- implementation, check :meth:`open_session`. Instead of overriding this
- method we recommend replacing the :class:`session_interface`.
-
- :param session: the session to be saved (a
- :class:`~werkzeug.contrib.securecookie.SecureCookie`
- object)
- :param response: an instance of :attr:`response_class`
- """
- return self.session_interface.save_session(self, session, response)
-
- def make_null_session(self):
- """Creates a new instance of a missing session. Instead of overriding
- this method we recommend replacing the :class:`session_interface`.
-
- .. versionadded:: 0.7
- """
- return self.session_interface.make_null_session(self)
-
- def register_module(self, module, **options):
- """Registers a module with this application. The keyword argument
- of this function are the same as the ones for the constructor of the
- :class:`Module` class and will override the values of the module if
- provided.
-
- .. versionchanged:: 0.7
- The module system was deprecated in favor for the blueprint
- system.
- """
- assert blueprint_is_module(module), 'register_module requires ' \
- 'actual module objects. Please upgrade to blueprints though.'
- if not self.enable_modules:
- raise RuntimeError('Module support was disabled but code '
- 'attempted to register a module named %r' % module)
- else:
- from warnings import warn
- warn(DeprecationWarning('Modules are deprecated. Upgrade to '
- 'using blueprints. Have a look into the documentation for '
- 'more information. If this module was registered by a '
- 'Flask-Extension upgrade the extension or contact the author '
- 'of that extension instead. (Registered %r)' % module),
- stacklevel=2)
-
- self.register_blueprint(module, **options)
-
- @setupmethod
- def register_blueprint(self, blueprint, **options):
- """Registers a blueprint on the application.
-
- .. versionadded:: 0.7
- """
- first_registration = False
- if blueprint.name in self.blueprints:
- assert self.blueprints[blueprint.name] is blueprint, \
- 'A blueprint\'s name collision occurred between %r and ' \
- '%r. Both share the same name "%s". Blueprints that ' \
- 'are created on the fly need unique names.' % \
- (blueprint, self.blueprints[blueprint.name], blueprint.name)
- else:
- self.blueprints[blueprint.name] = blueprint
- first_registration = True
- blueprint.register(self, options, first_registration)
-
- @setupmethod
- def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
- """Connects a URL rule. Works exactly like the :meth:`route`
- decorator. If a view_func is provided it will be registered with the
- endpoint.
-
- Basically this example::
-
- @app.route('/')
- def index():
- pass
-
- Is equivalent to the following::
-
- def index():
- pass
- app.add_url_rule('/', 'index', index)
-
- If the view_func is not provided you will need to connect the endpoint
- to a view function like so::
-
- app.view_functions['index'] = index
-
- Internally :meth:`route` invokes :meth:`add_url_rule` so if you want
- to customize the behavior via subclassing you only need to change
- this method.
-
- For more information refer to :ref:`url-route-registrations`.
-
- .. versionchanged:: 0.2
- `view_func` parameter added.
-
- .. versionchanged:: 0.6
- `OPTIONS` is added automatically as method.
-
- :param rule: the URL rule as string
- :param endpoint: the endpoint for the registered URL rule. Flask
- itself assumes the name of the view function as
- endpoint
- :param view_func: the function to call when serving a request to the
- provided endpoint
- :param options: the options to be forwarded to the underlying
- :class:`~werkzeug.routing.Rule` object. A change
- to Werkzeug is handling of method options. methods
- is a list of methods this rule should be limited
- to (`GET`, `POST` etc.). By default a rule
- just listens for `GET` (and implicitly `HEAD`).
- Starting with Flask 0.6, `OPTIONS` is implicitly
- added and handled by the standard request handling.
- """
- if endpoint is None:
- endpoint = _endpoint_from_view_func(view_func)
- options['endpoint'] = endpoint
- methods = options.pop('methods', None)
-
- # if the methods are not given and the view_func object knows its
- # methods we can use that instead. If neither exists, we go with
- # a tuple of only `GET` as default.
- if methods is None:
- methods = getattr(view_func, 'methods', None) or ('GET',)
- methods = set(methods)
-
- # Methods that should always be added
- required_methods = set(getattr(view_func, 'required_methods', ()))
-
- # starting with Flask 0.8 the view_func object can disable and
- # force-enable the automatic options handling.
- provide_automatic_options = getattr(view_func,
- 'provide_automatic_options', None)
-
- if provide_automatic_options is None:
- if 'OPTIONS' not in methods:
- provide_automatic_options = True
- required_methods.add('OPTIONS')
- else:
- provide_automatic_options = False
-
- # Add the required methods now.
- methods |= required_methods
-
- # due to a werkzeug bug we need to make sure that the defaults are
- # None if they are an empty dictionary. This should not be necessary
- # with Werkzeug 0.7
- options['defaults'] = options.get('defaults') or None
-
- rule = self.url_rule_class(rule, methods=methods, **options)
- rule.provide_automatic_options = provide_automatic_options
-
- self.url_map.add(rule)
- if view_func is not None:
- old_func = self.view_functions.get(endpoint)
- if old_func is not None and old_func != view_func:
- raise AssertionError('View function mapping is overwriting an '
- 'existing endpoint function: %s' % endpoint)
- self.view_functions[endpoint] = view_func
-
- def route(self, rule, **options):
- """A decorator that is used to register a view function for a
- given URL rule. This does the same thing as :meth:`add_url_rule`
- but is intended for decorator usage::
-
- @app.route('/')
- def index():
- return 'Hello World'
-
- For more information refer to :ref:`url-route-registrations`.
-
- :param rule: the URL rule as string
- :param endpoint: the endpoint for the registered URL rule. Flask
- itself assumes the name of the view function as
- endpoint
- :param options: the options to be forwarded to the underlying
- :class:`~werkzeug.routing.Rule` object. A change
- to Werkzeug is handling of method options. methods
- is a list of methods this rule should be limited
- to (`GET`, `POST` etc.). By default a rule
- just listens for `GET` (and implicitly `HEAD`).
- Starting with Flask 0.6, `OPTIONS` is implicitly
- added and handled by the standard request handling.
- """
- def decorator(f):
- endpoint = options.pop('endpoint', None)
- self.add_url_rule(rule, endpoint, f, **options)
- return f
- return decorator
-
- @setupmethod
- def endpoint(self, endpoint):
- """A decorator to register a function as an endpoint.
- Example::
-
- @app.endpoint('example.endpoint')
- def example():
- return "example"
-
- :param endpoint: the name of the endpoint
- """
- def decorator(f):
- self.view_functions[endpoint] = f
- return f
- return decorator
-
- @setupmethod
- def errorhandler(self, code_or_exception):
- """A decorator that is used to register a function give a given
- error code. Example::
-
- @app.errorhandler(404)
- def page_not_found(error):
- return 'This page does not exist', 404
-
- You can also register handlers for arbitrary exceptions::
-
- @app.errorhandler(DatabaseError)
- def special_exception_handler(error):
- return 'Database connection failed', 500
-
- You can also register a function as error handler without using
- the :meth:`errorhandler` decorator. The following example is
- equivalent to the one above::
-
- def page_not_found(error):
- return 'This page does not exist', 404
- app.error_handler_spec[None][404] = page_not_found
-
- Setting error handlers via assignments to :attr:`error_handler_spec`
- however is discouraged as it requires fiddling with nested dictionaries
- and the special case for arbitrary exception types.
-
- The first `None` refers to the active blueprint. If the error
- handler should be application wide `None` shall be used.
-
- .. versionadded:: 0.7
- One can now additionally also register custom exception types
- that do not necessarily have to be a subclass of the
- :class:`~werkzeug.exceptions.HTTPException` class.
-
- :param code: the code as integer for the handler
- """
- def decorator(f):
- self._register_error_handler(None, code_or_exception, f)
- return f
- return decorator
-
- def register_error_handler(self, code_or_exception, f):
- """Alternative error attach function to the :meth:`errorhandler`
- decorator that is more straightforward to use for non decorator
- usage.
-
- .. versionadded:: 0.7
- """
- self._register_error_handler(None, code_or_exception, f)
-
- @setupmethod
- def _register_error_handler(self, key, code_or_exception, f):
- if isinstance(code_or_exception, HTTPException):
- code_or_exception = code_or_exception.code
- if isinstance(code_or_exception, integer_types):
- assert code_or_exception != 500 or key is None, \
- 'It is currently not possible to register a 500 internal ' \
- 'server error on a per-blueprint level.'
- self.error_handler_spec.setdefault(key, {})[code_or_exception] = f
- else:
- self.error_handler_spec.setdefault(key, {}).setdefault(None, []) \
- .append((code_or_exception, f))
-
- @setupmethod
- def template_filter(self, name=None):
- """A decorator that is used to register custom template filter.
- You can specify a name for the filter, otherwise the function
- name will be used. Example::
-
- @app.template_filter()
- def reverse(s):
- return s[::-1]
-
- :param name: the optional name of the filter, otherwise the
- function name will be used.
- """
- def decorator(f):
- self.add_template_filter(f, name=name)
- return f
- return decorator
-
- @setupmethod
- def add_template_filter(self, f, name=None):
- """Register a custom template filter. Works exactly like the
- :meth:`template_filter` decorator.
-
- :param name: the optional name of the filter, otherwise the
- function name will be used.
- """
- self.jinja_env.filters[name or f.__name__] = f
-
- @setupmethod
- def template_test(self, name=None):
- """A decorator that is used to register custom template test.
- You can specify a name for the test, otherwise the function
- name will be used. Example::
-
- @app.template_test()
- def is_prime(n):
- if n == 2:
- return True
- for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
- if n % i == 0:
- return False
- return True
-
- .. versionadded:: 0.10
-
- :param name: the optional name of the test, otherwise the
- function name will be used.
- """
- def decorator(f):
- self.add_template_test(f, name=name)
- return f
- return decorator
-
- @setupmethod
- def add_template_test(self, f, name=None):
- """Register a custom template test. Works exactly like the
- :meth:`template_test` decorator.
-
- .. versionadded:: 0.10
-
- :param name: the optional name of the test, otherwise the
- function name will be used.
- """
- self.jinja_env.tests[name or f.__name__] = f
-
-
- @setupmethod
- def template_global(self, name=None):
- """A decorator that is used to register a custom template global function.
- You can specify a name for the global function, otherwise the function
- name will be used. Example::
-
- @app.template_global()
- def double(n):
- return 2 * n
-
- .. versionadded:: 0.10
-
- :param name: the optional name of the global function, otherwise the
- function name will be used.
- """
- def decorator(f):
- self.add_template_global(f, name=name)
- return f
- return decorator
-
- @setupmethod
- def add_template_global(self, f, name=None):
- """Register a custom template global function. Works exactly like the
- :meth:`template_global` decorator.
-
- .. versionadded:: 0.10
-
- :param name: the optional name of the global function, otherwise the
- function name will be used.
- """
- self.jinja_env.globals[name or f.__name__] = f
-
- @setupmethod
- def before_request(self, f):
- """Registers a function to run before each request."""
- self.before_request_funcs.setdefault(None, []).append(f)
- return f
-
- @setupmethod
- def before_first_request(self, f):
- """Registers a function to be run before the first request to this
- instance of the application.
-
- .. versionadded:: 0.8
- """
- self.before_first_request_funcs.append(f)
-
- @setupmethod
- def after_request(self, f):
- """Register a function to be run after each request. Your function
- must take one parameter, a :attr:`response_class` object and return
- a new response object or the same (see :meth:`process_response`).
-
- As of Flask 0.7 this function might not be executed at the end of the
- request in case an unhandled exception occurred.
- """
- self.after_request_funcs.setdefault(None, []).append(f)
- return f
-
- @setupmethod
- def teardown_request(self, f):
- """Register a function to be run at the end of each request,
- regardless of whether there was an exception or not. These functions
- are executed when the request context is popped, even if not an
- actual request was performed.
-
- Example::
-
- ctx = app.test_request_context()
- ctx.push()
- ...
- ctx.pop()
-
- When ``ctx.pop()`` is executed in the above example, the teardown
- functions are called just before the request context moves from the
- stack of active contexts. This becomes relevant if you are using
- such constructs in tests.
-
- Generally teardown functions must take every necessary step to avoid
- that they will fail. If they do execute code that might fail they
- will have to surround the execution of these code by try/except
- statements and log occurring errors.
-
- When a teardown function was called because of a exception it will
- be passed an error object.
-
- .. admonition:: Debug Note
-
- In debug mode Flask will not tear down a request on an exception
- immediately. Instead if will keep it alive so that the interactive
- debugger can still access it. This behavior can be controlled
- by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
- """
- self.teardown_request_funcs.setdefault(None, []).append(f)
- return f
-
- @setupmethod
- def teardown_appcontext(self, f):
- """Registers a function to be called when the application context
- ends. These functions are typically also called when the request
- context is popped.
-
- Example::
-
- ctx = app.app_context()
- ctx.push()
- ...
- ctx.pop()
-
- When ``ctx.pop()`` is executed in the above example, the teardown
- functions are called just before the app context moves from the
- stack of active contexts. This becomes relevant if you are using
- such constructs in tests.
-
- Since a request context typically also manages an application
- context it would also be called when you pop a request context.
-
- When a teardown function was called because of an exception it will
- be passed an error object.
-
- .. versionadded:: 0.9
- """
- self.teardown_appcontext_funcs.append(f)
- return f
-
- @setupmethod
- def context_processor(self, f):
- """Registers a template context processor function."""
- self.template_context_processors[None].append(f)
- return f
-
- @setupmethod
- def url_value_preprocessor(self, f):
- """Registers a function as URL value preprocessor for all view
- functions of the application. It's called before the view functions
- are called and can modify the url values provided.
- """
- self.url_value_preprocessors.setdefault(None, []).append(f)
- return f
-
- @setupmethod
- def url_defaults(self, f):
- """Callback function for URL defaults for all view functions of the
- application. It's called with the endpoint and values and should
- update the values passed in place.
- """
- self.url_default_functions.setdefault(None, []).append(f)
- return f
-
- def handle_http_exception(self, e):
- """Handles an HTTP exception. By default this will invoke the
- registered error handlers and fall back to returning the
- exception as response.
-
- .. versionadded:: 0.3
- """
- handlers = self.error_handler_spec.get(request.blueprint)
- # Proxy exceptions don't have error codes. We want to always return
- # those unchanged as errors
- if e.code is None:
- return e
- if handlers and e.code in handlers:
- handler = handlers[e.code]
- else:
- handler = self.error_handler_spec[None].get(e.code)
- if handler is None:
- return e
- return handler(e)
-
- def trap_http_exception(self, e):
- """Checks if an HTTP exception should be trapped or not. By default
- this will return `False` for all exceptions except for a bad request
- key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to `True`. It
- also returns `True` if ``TRAP_HTTP_EXCEPTIONS`` is set to `True`.
-
- This is called for all HTTP exceptions raised by a view function.
- If it returns `True` for any exception the error handler for this
- exception is not called and it shows up as regular exception in the
- traceback. This is helpful for debugging implicitly raised HTTP
- exceptions.
-
- .. versionadded:: 0.8
- """
- if self.config['TRAP_HTTP_EXCEPTIONS']:
- return True
- if self.config['TRAP_BAD_REQUEST_ERRORS']:
- return isinstance(e, BadRequest)
- return False
-
- def handle_user_exception(self, e):
- """This method is called whenever an exception occurs that should be
- handled. A special case are
- :class:`~werkzeug.exception.HTTPException`\s which are forwarded by
- this function to the :meth:`handle_http_exception` method. This
- function will either return a response value or reraise the
- exception with the same traceback.
-
- .. versionadded:: 0.7
- """
- exc_type, exc_value, tb = sys.exc_info()
- assert exc_value is e
-
- # ensure not to trash sys.exc_info() at that point in case someone
- # wants the traceback preserved in handle_http_exception. Of course
- # we cannot prevent users from trashing it themselves in a custom
- # trap_http_exception method so that's their fault then.
- if isinstance(e, HTTPException) and not self.trap_http_exception(e):
- return self.handle_http_exception(e)
-
- blueprint_handlers = ()
- handlers = self.error_handler_spec.get(request.blueprint)
- if handlers is not None:
- blueprint_handlers = handlers.get(None, ())
- app_handlers = self.error_handler_spec[None].get(None, ())
- for typecheck, handler in chain(blueprint_handlers, app_handlers):
- if isinstance(e, typecheck):
- return handler(e)
-
- reraise(exc_type, exc_value, tb)
-
- def handle_exception(self, e):
- """Default exception handling that kicks in when an exception
- occurs that is not caught. In debug mode the exception will
- be re-raised immediately, otherwise it is logged and the handler
- for a 500 internal server error is used. If no such handler
- exists, a default 500 internal server error message is displayed.
-
- .. versionadded:: 0.3
- """
- exc_type, exc_value, tb = sys.exc_info()
-
- got_request_exception.send(self, exception=e)
- handler = self.error_handler_spec[None].get(500)
-
- if self.propagate_exceptions:
- # if we want to repropagate the exception, we can attempt to
- # raise it with the whole traceback in case we can do that
- # (the function was actually called from the except part)
- # otherwise, we just raise the error again
- if exc_value is e:
- reraise(exc_type, exc_value, tb)
- else:
- raise e
-
- self.log_exception((exc_type, exc_value, tb))
- if handler is None:
- return InternalServerError()
- return handler(e)
-
- def log_exception(self, exc_info):
- """Logs an exception. This is called by :meth:`handle_exception`
- if debugging is disabled and right before the handler is called.
- The default implementation logs the exception as error on the
- :attr:`logger`.
-
- .. versionadded:: 0.8
- """
- self.logger.error('Exception on %s [%s]' % (
- request.path,
- request.method
- ), exc_info=exc_info)
-
- def raise_routing_exception(self, request):
- """Exceptions that are recording during routing are reraised with
- this method. During debug we are not reraising redirect requests
- for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
- a different error instead to help debug situations.
-
- :internal:
- """
- if not self.debug \
- or not isinstance(request.routing_exception, RequestRedirect) \
- or request.method in ('GET', 'HEAD', 'OPTIONS'):
- raise request.routing_exception
-
- from .debughelpers import FormDataRoutingRedirect
- raise FormDataRoutingRedirect(request)
-
- def dispatch_request(self):
- """Does the request dispatching. Matches the URL and returns the
- return value of the view or error handler. This does not have to
- be a response object. In order to convert the return value to a
- proper response object, call :func:`make_response`.
-
- .. versionchanged:: 0.7
- This no longer does the exception handling, this code was
- moved to the new :meth:`full_dispatch_request`.
- """
- req = _request_ctx_stack.top.request
- if req.routing_exception is not None:
- self.raise_routing_exception(req)
- rule = req.url_rule
- # if we provide automatic options for this URL and the
- # request came with the OPTIONS method, reply automatically
- if getattr(rule, 'provide_automatic_options', False) \
- and req.method == 'OPTIONS':
- return self.make_default_options_response()
- # otherwise dispatch to the handler for that endpoint
- return self.view_functions[rule.endpoint](**req.view_args)
-
- def full_dispatch_request(self):
- """Dispatches the request and on top of that performs request
- pre and postprocessing as well as HTTP exception catching and
- error handling.
-
- .. versionadded:: 0.7
- """
- self.try_trigger_before_first_request_functions()
- try:
- request_started.send(self)
- rv = self.preprocess_request()
- if rv is None:
- rv = self.dispatch_request()
- except Exception as e:
- rv = self.handle_user_exception(e)
- response = self.make_response(rv)
- response = self.process_response(response)
- request_finished.send(self, response=response)
- return response
-
- def try_trigger_before_first_request_functions(self):
- """Called before each request and will ensure that it triggers
- the :attr:`before_first_request_funcs` and only exactly once per
- application instance (which means process usually).
-
- :internal:
- """
- if self._got_first_request:
- return
- with self._before_request_lock:
- if self._got_first_request:
- return
- self._got_first_request = True
- for func in self.before_first_request_funcs:
- func()
-
- def make_default_options_response(self):
- """This method is called to create the default `OPTIONS` response.
- This can be changed through subclassing to change the default
- behavior of `OPTIONS` responses.
-
- .. versionadded:: 0.7
- """
- adapter = _request_ctx_stack.top.url_adapter
- if hasattr(adapter, 'allowed_methods'):
- methods = adapter.allowed_methods()
- else:
- # fallback for Werkzeug < 0.7
- methods = []
- try:
- adapter.match(method='--')
- except MethodNotAllowed as e:
- methods = e.valid_methods
- except HTTPException as e:
- pass
- rv = self.response_class()
- rv.allow.update(methods)
- return rv
-
- def should_ignore_error(self, error):
- """This is called to figure out if an error should be ignored
- or not as far as the teardown system is concerned. If this
- function returns `True` then the teardown handlers will not be
- passed the error.
-
- .. versionadded:: 0.10
- """
- return False
-
- def make_response(self, rv):
- """Converts the return value from a view function to a real
- response object that is an instance of :attr:`response_class`.
-
- The following types are allowed for `rv`:
-
- .. tabularcolumns:: |p{3.5cm}|p{9.5cm}|
-
- ======================= ===========================================
- :attr:`response_class` the object is returned unchanged
- :class:`str` a response object is created with the
- string as body
- :class:`unicode` a response object is created with the
- string encoded to utf-8 as body
- a WSGI function the function is called as WSGI application
- and buffered as response object
- :class:`tuple` A tuple in the form ``(response, status,
- headers)`` where `response` is any of the
- types defined here, `status` is a string
- or an integer and `headers` is a list of
- a dictionary with header values.
- ======================= ===========================================
-
- :param rv: the return value from the view function
-
- .. versionchanged:: 0.9
- Previously a tuple was interpreted as the arguments for the
- response object.
- """
- status = headers = None
- if isinstance(rv, tuple):
- rv, status, headers = rv + (None,) * (3 - len(rv))
-
- if rv is None:
- raise ValueError('View function did not return a response')
-
- if not isinstance(rv, self.response_class):
- # When we create a response object directly, we let the constructor
- # set the headers and status. We do this because there can be
- # some extra logic involved when creating these objects with
- # specific values (like default content type selection).
- if isinstance(rv, (text_type, bytes, bytearray)):
- rv = self.response_class(rv, headers=headers, status=status)
- headers = status = None
- else:
- rv = self.response_class.force_type(rv, request.environ)
-
- if status is not None:
- if isinstance(status, string_types):
- rv.status = status
- else:
- rv.status_code = status
- if headers:
- rv.headers.extend(headers)
-
- return rv
-
- def create_url_adapter(self, request):
- """Creates a URL adapter for the given request. The URL adapter
- is created at a point where the request context is not yet set up
- so the request is passed explicitly.
-
- .. versionadded:: 0.6
-
- .. versionchanged:: 0.9
- This can now also be called without a request object when the
- URL adapter is created for the application context.
- """
- if request is not None:
- return self.url_map.bind_to_environ(request.environ,
- server_name=self.config['SERVER_NAME'])
- # We need at the very least the server name to be set for this
- # to work.
- if self.config['SERVER_NAME'] is not None:
- return self.url_map.bind(
- self.config['SERVER_NAME'],
- script_name=self.config['APPLICATION_ROOT'] or '/',
- url_scheme=self.config['PREFERRED_URL_SCHEME'])
-
- def inject_url_defaults(self, endpoint, values):
- """Injects the URL defaults for the given endpoint directly into
- the values dictionary passed. This is used internally and
- automatically called on URL building.
-
- .. versionadded:: 0.7
- """
- funcs = self.url_default_functions.get(None, ())
- if '.' in endpoint:
- bp = endpoint.rsplit('.', 1)[0]
- funcs = chain(funcs, self.url_default_functions.get(bp, ()))
- for func in funcs:
- func(endpoint, values)
-
- def handle_url_build_error(self, error, endpoint, values):
- """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`.
- """
- exc_type, exc_value, tb = sys.exc_info()
- for handler in self.url_build_error_handlers:
- try:
- rv = handler(error, endpoint, values)
- if rv is not None:
- return rv
- except BuildError as error:
- pass
-
- # At this point we want to reraise the exception. If the error is
- # still the same one we can reraise it with the original traceback,
- # otherwise we raise it from here.
- if error is exc_value:
- reraise(exc_type, exc_value, tb)
- raise error
-
- def preprocess_request(self):
- """Called before the actual request dispatching and will
- call every as :meth:`before_request` decorated function.
- If any of these function returns a value it's handled as
- if it was the return value from the view and further
- request handling is stopped.
-
- This also triggers the :meth:`url_value_processor` functions before
- the actual :meth:`before_request` functions are called.
- """
- bp = _request_ctx_stack.top.request.blueprint
-
- funcs = self.url_value_preprocessors.get(None, ())
- if bp is not None and bp in self.url_value_preprocessors:
- funcs = chain(funcs, self.url_value_preprocessors[bp])
- for func in funcs:
- func(request.endpoint, request.view_args)
-
- funcs = self.before_request_funcs.get(None, ())
- if bp is not None and bp in self.before_request_funcs:
- funcs = chain(funcs, self.before_request_funcs[bp])
- for func in funcs:
- rv = func()
- if rv is not None:
- return rv
-
- def process_response(self, response):
- """Can be overridden in order to modify the response object
- before it's sent to the WSGI server. By default this will
- call all the :meth:`after_request` decorated functions.
-
- .. versionchanged:: 0.5
- As of Flask 0.5 the functions registered for after request
- execution are called in reverse order of registration.
-
- :param response: a :attr:`response_class` object.
- :return: a new response object or the same, has to be an
- instance of :attr:`response_class`.
- """
- ctx = _request_ctx_stack.top
- bp = ctx.request.blueprint
- funcs = ctx._after_request_functions
- if bp is not None and bp in self.after_request_funcs:
- funcs = chain(funcs, reversed(self.after_request_funcs[bp]))
- if None in self.after_request_funcs:
- funcs = chain(funcs, reversed(self.after_request_funcs[None]))
- for handler in funcs:
- response = handler(response)
- if not self.session_interface.is_null_session(ctx.session):
- self.save_session(ctx.session, response)
- return response
-
- def do_teardown_request(self, exc=None):
- """Called after the actual request dispatching and will
- call every as :meth:`teardown_request` decorated function. This is
- not actually called by the :class:`Flask` object itself but is always
- triggered when the request context is popped. That way we have a
- tighter control over certain resources under testing environments.
-
- .. versionchanged:: 0.9
- Added the `exc` argument. Previously this was always using the
- current exception information.
- """
- if exc is None:
- exc = sys.exc_info()[1]
- funcs = reversed(self.teardown_request_funcs.get(None, ()))
- bp = _request_ctx_stack.top.request.blueprint
- if bp is not None and bp in self.teardown_request_funcs:
- funcs = chain(funcs, reversed(self.teardown_request_funcs[bp]))
- for func in funcs:
- rv = func(exc)
- request_tearing_down.send(self, exc=exc)
-
- def do_teardown_appcontext(self, exc=None):
- """Called when an application context is popped. This works pretty
- much the same as :meth:`do_teardown_request` but for the application
- context.
-
- .. versionadded:: 0.9
- """
- if exc is None:
- exc = sys.exc_info()[1]
- for func in reversed(self.teardown_appcontext_funcs):
- func(exc)
- appcontext_tearing_down.send(self, exc=exc)
-
- def app_context(self):
- """Binds the application only. For as long as the application is bound
- to the current context the :data:`flask.current_app` points to that
- application. An application context is automatically created when a
- request context is pushed if necessary.
-
- Example usage::
-
- with app.app_context():
- ...
-
- .. versionadded:: 0.9
- """
- return AppContext(self)
-
- def request_context(self, environ):
- """Creates a :class:`~flask.ctx.RequestContext` from the given
- environment and binds it to the current context. This must be used in
- combination with the `with` statement because the request is only bound
- to the current context for the duration of the `with` block.
-
- Example usage::
-
- with app.request_context(environ):
- do_something_with(request)
-
- The object returned can also be used without the `with` statement
- which is useful for working in the shell. The example above is
- doing exactly the same as this code::
-
- ctx = app.request_context(environ)
- ctx.push()
- try:
- do_something_with(request)
- finally:
- ctx.pop()
-
- .. versionchanged:: 0.3
- Added support for non-with statement usage and `with` statement
- is now passed the ctx object.
-
- :param environ: a WSGI environment
- """
- return RequestContext(self, environ)
-
- def test_request_context(self, *args, **kwargs):
- """Creates a WSGI environment from the given values (see
- :func:`werkzeug.test.EnvironBuilder` for more information, this
- function accepts the same arguments).
- """
- from flask.testing import make_test_environ_builder
- builder = make_test_environ_builder(self, *args, **kwargs)
- try:
- return self.request_context(builder.get_environ())
- finally:
- builder.close()
-
- def wsgi_app(self, environ, start_response):
- """The actual WSGI application. This is not implemented in
- `__call__` so that middlewares can be applied without losing a
- reference to the class. So instead of doing this::
-
- app = MyMiddleware(app)
-
- It's a better idea to do this instead::
-
- app.wsgi_app = MyMiddleware(app.wsgi_app)
-
- Then you still have the original application object around and
- can continue to call methods on it.
-
- .. versionchanged:: 0.7
- The behavior of the before and after request callbacks was changed
- under error conditions and a new callback was added that will
- always execute at the end of the request, independent on if an
- error occurred or not. See :ref:`callbacks-and-errors`.
-
- :param environ: a WSGI environment
- :param start_response: a callable accepting a status code,
- a list of headers and an optional
- exception context to start the response
- """
- ctx = self.request_context(environ)
- ctx.push()
- error = None
- try:
- try:
- response = self.full_dispatch_request()
- except Exception as e:
- error = e
- response = self.make_response(self.handle_exception(e))
- return response(environ, start_response)
- finally:
- if self.should_ignore_error(error):
- error = None
- ctx.auto_pop(error)
-
- @property
- def modules(self):
- from warnings import warn
- warn(DeprecationWarning('Flask.modules is deprecated, use '
- 'Flask.blueprints instead'), stacklevel=2)
- return self.blueprints
-
- def __call__(self, environ, start_response):
- """Shortcut for :attr:`wsgi_app`."""
- return self.wsgi_app(environ, start_response)
-
- def __repr__(self):
- return '<%s %r>' % (
- self.__class__.__name__,
- self.name,
- )
diff --git a/Darwin/lib/python2.7/site-packages/flask/blueprints.py b/Darwin/lib/python2.7/site-packages/flask/blueprints.py
deleted file mode 100644
index 4575ec9..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/blueprints.py
+++ /dev/null
@@ -1,401 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask.blueprints
- ~~~~~~~~~~~~~~~~
-
- Blueprints are the recommended way to implement larger or more
- pluggable applications in Flask 0.7 and later.
-
- :copyright: (c) 2011 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-from functools import update_wrapper
-
-from .helpers import _PackageBoundObject, _endpoint_from_view_func
-
-
-class BlueprintSetupState(object):
- """Temporary holder object for registering a blueprint with the
- application. An instance of this class is created by the
- :meth:`~flask.Blueprint.make_setup_state` method and later passed
- to all register callback functions.
- """
-
- def __init__(self, blueprint, app, options, first_registration):
- #: a reference to the current application
- self.app = app
-
- #: a reference to the blueprint that created this setup state.
- self.blueprint = blueprint
-
- #: a dictionary with all options that were passed to the
- #: :meth:`~flask.Flask.register_blueprint` method.
- self.options = options
-
- #: as blueprints can be registered multiple times with the
- #: application and not everything wants to be registered
- #: multiple times on it, this attribute can be used to figure
- #: out if the blueprint was registered in the past already.
- self.first_registration = first_registration
-
- subdomain = self.options.get('subdomain')
- if subdomain is None:
- subdomain = self.blueprint.subdomain
-
- #: The subdomain that the blueprint should be active for, `None`
- #: otherwise.
- self.subdomain = subdomain
-
- url_prefix = self.options.get('url_prefix')
- if url_prefix is None:
- url_prefix = self.blueprint.url_prefix
-
- #: The prefix that should be used for all URLs defined on the
- #: blueprint.
- self.url_prefix = url_prefix
-
- #: A dictionary with URL defaults that is added to each and every
- #: URL that was defined with the blueprint.
- self.url_defaults = dict(self.blueprint.url_values_defaults)
- self.url_defaults.update(self.options.get('url_defaults', ()))
-
- def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
- """A helper method to register a rule (and optionally a view function)
- to the application. The endpoint is automatically prefixed with the
- blueprint's name.
- """
- if self.url_prefix:
- rule = self.url_prefix + rule
- options.setdefault('subdomain', self.subdomain)
- if endpoint is None:
- endpoint = _endpoint_from_view_func(view_func)
- defaults = self.url_defaults
- if 'defaults' in options:
- defaults = dict(defaults, **options.pop('defaults'))
- self.app.add_url_rule(rule, '%s.%s' % (self.blueprint.name, endpoint),
- view_func, defaults=defaults, **options)
-
-
-class Blueprint(_PackageBoundObject):
- """Represents a blueprint. A blueprint is an object that records
- functions that will be called with the
- :class:`~flask.blueprint.BlueprintSetupState` later to register functions
- or other things on the main application. See :ref:`blueprints` for more
- information.
-
- .. versionadded:: 0.7
- """
-
- warn_on_modifications = False
- _got_registered_once = False
-
- def __init__(self, name, import_name, static_folder=None,
- static_url_path=None, template_folder=None,
- url_prefix=None, subdomain=None, url_defaults=None):
- _PackageBoundObject.__init__(self, import_name, template_folder)
- self.name = name
- self.url_prefix = url_prefix
- self.subdomain = subdomain
- self.static_folder = static_folder
- self.static_url_path = static_url_path
- self.deferred_functions = []
- self.view_functions = {}
- if url_defaults is None:
- url_defaults = {}
- self.url_values_defaults = url_defaults
-
- def record(self, func):
- """Registers a function that is called when the blueprint is
- registered on the application. This function is called with the
- state as argument as returned by the :meth:`make_setup_state`
- method.
- """
- if self._got_registered_once and self.warn_on_modifications:
- from warnings import warn
- warn(Warning('The blueprint was already registered once '
- 'but is getting modified now. These changes '
- 'will not show up.'))
- self.deferred_functions.append(func)
-
- def record_once(self, func):
- """Works like :meth:`record` but wraps the function in another
- function that will ensure the function is only called once. If the
- blueprint is registered a second time on the application, the
- function passed is not called.
- """
- def wrapper(state):
- if state.first_registration:
- func(state)
- return self.record(update_wrapper(wrapper, func))
-
- def make_setup_state(self, app, options, first_registration=False):
- """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`
- object that is later passed to the register callback functions.
- Subclasses can override this to return a subclass of the setup state.
- """
- return BlueprintSetupState(self, app, options, first_registration)
-
- def register(self, app, options, first_registration=False):
- """Called by :meth:`Flask.register_blueprint` to register a blueprint
- on the application. This can be overridden to customize the register
- behavior. Keyword arguments from
- :func:`~flask.Flask.register_blueprint` are directly forwarded to this
- method in the `options` dictionary.
- """
- self._got_registered_once = True
- state = self.make_setup_state(app, options, first_registration)
- if self.has_static_folder:
- state.add_url_rule(self.static_url_path + '/',
- view_func=self.send_static_file,
- endpoint='static')
-
- for deferred in self.deferred_functions:
- deferred(state)
-
- def route(self, rule, **options):
- """Like :meth:`Flask.route` but for a blueprint. The endpoint for the
- :func:`url_for` function is prefixed with the name of the blueprint.
- """
- def decorator(f):
- endpoint = options.pop("endpoint", f.__name__)
- self.add_url_rule(rule, endpoint, f, **options)
- return f
- return decorator
-
- def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
- """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for
- the :func:`url_for` function is prefixed with the name of the blueprint.
- """
- if endpoint:
- assert '.' not in endpoint, "Blueprint endpoint's should not contain dot's"
- self.record(lambda s:
- s.add_url_rule(rule, endpoint, view_func, **options))
-
- def endpoint(self, endpoint):
- """Like :meth:`Flask.endpoint` but for a blueprint. This does not
- prefix the endpoint with the blueprint name, this has to be done
- explicitly by the user of this method. If the endpoint is prefixed
- with a `.` it will be registered to the current blueprint, otherwise
- it's an application independent endpoint.
- """
- def decorator(f):
- def register_endpoint(state):
- state.app.view_functions[endpoint] = f
- self.record_once(register_endpoint)
- return f
- return decorator
-
- def app_template_filter(self, name=None):
- """Register a custom template filter, available application wide. Like
- :meth:`Flask.template_filter` but for a blueprint.
-
- :param name: the optional name of the filter, otherwise the
- function name will be used.
- """
- def decorator(f):
- self.add_app_template_filter(f, name=name)
- return f
- return decorator
-
- def add_app_template_filter(self, f, name=None):
- """Register a custom template filter, available application wide. Like
- :meth:`Flask.add_template_filter` but for a blueprint. Works exactly
- like the :meth:`app_template_filter` decorator.
-
- :param name: the optional name of the filter, otherwise the
- function name will be used.
- """
- def register_template(state):
- state.app.jinja_env.filters[name or f.__name__] = f
- self.record_once(register_template)
-
- def app_template_test(self, name=None):
- """Register a custom template test, available application wide. Like
- :meth:`Flask.template_test` but for a blueprint.
-
- .. versionadded:: 0.10
-
- :param name: the optional name of the test, otherwise the
- function name will be used.
- """
- def decorator(f):
- self.add_app_template_test(f, name=name)
- return f
- return decorator
-
- def add_app_template_test(self, f, name=None):
- """Register a custom template test, available application wide. Like
- :meth:`Flask.add_template_test` but for a blueprint. Works exactly
- like the :meth:`app_template_test` decorator.
-
- .. versionadded:: 0.10
-
- :param name: the optional name of the test, otherwise the
- function name will be used.
- """
- def register_template(state):
- state.app.jinja_env.tests[name or f.__name__] = f
- self.record_once(register_template)
-
- def app_template_global(self, name=None):
- """Register a custom template global, available application wide. Like
- :meth:`Flask.template_global` but for a blueprint.
-
- .. versionadded:: 0.10
-
- :param name: the optional name of the global, otherwise the
- function name will be used.
- """
- def decorator(f):
- self.add_app_template_global(f, name=name)
- return f
- return decorator
-
- def add_app_template_global(self, f, name=None):
- """Register a custom template global, available application wide. Like
- :meth:`Flask.add_template_global` but for a blueprint. Works exactly
- like the :meth:`app_template_global` decorator.
-
- .. versionadded:: 0.10
-
- :param name: the optional name of the global, otherwise the
- function name will be used.
- """
- def register_template(state):
- state.app.jinja_env.globals[name or f.__name__] = f
- self.record_once(register_template)
-
- def before_request(self, f):
- """Like :meth:`Flask.before_request` but for a blueprint. This function
- is only executed before each request that is handled by a function of
- that blueprint.
- """
- self.record_once(lambda s: s.app.before_request_funcs
- .setdefault(self.name, []).append(f))
- return f
-
- def before_app_request(self, f):
- """Like :meth:`Flask.before_request`. Such a function is executed
- before each request, even if outside of a blueprint.
- """
- self.record_once(lambda s: s.app.before_request_funcs
- .setdefault(None, []).append(f))
- return f
-
- def before_app_first_request(self, f):
- """Like :meth:`Flask.before_first_request`. Such a function is
- executed before the first request to the application.
- """
- self.record_once(lambda s: s.app.before_first_request_funcs.append(f))
- return f
-
- def after_request(self, f):
- """Like :meth:`Flask.after_request` but for a blueprint. This function
- is only executed after each request that is handled by a function of
- that blueprint.
- """
- self.record_once(lambda s: s.app.after_request_funcs
- .setdefault(self.name, []).append(f))
- return f
-
- def after_app_request(self, f):
- """Like :meth:`Flask.after_request` but for a blueprint. Such a function
- is executed after each request, even if outside of the blueprint.
- """
- self.record_once(lambda s: s.app.after_request_funcs
- .setdefault(None, []).append(f))
- return f
-
- def teardown_request(self, f):
- """Like :meth:`Flask.teardown_request` but for a blueprint. This
- function is only executed when tearing down requests handled by a
- function of that blueprint. Teardown request functions are executed
- when the request context is popped, even when no actual request was
- performed.
- """
- self.record_once(lambda s: s.app.teardown_request_funcs
- .setdefault(self.name, []).append(f))
- return f
-
- def teardown_app_request(self, f):
- """Like :meth:`Flask.teardown_request` but for a blueprint. Such a
- function is executed when tearing down each request, even if outside of
- the blueprint.
- """
- self.record_once(lambda s: s.app.teardown_request_funcs
- .setdefault(None, []).append(f))
- return f
-
- def context_processor(self, f):
- """Like :meth:`Flask.context_processor` but for a blueprint. This
- function is only executed for requests handled by a blueprint.
- """
- self.record_once(lambda s: s.app.template_context_processors
- .setdefault(self.name, []).append(f))
- return f
-
- def app_context_processor(self, f):
- """Like :meth:`Flask.context_processor` but for a blueprint. Such a
- function is executed each request, even if outside of the blueprint.
- """
- self.record_once(lambda s: s.app.template_context_processors
- .setdefault(None, []).append(f))
- return f
-
- def app_errorhandler(self, code):
- """Like :meth:`Flask.errorhandler` but for a blueprint. This
- handler is used for all requests, even if outside of the blueprint.
- """
- def decorator(f):
- self.record_once(lambda s: s.app.errorhandler(code)(f))
- return f
- return decorator
-
- def url_value_preprocessor(self, f):
- """Registers a function as URL value preprocessor for this
- blueprint. It's called before the view functions are called and
- can modify the url values provided.
- """
- self.record_once(lambda s: s.app.url_value_preprocessors
- .setdefault(self.name, []).append(f))
- return f
-
- def url_defaults(self, f):
- """Callback function for URL defaults for this blueprint. It's called
- with the endpoint and values and should update the values passed
- in place.
- """
- self.record_once(lambda s: s.app.url_default_functions
- .setdefault(self.name, []).append(f))
- return f
-
- def app_url_value_preprocessor(self, f):
- """Same as :meth:`url_value_preprocessor` but application wide.
- """
- self.record_once(lambda s: s.app.url_value_preprocessors
- .setdefault(None, []).append(f))
- return f
-
- def app_url_defaults(self, f):
- """Same as :meth:`url_defaults` but application wide.
- """
- self.record_once(lambda s: s.app.url_default_functions
- .setdefault(None, []).append(f))
- return f
-
- def errorhandler(self, code_or_exception):
- """Registers an error handler that becomes active for this blueprint
- only. Please be aware that routing does not happen local to a
- blueprint so an error handler for 404 usually is not handled by
- a blueprint unless it is caused inside a view function. Another
- special case is the 500 internal server error which is always looked
- up from the application.
-
- Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator
- of the :class:`~flask.Flask` object.
- """
- def decorator(f):
- self.record_once(lambda s: s.app._register_error_handler(
- self.name, code_or_exception, f))
- return f
- return decorator
diff --git a/Darwin/lib/python2.7/site-packages/flask/config.py b/Darwin/lib/python2.7/site-packages/flask/config.py
deleted file mode 100644
index 155afa2..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/config.py
+++ /dev/null
@@ -1,168 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask.config
- ~~~~~~~~~~~~
-
- Implements the configuration related objects.
-
- :copyright: (c) 2011 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-
-import imp
-import os
-import errno
-
-from werkzeug.utils import import_string
-from ._compat import string_types
-
-
-class ConfigAttribute(object):
- """Makes an attribute forward to the config"""
-
- def __init__(self, name, get_converter=None):
- self.__name__ = name
- self.get_converter = get_converter
-
- def __get__(self, obj, type=None):
- if obj is None:
- return self
- rv = obj.config[self.__name__]
- if self.get_converter is not None:
- rv = self.get_converter(rv)
- return rv
-
- def __set__(self, obj, value):
- obj.config[self.__name__] = value
-
-
-class Config(dict):
- """Works exactly like a dict but provides ways to fill it from files
- or special dictionaries. There are two common patterns to populate the
- config.
-
- Either you can fill the config from a config file::
-
- app.config.from_pyfile('yourconfig.cfg')
-
- Or alternatively you can define the configuration options in the
- module that calls :meth:`from_object` or provide an import path to
- a module that should be loaded. It is also possible to tell it to
- use the same module and with that provide the configuration values
- just before the call::
-
- DEBUG = True
- SECRET_KEY = 'development key'
- app.config.from_object(__name__)
-
- In both cases (loading from any Python file or loading from modules),
- only uppercase keys are added to the config. This makes it possible to use
- lowercase values in the config file for temporary values that are not added
- to the config or to define the config keys in the same file that implements
- the application.
-
- Probably the most interesting way to load configurations is from an
- environment variable pointing to a file::
-
- app.config.from_envvar('YOURAPPLICATION_SETTINGS')
-
- In this case before launching the application you have to set this
- environment variable to the file you want to use. On Linux and OS X
- use the export statement::
-
- export YOURAPPLICATION_SETTINGS='/path/to/config/file'
-
- On windows use `set` instead.
-
- :param root_path: path to which files are read relative from. When the
- config object is created by the application, this is
- the application's :attr:`~flask.Flask.root_path`.
- :param defaults: an optional dictionary of default values
- """
-
- def __init__(self, root_path, defaults=None):
- dict.__init__(self, defaults or {})
- self.root_path = root_path
-
- def from_envvar(self, variable_name, silent=False):
- """Loads a configuration from an environment variable pointing to
- a configuration file. This is basically just a shortcut with nicer
- error messages for this line of code::
-
- app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS'])
-
- :param variable_name: name of the environment variable
- :param silent: set to `True` if you want silent failure for missing
- files.
- :return: bool. `True` if able to load config, `False` otherwise.
- """
- rv = os.environ.get(variable_name)
- if not rv:
- if silent:
- return False
- raise RuntimeError('The environment variable %r is not set '
- 'and as such configuration could not be '
- 'loaded. Set this variable and make it '
- 'point to a configuration file' %
- variable_name)
- return self.from_pyfile(rv, silent=silent)
-
- def from_pyfile(self, filename, silent=False):
- """Updates the values in the config from a Python file. This function
- behaves as if the file was imported as module with the
- :meth:`from_object` function.
-
- :param filename: the filename of the config. This can either be an
- absolute filename or a filename relative to the
- root path.
- :param silent: set to `True` if you want silent failure for missing
- files.
-
- .. versionadded:: 0.7
- `silent` parameter.
- """
- filename = os.path.join(self.root_path, filename)
- d = imp.new_module('config')
- d.__file__ = filename
- try:
- with open(filename) as config_file:
- exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
- except IOError as e:
- if silent and e.errno in (errno.ENOENT, errno.EISDIR):
- return False
- e.strerror = 'Unable to load configuration file (%s)' % e.strerror
- raise
- self.from_object(d)
- return True
-
- def from_object(self, obj):
- """Updates the values from the given object. An object can be of one
- of the following two types:
-
- - a string: in this case the object with that name will be imported
- - an actual object reference: that object is used directly
-
- Objects are usually either modules or classes.
-
- Just the uppercase variables in that object are stored in the config.
- Example usage::
-
- app.config.from_object('yourapplication.default_config')
- from yourapplication import default_config
- app.config.from_object(default_config)
-
- You should not use this function to load the actual configuration but
- rather configuration defaults. The actual config should be loaded
- with :meth:`from_pyfile` and ideally from a location not within the
- package because the package might be installed system wide.
-
- :param obj: an import name or object
- """
- if isinstance(obj, string_types):
- obj = import_string(obj)
- for key in dir(obj):
- if key.isupper():
- self[key] = getattr(obj, key)
-
- def __repr__(self):
- return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))
diff --git a/Darwin/lib/python2.7/site-packages/flask/ctx.py b/Darwin/lib/python2.7/site-packages/flask/ctx.py
deleted file mode 100644
index f134237..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/ctx.py
+++ /dev/null
@@ -1,394 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask.ctx
- ~~~~~~~~~
-
- Implements the objects required to keep the context.
-
- :copyright: (c) 2011 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-
-from __future__ import with_statement
-
-import sys
-from functools import update_wrapper
-
-from werkzeug.exceptions import HTTPException
-
-from .globals import _request_ctx_stack, _app_ctx_stack
-from .module import blueprint_is_module
-from .signals import appcontext_pushed, appcontext_popped
-
-
-class _AppCtxGlobals(object):
- """A plain object."""
-
- def get(self, name, default=None):
- return self.__dict__.get(name, default)
-
- def __contains__(self, item):
- return item in self.__dict__
-
- def __iter__(self):
- return iter(self.__dict__)
-
- def __repr__(self):
- top = _app_ctx_stack.top
- if top is not None:
- return '' % top.app.name
- return object.__repr__(self)
-
-
-def after_this_request(f):
- """Executes a function after this request. This is useful to modify
- response objects. The function is passed the response object and has
- to return the same or a new one.
-
- Example::
-
- @app.route('/')
- def index():
- @after_this_request
- def add_header(response):
- response.headers['X-Foo'] = 'Parachute'
- return response
- return 'Hello World!'
-
- This is more useful if a function other than the view function wants to
- modify a response. For instance think of a decorator that wants to add
- some headers without converting the return value into a response object.
-
- .. versionadded:: 0.9
- """
- _request_ctx_stack.top._after_request_functions.append(f)
- return f
-
-
-def copy_current_request_context(f):
- """A helper function that decorates a function to retain the current
- request context. This is useful when working with greenlets. The moment
- the function is decorated a copy of the request context is created and
- then pushed when the function is called.
-
- Example::
-
- import gevent
- from flask import copy_current_request_context
-
- @app.route('/')
- def index():
- @copy_current_request_context
- def do_some_work():
- # do some work here, it can access flask.request like you
- # would otherwise in the view function.
- ...
- gevent.spawn(do_some_work)
- return 'Regular response'
-
- .. versionadded:: 0.10
- """
- top = _request_ctx_stack.top
- if top is None:
- raise RuntimeError('This decorator can only be used at local scopes '
- 'when a request context is on the stack. For instance within '
- 'view functions.')
- reqctx = top.copy()
- def wrapper(*args, **kwargs):
- with reqctx:
- return f(*args, **kwargs)
- return update_wrapper(wrapper, f)
-
-
-def has_request_context():
- """If you have code that wants to test if a request context is there or
- not this function can be used. For instance, you may want to take advantage
- of request information if the request object is available, but fail
- silently if it is unavailable.
-
- ::
-
- class User(db.Model):
-
- def __init__(self, username, remote_addr=None):
- self.username = username
- if remote_addr is None and has_request_context():
- remote_addr = request.remote_addr
- self.remote_addr = remote_addr
-
- Alternatively you can also just test any of the context bound objects
- (such as :class:`request` or :class:`g` for truthness)::
-
- class User(db.Model):
-
- def __init__(self, username, remote_addr=None):
- self.username = username
- if remote_addr is None and request:
- remote_addr = request.remote_addr
- self.remote_addr = remote_addr
-
- .. versionadded:: 0.7
- """
- return _request_ctx_stack.top is not None
-
-
-def has_app_context():
- """Works like :func:`has_request_context` but for the application
- context. You can also just do a boolean check on the
- :data:`current_app` object instead.
-
- .. versionadded:: 0.9
- """
- return _app_ctx_stack.top is not None
-
-
-class AppContext(object):
- """The application context binds an application object implicitly
- to the current thread or greenlet, similar to how the
- :class:`RequestContext` binds request information. The application
- context is also implicitly created if a request context is created
- but the application is not on top of the individual application
- context.
- """
-
- def __init__(self, app):
- self.app = app
- self.url_adapter = app.create_url_adapter(None)
- self.g = app.app_ctx_globals_class()
-
- # Like request context, app contexts can be pushed multiple times
- # but there a basic "refcount" is enough to track them.
- self._refcnt = 0
-
- def push(self):
- """Binds the app context to the current context."""
- self._refcnt += 1
- _app_ctx_stack.push(self)
- appcontext_pushed.send(self.app)
-
- def pop(self, exc=None):
- """Pops the app context."""
- self._refcnt -= 1
- if self._refcnt <= 0:
- if exc is None:
- exc = sys.exc_info()[1]
- self.app.do_teardown_appcontext(exc)
- rv = _app_ctx_stack.pop()
- assert rv is self, 'Popped wrong app context. (%r instead of %r)' \
- % (rv, self)
- appcontext_popped.send(self.app)
-
- def __enter__(self):
- self.push()
- return self
-
- def __exit__(self, exc_type, exc_value, tb):
- self.pop(exc_value)
-
-
-class RequestContext(object):
- """The request context contains all request relevant information. It is
- created at the beginning of the request and pushed to the
- `_request_ctx_stack` and removed at the end of it. It will create the
- URL adapter and request object for the WSGI environment provided.
-
- Do not attempt to use this class directly, instead use
- :meth:`~flask.Flask.test_request_context` and
- :meth:`~flask.Flask.request_context` to create this object.
-
- When the request context is popped, it will evaluate all the
- functions registered on the application for teardown execution
- (:meth:`~flask.Flask.teardown_request`).
-
- The request context is automatically popped at the end of the request
- for you. In debug mode the request context is kept around if
- exceptions happen so that interactive debuggers have a chance to
- introspect the data. With 0.4 this can also be forced for requests
- that did not fail and outside of `DEBUG` mode. By setting
- ``'flask._preserve_context'`` to `True` on the WSGI environment the
- context will not pop itself at the end of the request. This is used by
- the :meth:`~flask.Flask.test_client` for example to implement the
- deferred cleanup functionality.
-
- You might find this helpful for unittests where you need the
- information from the context local around for a little longer. Make
- sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in
- that situation, otherwise your unittests will leak memory.
- """
-
- def __init__(self, app, environ, request=None):
- self.app = app
- if request is None:
- request = app.request_class(environ)
- self.request = request
- self.url_adapter = app.create_url_adapter(self.request)
- self.flashes = None
- self.session = None
-
- # Request contexts can be pushed multiple times and interleaved with
- # other request contexts. Now only if the last level is popped we
- # get rid of them. Additionally if an application context is missing
- # one is created implicitly so for each level we add this information
- self._implicit_app_ctx_stack = []
-
- # indicator if the context was preserved. Next time another context
- # is pushed the preserved context is popped.
- self.preserved = False
-
- # remembers the exception for pop if there is one in case the context
- # preservation kicks in.
- self._preserved_exc = None
-
- # Functions that should be executed after the request on the response
- # object. These will be called before the regular "after_request"
- # functions.
- self._after_request_functions = []
-
- self.match_request()
-
- # XXX: Support for deprecated functionality. This is going away with
- # Flask 1.0
- blueprint = self.request.blueprint
- if blueprint is not None:
- # better safe than sorry, we don't want to break code that
- # already worked
- bp = app.blueprints.get(blueprint)
- if bp is not None and blueprint_is_module(bp):
- self.request._is_old_module = True
-
- def _get_g(self):
- return _app_ctx_stack.top.g
- def _set_g(self, value):
- _app_ctx_stack.top.g = value
- g = property(_get_g, _set_g)
- del _get_g, _set_g
-
- def copy(self):
- """Creates a copy of this request context with the same request object.
- This can be used to move a request context to a different greenlet.
- Because the actual request object is the same this cannot be used to
- move a request context to a different thread unless access to the
- request object is locked.
-
- .. versionadded:: 0.10
- """
- return self.__class__(self.app,
- environ=self.request.environ,
- request=self.request
- )
-
- def match_request(self):
- """Can be overridden by a subclass to hook into the matching
- of the request.
- """
- try:
- url_rule, self.request.view_args = \
- self.url_adapter.match(return_rule=True)
- self.request.url_rule = url_rule
- except HTTPException as e:
- self.request.routing_exception = e
-
- def push(self):
- """Binds the request context to the current context."""
- # If an exception occurs in debug mode or if context preservation is
- # activated under exception situations exactly one context stays
- # on the stack. The rationale is that you want to access that
- # information under debug situations. However if someone forgets to
- # pop that context again we want to make sure that on the next push
- # it's invalidated, otherwise we run at risk that something leaks
- # memory. This is usually only a problem in testsuite since this
- # functionality is not active in production environments.
- top = _request_ctx_stack.top
- if top is not None and top.preserved:
- top.pop(top._preserved_exc)
-
- # Before we push the request context we have to ensure that there
- # is an application context.
- app_ctx = _app_ctx_stack.top
- if app_ctx is None or app_ctx.app != self.app:
- app_ctx = self.app.app_context()
- app_ctx.push()
- self._implicit_app_ctx_stack.append(app_ctx)
- else:
- self._implicit_app_ctx_stack.append(None)
-
- _request_ctx_stack.push(self)
-
- # Open the session at the moment that the request context is
- # available. This allows a custom open_session method to use the
- # request context (e.g. code that access database information
- # stored on `g` instead of the appcontext).
- self.session = self.app.open_session(self.request)
- if self.session is None:
- self.session = self.app.make_null_session()
-
- def pop(self, exc=None):
- """Pops the request context and unbinds it by doing that. This will
- also trigger the execution of functions registered by the
- :meth:`~flask.Flask.teardown_request` decorator.
-
- .. versionchanged:: 0.9
- Added the `exc` argument.
- """
- app_ctx = self._implicit_app_ctx_stack.pop()
-
- clear_request = False
- if not self._implicit_app_ctx_stack:
- self.preserved = False
- self._preserved_exc = None
- if exc is None:
- exc = sys.exc_info()[1]
- self.app.do_teardown_request(exc)
-
- # If this interpreter supports clearing the exception information
- # we do that now. This will only go into effect on Python 2.x,
- # on 3.x it disappears automatically at the end of the exception
- # stack.
- if hasattr(sys, 'exc_clear'):
- sys.exc_clear()
-
- request_close = getattr(self.request, 'close', None)
- if request_close is not None:
- request_close()
- clear_request = True
-
- rv = _request_ctx_stack.pop()
- assert rv is self, 'Popped wrong request context. (%r instead of %r)' \
- % (rv, self)
-
- # get rid of circular dependencies at the end of the request
- # so that we don't require the GC to be active.
- if clear_request:
- rv.request.environ['werkzeug.request'] = None
-
- # Get rid of the app as well if necessary.
- if app_ctx is not None:
- app_ctx.pop(exc)
-
- def auto_pop(self, exc):
- if self.request.environ.get('flask._preserve_context') or \
- (exc is not None and self.app.preserve_context_on_exception):
- self.preserved = True
- self._preserved_exc = exc
- else:
- self.pop(exc)
-
- def __enter__(self):
- self.push()
- return self
-
- def __exit__(self, exc_type, exc_value, tb):
- # do not pop the request stack if we are in debug mode and an
- # exception happened. This will allow the debugger to still
- # access the request object in the interactive shell. Furthermore
- # the context can be force kept alive for the test client.
- # See flask.testing for how this works.
- self.auto_pop(exc_value)
-
- def __repr__(self):
- return '<%s \'%s\' [%s] of %s>' % (
- self.__class__.__name__,
- self.request.url,
- self.request.method,
- self.app.name,
- )
diff --git a/Darwin/lib/python2.7/site-packages/flask/debughelpers.py b/Darwin/lib/python2.7/site-packages/flask/debughelpers.py
deleted file mode 100644
index 2f8510f..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/debughelpers.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask.debughelpers
- ~~~~~~~~~~~~~~~~~~
-
- Various helpers to make the development experience better.
-
- :copyright: (c) 2011 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-from ._compat import implements_to_string
-
-
-class UnexpectedUnicodeError(AssertionError, UnicodeError):
- """Raised in places where we want some better error reporting for
- unexpected unicode or binary data.
- """
-
-
-@implements_to_string
-class DebugFilesKeyError(KeyError, AssertionError):
- """Raised from request.files during debugging. The idea is that it can
- provide a better error message than just a generic KeyError/BadRequest.
- """
-
- def __init__(self, request, key):
- form_matches = request.form.getlist(key)
- buf = ['You tried to access the file "%s" in the request.files '
- 'dictionary but it does not exist. The mimetype for the request '
- 'is "%s" instead of "multipart/form-data" which means that no '
- 'file contents were transmitted. To fix this error you should '
- 'provide enctype="multipart/form-data" in your form.' %
- (key, request.mimetype)]
- if form_matches:
- buf.append('\n\nThe browser instead transmitted some file names. '
- 'This was submitted: %s' % ', '.join('"%s"' % x
- for x in form_matches))
- self.msg = ''.join(buf)
-
- def __str__(self):
- return self.msg
-
-
-class FormDataRoutingRedirect(AssertionError):
- """This exception is raised by Flask in debug mode if it detects a
- redirect caused by the routing system when the request method is not
- GET, HEAD or OPTIONS. Reasoning: form data will be dropped.
- """
-
- def __init__(self, request):
- exc = request.routing_exception
- buf = ['A request was sent to this URL (%s) but a redirect was '
- 'issued automatically by the routing system to "%s".'
- % (request.url, exc.new_url)]
-
- # In case just a slash was appended we can be extra helpful
- if request.base_url + '/' == exc.new_url.split('?')[0]:
- buf.append(' The URL was defined with a trailing slash so '
- 'Flask will automatically redirect to the URL '
- 'with the trailing slash if it was accessed '
- 'without one.')
-
- buf.append(' Make sure to directly send your %s-request to this URL '
- 'since we can\'t make browsers or HTTP clients redirect '
- 'with form data reliably or without user interaction.' %
- request.method)
- buf.append('\n\nNote: this exception is only raised in debug mode')
- AssertionError.__init__(self, ''.join(buf).encode('utf-8'))
-
-
-def attach_enctype_error_multidict(request):
- """Since Flask 0.8 we're monkeypatching the files object in case a
- request is detected that does not use multipart form data but the files
- object is accessed.
- """
- oldcls = request.files.__class__
- class newcls(oldcls):
- def __getitem__(self, key):
- try:
- return oldcls.__getitem__(self, key)
- except KeyError as e:
- if key not in request.form:
- raise
- raise DebugFilesKeyError(request, key)
- newcls.__name__ = oldcls.__name__
- newcls.__module__ = oldcls.__module__
- request.files.__class__ = newcls
diff --git a/Darwin/lib/python2.7/site-packages/flask/ext/__init__.py b/Darwin/lib/python2.7/site-packages/flask/ext/__init__.py
deleted file mode 100644
index f29958a..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/ext/__init__.py
+++ /dev/null
@@ -1,29 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask.ext
- ~~~~~~~~~
-
- Redirect imports for extensions. This module basically makes it possible
- for us to transition from flaskext.foo to flask_foo without having to
- force all extensions to upgrade at the same time.
-
- When a user does ``from flask.ext.foo import bar`` it will attempt to
- import ``from flask_foo import bar`` first and when that fails it will
- try to import ``from flaskext.foo import bar``.
-
- We're switching from namespace packages because it was just too painful for
- everybody involved.
-
- :copyright: (c) 2011 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-
-
-def setup():
- from ..exthook import ExtensionImporter
- importer = ExtensionImporter(['flask_%s', 'flaskext.%s'], __name__)
- importer.install()
-
-
-setup()
-del setup
diff --git a/Darwin/lib/python2.7/site-packages/flask/exthook.py b/Darwin/lib/python2.7/site-packages/flask/exthook.py
deleted file mode 100644
index d0d814c..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/exthook.py
+++ /dev/null
@@ -1,120 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask.exthook
- ~~~~~~~~~~~~~
-
- Redirect imports for extensions. This module basically makes it possible
- for us to transition from flaskext.foo to flask_foo without having to
- force all extensions to upgrade at the same time.
-
- When a user does ``from flask.ext.foo import bar`` it will attempt to
- import ``from flask_foo import bar`` first and when that fails it will
- try to import ``from flaskext.foo import bar``.
-
- We're switching from namespace packages because it was just too painful for
- everybody involved.
-
- This is used by `flask.ext`.
-
- :copyright: (c) 2011 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-import sys
-import os
-from ._compat import reraise
-
-
-class ExtensionImporter(object):
- """This importer redirects imports from this submodule to other locations.
- This makes it possible to transition from the old flaskext.name to the
- newer flask_name without people having a hard time.
- """
-
- def __init__(self, module_choices, wrapper_module):
- self.module_choices = module_choices
- self.wrapper_module = wrapper_module
- self.prefix = wrapper_module + '.'
- self.prefix_cutoff = wrapper_module.count('.') + 1
-
- def __eq__(self, other):
- return self.__class__.__module__ == other.__class__.__module__ and \
- self.__class__.__name__ == other.__class__.__name__ and \
- self.wrapper_module == other.wrapper_module and \
- self.module_choices == other.module_choices
-
- def __ne__(self, other):
- return not self.__eq__(other)
-
- def install(self):
- sys.meta_path[:] = [x for x in sys.meta_path if self != x] + [self]
-
- def find_module(self, fullname, path=None):
- if fullname.startswith(self.prefix):
- return self
-
- def load_module(self, fullname):
- if fullname in sys.modules:
- return sys.modules[fullname]
- modname = fullname.split('.', self.prefix_cutoff)[self.prefix_cutoff]
- for path in self.module_choices:
- realname = path % modname
- try:
- __import__(realname)
- except ImportError:
- exc_type, exc_value, tb = sys.exc_info()
- # since we only establish the entry in sys.modules at the
- # very this seems to be redundant, but if recursive imports
- # happen we will call into the move import a second time.
- # On the second invocation we still don't have an entry for
- # fullname in sys.modules, but we will end up with the same
- # fake module name and that import will succeed since this
- # one already has a temporary entry in the modules dict.
- # Since this one "succeeded" temporarily that second
- # invocation now will have created a fullname entry in
- # sys.modules which we have to kill.
- sys.modules.pop(fullname, None)
-
- # If it's an important traceback we reraise it, otherwise
- # we swallow it and try the next choice. The skipped frame
- # is the one from __import__ above which we don't care about
- if self.is_important_traceback(realname, tb):
- reraise(exc_type, exc_value, tb.tb_next)
- continue
- module = sys.modules[fullname] = sys.modules[realname]
- if '.' not in modname:
- setattr(sys.modules[self.wrapper_module], modname, module)
- return module
- raise ImportError('No module named %s' % fullname)
-
- def is_important_traceback(self, important_module, tb):
- """Walks a traceback's frames and checks if any of the frames
- originated in the given important module. If that is the case then we
- were able to import the module itself but apparently something went
- wrong when the module was imported. (Eg: import of an import failed).
- """
- while tb is not None:
- if self.is_important_frame(important_module, tb):
- return True
- tb = tb.tb_next
- return False
-
- def is_important_frame(self, important_module, tb):
- """Checks a single frame if it's important."""
- g = tb.tb_frame.f_globals
- if '__name__' not in g:
- return False
-
- module_name = g['__name__']
-
- # Python 2.7 Behavior. Modules are cleaned up late so the
- # name shows up properly here. Success!
- if module_name == important_module:
- return True
-
- # Some python versions will will clean up modules so early that the
- # module name at that point is no longer set. Try guessing from
- # the filename then.
- filename = os.path.abspath(tb.tb_frame.f_code.co_filename)
- test_string = os.path.sep + important_module.replace('.', os.path.sep)
- return test_string + '.py' in filename or \
- test_string + os.path.sep + '__init__.py' in filename
diff --git a/Darwin/lib/python2.7/site-packages/flask/globals.py b/Darwin/lib/python2.7/site-packages/flask/globals.py
deleted file mode 100644
index 67d41f5..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/globals.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask.globals
- ~~~~~~~~~~~~~
-
- Defines all the global objects that are proxies to the current
- active context.
-
- :copyright: (c) 2011 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-
-from functools import partial
-from werkzeug.local import LocalStack, LocalProxy
-
-
-def _lookup_req_object(name):
- top = _request_ctx_stack.top
- if top is None:
- raise RuntimeError('working outside of request context')
- return getattr(top, name)
-
-
-def _lookup_app_object(name):
- top = _app_ctx_stack.top
- if top is None:
- raise RuntimeError('working outside of application context')
- return getattr(top, name)
-
-
-def _find_app():
- top = _app_ctx_stack.top
- if top is None:
- raise RuntimeError('working outside of application context')
- return top.app
-
-
-# context locals
-_request_ctx_stack = LocalStack()
-_app_ctx_stack = LocalStack()
-current_app = LocalProxy(_find_app)
-request = LocalProxy(partial(_lookup_req_object, 'request'))
-session = LocalProxy(partial(_lookup_req_object, 'session'))
-g = LocalProxy(partial(_lookup_app_object, 'g'))
diff --git a/Darwin/lib/python2.7/site-packages/flask/helpers.py b/Darwin/lib/python2.7/site-packages/flask/helpers.py
deleted file mode 100644
index 1e7c87f..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/helpers.py
+++ /dev/null
@@ -1,849 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask.helpers
- ~~~~~~~~~~~~~
-
- Implements various helpers.
-
- :copyright: (c) 2011 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-
-import os
-import sys
-import pkgutil
-import posixpath
-import mimetypes
-from time import time
-from zlib import adler32
-from threading import RLock
-from werkzeug.routing import BuildError
-from functools import update_wrapper
-
-try:
- from werkzeug.urls import url_quote
-except ImportError:
- from urlparse import quote as url_quote
-
-from werkzeug.datastructures import Headers
-from werkzeug.exceptions import NotFound
-
-# this was moved in 0.7
-try:
- from werkzeug.wsgi import wrap_file
-except ImportError:
- from werkzeug.utils import wrap_file
-
-from jinja2 import FileSystemLoader
-
-from .signals import message_flashed
-from .globals import session, _request_ctx_stack, _app_ctx_stack, \
- current_app, request
-from ._compat import string_types, text_type
-
-
-# sentinel
-_missing = object()
-
-
-# what separators does this operating system provide that are not a slash?
-# this is used by the send_from_directory function to ensure that nobody is
-# able to access files from outside the filesystem.
-_os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]
- if sep not in (None, '/'))
-
-
-def _endpoint_from_view_func(view_func):
- """Internal helper that returns the default endpoint for a given
- function. This always is the function name.
- """
- assert view_func is not None, 'expected view func if endpoint ' \
- 'is not provided.'
- return view_func.__name__
-
-
-def stream_with_context(generator_or_function):
- """Request contexts disappear when the response is started on the server.
- This is done for efficiency reasons and to make it less likely to encounter
- memory leaks with badly written WSGI middlewares. The downside is that if
- you are using streamed responses, the generator cannot access request bound
- information any more.
-
- This function however can help you keep the context around for longer::
-
- from flask import stream_with_context, request, Response
-
- @app.route('/stream')
- def streamed_response():
- @stream_with_context
- def generate():
- yield 'Hello '
- yield request.args['name']
- yield '!'
- return Response(generate())
-
- Alternatively it can also be used around a specific generator::
-
- from flask import stream_with_context, request, Response
-
- @app.route('/stream')
- def streamed_response():
- def generate():
- yield 'Hello '
- yield request.args['name']
- yield '!'
- return Response(stream_with_context(generate()))
-
- .. versionadded:: 0.9
- """
- try:
- gen = iter(generator_or_function)
- except TypeError:
- def decorator(*args, **kwargs):
- gen = generator_or_function()
- return stream_with_context(gen)
- return update_wrapper(decorator, generator_or_function)
-
- def generator():
- ctx = _request_ctx_stack.top
- if ctx is None:
- raise RuntimeError('Attempted to stream with context but '
- 'there was no context in the first place to keep around.')
- with ctx:
- # Dummy sentinel. Has to be inside the context block or we're
- # not actually keeping the context around.
- yield None
-
- # The try/finally is here so that if someone passes a WSGI level
- # iterator in we're still running the cleanup logic. Generators
- # don't need that because they are closed on their destruction
- # automatically.
- try:
- for item in gen:
- yield item
- finally:
- if hasattr(gen, 'close'):
- gen.close()
-
- # The trick is to start the generator. Then the code execution runs until
- # the first dummy None is yielded at which point the context was already
- # pushed. This item is discarded. Then when the iteration continues the
- # real generator is executed.
- wrapped_g = generator()
- next(wrapped_g)
- return wrapped_g
-
-
-def make_response(*args):
- """Sometimes it is necessary to set additional headers in a view. Because
- views do not have to return response objects but can return a value that
- is converted into a response object by Flask itself, it becomes tricky to
- add headers to it. This function can be called instead of using a return
- and you will get a response object which you can use to attach headers.
-
- If view looked like this and you want to add a new header::
-
- def index():
- return render_template('index.html', foo=42)
-
- You can now do something like this::
-
- def index():
- response = make_response(render_template('index.html', foo=42))
- response.headers['X-Parachutes'] = 'parachutes are cool'
- return response
-
- This function accepts the very same arguments you can return from a
- view function. This for example creates a response with a 404 error
- code::
-
- response = make_response(render_template('not_found.html'), 404)
-
- The other use case of this function is to force the return value of a
- view function into a response which is helpful with view
- decorators::
-
- response = make_response(view_function())
- response.headers['X-Parachutes'] = 'parachutes are cool'
-
- Internally this function does the following things:
-
- - if no arguments are passed, it creates a new response argument
- - if one argument is passed, :meth:`flask.Flask.make_response`
- is invoked with it.
- - if more than one argument is passed, the arguments are passed
- to the :meth:`flask.Flask.make_response` function as tuple.
-
- .. versionadded:: 0.6
- """
- if not args:
- return current_app.response_class()
- if len(args) == 1:
- args = args[0]
- return current_app.make_response(args)
-
-
-def url_for(endpoint, **values):
- """Generates a URL to the given endpoint with the method provided.
-
- Variable arguments that are unknown to the target endpoint are appended
- to the generated URL as query arguments. If the value of a query argument
- is `None`, the whole pair is skipped. In case blueprints are active
- you can shortcut references to the same blueprint by prefixing the
- local endpoint with a dot (``.``).
-
- This will reference the index function local to the current blueprint::
-
- url_for('.index')
-
- For more information, head over to the :ref:`Quickstart `.
-
- To integrate applications, :class:`Flask` has a hook to intercept URL build
- errors through :attr:`Flask.build_error_handler`. The `url_for` function
- results in a :exc:`~werkzeug.routing.BuildError` when the current app does
- not have a URL for the given endpoint and values. When it does, the
- :data:`~flask.current_app` calls its :attr:`~Flask.build_error_handler` if
- it is not `None`, which can return a string to use as the result of
- `url_for` (instead of `url_for`'s default to raise the
- :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
- An example::
-
- def external_url_handler(error, endpoint, **values):
- "Looks up an external URL when `url_for` cannot build a URL."
- # This is an example of hooking the build_error_handler.
- # Here, lookup_url is some utility function you've built
- # which looks up the endpoint in some external URL registry.
- url = lookup_url(endpoint, **values)
- if url is None:
- # External lookup did not have a URL.
- # Re-raise the BuildError, in context of original traceback.
- exc_type, exc_value, tb = sys.exc_info()
- if exc_value is error:
- raise exc_type, exc_value, tb
- else:
- raise error
- # url_for will use this result, instead of raising BuildError.
- return url
-
- app.build_error_handler = external_url_handler
-
- Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
- `endpoint` and `**values` are the arguments passed into `url_for`. Note
- that this is for building URLs outside the current application, and not for
- handling 404 NotFound errors.
-
- .. versionadded:: 0.10
- The `_scheme` parameter was added.
-
- .. versionadded:: 0.9
- The `_anchor` and `_method` parameters were added.
-
- .. versionadded:: 0.9
- Calls :meth:`Flask.handle_build_error` on
- :exc:`~werkzeug.routing.BuildError`.
-
- :param endpoint: the endpoint of the URL (name of the function)
- :param values: the variable arguments of the URL rule
- :param _external: if set to `True`, an absolute URL is generated. Server
- address can be changed via `SERVER_NAME` configuration variable which
- defaults to `localhost`.
- :param _scheme: a string specifying the desired URL scheme. The `_external`
- parameter must be set to `True` or a `ValueError` is raised.
- :param _anchor: if provided this is added as anchor to the URL.
- :param _method: if provided this explicitly specifies an HTTP method.
- """
- appctx = _app_ctx_stack.top
- reqctx = _request_ctx_stack.top
- if appctx is None:
- raise RuntimeError('Attempted to generate a URL without the '
- 'application context being pushed. This has to be '
- 'executed when application context is available.')
-
- # If request specific information is available we have some extra
- # features that support "relative" urls.
- if reqctx is not None:
- url_adapter = reqctx.url_adapter
- blueprint_name = request.blueprint
- if not reqctx.request._is_old_module:
- if endpoint[:1] == '.':
- if blueprint_name is not None:
- endpoint = blueprint_name + endpoint
- else:
- endpoint = endpoint[1:]
- else:
- # TODO: get rid of this deprecated functionality in 1.0
- if '.' not in endpoint:
- if blueprint_name is not None:
- endpoint = blueprint_name + '.' + endpoint
- elif endpoint.startswith('.'):
- endpoint = endpoint[1:]
- external = values.pop('_external', False)
-
- # Otherwise go with the url adapter from the appctx and make
- # the urls external by default.
- else:
- url_adapter = appctx.url_adapter
- if url_adapter is None:
- raise RuntimeError('Application was not able to create a URL '
- 'adapter for request independent URL generation. '
- 'You might be able to fix this by setting '
- 'the SERVER_NAME config variable.')
- external = values.pop('_external', True)
-
- anchor = values.pop('_anchor', None)
- method = values.pop('_method', None)
- scheme = values.pop('_scheme', None)
- appctx.app.inject_url_defaults(endpoint, values)
-
- if scheme is not None:
- if not external:
- raise ValueError('When specifying _scheme, _external must be True')
- url_adapter.url_scheme = scheme
-
- try:
- rv = url_adapter.build(endpoint, values, method=method,
- force_external=external)
- except BuildError as error:
- # We need to inject the values again so that the app callback can
- # deal with that sort of stuff.
- values['_external'] = external
- values['_anchor'] = anchor
- values['_method'] = method
- return appctx.app.handle_url_build_error(error, endpoint, values)
-
- if anchor is not None:
- rv += '#' + url_quote(anchor)
- return rv
-
-
-def get_template_attribute(template_name, attribute):
- """Loads a macro (or variable) a template exports. This can be used to
- invoke a macro from within Python code. If you for example have a
- template named `_cider.html` with the following contents:
-
- .. sourcecode:: html+jinja
-
- {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
-
- You can access this from Python code like this::
-
- hello = get_template_attribute('_cider.html', 'hello')
- return hello('World')
-
- .. versionadded:: 0.2
-
- :param template_name: the name of the template
- :param attribute: the name of the variable of macro to access
- """
- return getattr(current_app.jinja_env.get_template(template_name).module,
- attribute)
-
-
-def flash(message, category='message'):
- """Flashes a message to the next request. In order to remove the
- flashed message from the session and to display it to the user,
- the template has to call :func:`get_flashed_messages`.
-
- .. versionchanged:: 0.3
- `category` parameter added.
-
- :param message: the message to be flashed.
- :param category: the category for the message. The following values
- are recommended: ``'message'`` for any kind of message,
- ``'error'`` for errors, ``'info'`` for information
- messages and ``'warning'`` for warnings. However any
- kind of string can be used as category.
- """
- # Original implementation:
- #
- # session.setdefault('_flashes', []).append((category, message))
- #
- # This assumed that changes made to mutable structures in the session are
- # are always in sync with the sess on object, which is not true for session
- # implementations that use external storage for keeping their keys/values.
- flashes = session.get('_flashes', [])
- flashes.append((category, message))
- session['_flashes'] = flashes
- message_flashed.send(current_app._get_current_object(),
- message=message, category=category)
-
-
-def get_flashed_messages(with_categories=False, category_filter=[]):
- """Pulls all flashed messages from the session and returns them.
- Further calls in the same request to the function will return
- the same messages. By default just the messages are returned,
- but when `with_categories` is set to `True`, the return value will
- be a list of tuples in the form ``(category, message)`` instead.
-
- Filter the flashed messages to one or more categories by providing those
- categories in `category_filter`. This allows rendering categories in
- separate html blocks. The `with_categories` and `category_filter`
- arguments are distinct:
-
- * `with_categories` controls whether categories are returned with message
- text (`True` gives a tuple, where `False` gives just the message text).
- * `category_filter` filters the messages down to only those matching the
- provided categories.
-
- See :ref:`message-flashing-pattern` for examples.
-
- .. versionchanged:: 0.3
- `with_categories` parameter added.
-
- .. versionchanged:: 0.9
- `category_filter` parameter added.
-
- :param with_categories: set to `True` to also receive categories.
- :param category_filter: whitelist of categories to limit return values
- """
- flashes = _request_ctx_stack.top.flashes
- if flashes is None:
- _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \
- if '_flashes' in session else []
- if category_filter:
- flashes = list(filter(lambda f: f[0] in category_filter, flashes))
- if not with_categories:
- return [x[1] for x in flashes]
- return flashes
-
-
-def send_file(filename_or_fp, mimetype=None, as_attachment=False,
- attachment_filename=None, add_etags=True,
- cache_timeout=None, conditional=False):
- """Sends the contents of a file to the client. This will use the
- most efficient method available and configured. By default it will
- try to use the WSGI server's file_wrapper support. Alternatively
- you can set the application's :attr:`~Flask.use_x_sendfile` attribute
- to ``True`` to directly emit an `X-Sendfile` header. This however
- requires support of the underlying webserver for `X-Sendfile`.
-
- By default it will try to guess the mimetype for you, but you can
- also explicitly provide one. For extra security you probably want
- to send certain files as attachment (HTML for instance). The mimetype
- guessing requires a `filename` or an `attachment_filename` to be
- provided.
-
- Please never pass filenames to this function from user sources without
- checking them first. Something like this is usually sufficient to
- avoid security problems::
-
- if '..' in filename or filename.startswith('/'):
- abort(404)
-
- .. versionadded:: 0.2
-
- .. versionadded:: 0.5
- The `add_etags`, `cache_timeout` and `conditional` parameters were
- added. The default behavior is now to attach etags.
-
- .. versionchanged:: 0.7
- mimetype guessing and etag support for file objects was
- deprecated because it was unreliable. Pass a filename if you are
- able to, otherwise attach an etag yourself. This functionality
- will be removed in Flask 1.0
-
- .. versionchanged:: 0.9
- cache_timeout pulls its default from application config, when None.
-
- :param filename_or_fp: the filename of the file to send. This is
- relative to the :attr:`~Flask.root_path` if a
- relative path is specified.
- Alternatively a file object might be provided
- in which case `X-Sendfile` might not work and
- fall back to the traditional method. Make sure
- that the file pointer is positioned at the start
- of data to send before calling :func:`send_file`.
- :param mimetype: the mimetype of the file if provided, otherwise
- auto detection happens.
- :param as_attachment: set to `True` if you want to send this file with
- a ``Content-Disposition: attachment`` header.
- :param attachment_filename: the filename for the attachment if it
- differs from the file's filename.
- :param add_etags: set to `False` to disable attaching of etags.
- :param conditional: set to `True` to enable conditional responses.
-
- :param cache_timeout: the timeout in seconds for the headers. When `None`
- (default), this value is set by
- :meth:`~Flask.get_send_file_max_age` of
- :data:`~flask.current_app`.
- """
- mtime = None
- if isinstance(filename_or_fp, string_types):
- filename = filename_or_fp
- file = None
- else:
- from warnings import warn
- file = filename_or_fp
- filename = getattr(file, 'name', None)
-
- # XXX: this behavior is now deprecated because it was unreliable.
- # removed in Flask 1.0
- if not attachment_filename and not mimetype \
- and isinstance(filename, string_types):
- warn(DeprecationWarning('The filename support for file objects '
- 'passed to send_file is now deprecated. Pass an '
- 'attach_filename if you want mimetypes to be guessed.'),
- stacklevel=2)
- if add_etags:
- warn(DeprecationWarning('In future flask releases etags will no '
- 'longer be generated for file objects passed to the send_file '
- 'function because this behavior was unreliable. Pass '
- 'filenames instead if possible, otherwise attach an etag '
- 'yourself based on another value'), stacklevel=2)
-
- if filename is not None:
- if not os.path.isabs(filename):
- filename = os.path.join(current_app.root_path, filename)
- if mimetype is None and (filename or attachment_filename):
- mimetype = mimetypes.guess_type(filename or attachment_filename)[0]
- if mimetype is None:
- mimetype = 'application/octet-stream'
-
- headers = Headers()
- if as_attachment:
- if attachment_filename is None:
- if filename is None:
- raise TypeError('filename unavailable, required for '
- 'sending as attachment')
- attachment_filename = os.path.basename(filename)
- headers.add('Content-Disposition', 'attachment',
- filename=attachment_filename)
-
- if current_app.use_x_sendfile and filename:
- if file is not None:
- file.close()
- headers['X-Sendfile'] = filename
- headers['Content-Length'] = os.path.getsize(filename)
- data = None
- else:
- if file is None:
- file = open(filename, 'rb')
- mtime = os.path.getmtime(filename)
- headers['Content-Length'] = os.path.getsize(filename)
- data = wrap_file(request.environ, file)
-
- rv = current_app.response_class(data, mimetype=mimetype, headers=headers,
- direct_passthrough=True)
-
- # if we know the file modification date, we can store it as the
- # the time of the last modification.
- if mtime is not None:
- rv.last_modified = int(mtime)
-
- rv.cache_control.public = True
- if cache_timeout is None:
- cache_timeout = current_app.get_send_file_max_age(filename)
- if cache_timeout is not None:
- rv.cache_control.max_age = cache_timeout
- rv.expires = int(time() + cache_timeout)
-
- if add_etags and filename is not None:
- rv.set_etag('flask-%s-%s-%s' % (
- os.path.getmtime(filename),
- os.path.getsize(filename),
- adler32(
- filename.encode('utf-8') if isinstance(filename, text_type)
- else filename
- ) & 0xffffffff
- ))
- if conditional:
- rv = rv.make_conditional(request)
- # make sure we don't send x-sendfile for servers that
- # ignore the 304 status code for x-sendfile.
- if rv.status_code == 304:
- rv.headers.pop('x-sendfile', None)
- return rv
-
-
-def safe_join(directory, filename):
- """Safely join `directory` and `filename`.
-
- Example usage::
-
- @app.route('/wiki/')
- def wiki_page(filename):
- filename = safe_join(app.config['WIKI_FOLDER'], filename)
- with open(filename, 'rb') as fd:
- content = fd.read() # Read and process the file content...
-
- :param directory: the base directory.
- :param filename: the untrusted filename relative to that directory.
- :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path
- would fall out of `directory`.
- """
- filename = posixpath.normpath(filename)
- for sep in _os_alt_seps:
- if sep in filename:
- raise NotFound()
- if os.path.isabs(filename) or \
- filename == '..' or \
- filename.startswith('../'):
- raise NotFound()
- return os.path.join(directory, filename)
-
-
-def send_from_directory(directory, filename, **options):
- """Send a file from a given directory with :func:`send_file`. This
- is a secure way to quickly expose static files from an upload folder
- or something similar.
-
- Example usage::
-
- @app.route('/uploads/')
- def download_file(filename):
- return send_from_directory(app.config['UPLOAD_FOLDER'],
- filename, as_attachment=True)
-
- .. admonition:: Sending files and Performance
-
- It is strongly recommended to activate either `X-Sendfile` support in
- your webserver or (if no authentication happens) to tell the webserver
- to serve files for the given path on its own without calling into the
- web application for improved performance.
-
- .. versionadded:: 0.5
-
- :param directory: the directory where all the files are stored.
- :param filename: the filename relative to that directory to
- download.
- :param options: optional keyword arguments that are directly
- forwarded to :func:`send_file`.
- """
- filename = safe_join(directory, filename)
- if not os.path.isfile(filename):
- raise NotFound()
- options.setdefault('conditional', True)
- return send_file(filename, **options)
-
-
-def get_root_path(import_name):
- """Returns the path to a package or cwd if that cannot be found. This
- returns the path of a package or the folder that contains a module.
-
- Not to be confused with the package path returned by :func:`find_package`.
- """
- # Module already imported and has a file attribute. Use that first.
- mod = sys.modules.get(import_name)
- if mod is not None and hasattr(mod, '__file__'):
- return os.path.dirname(os.path.abspath(mod.__file__))
-
- # Next attempt: check the loader.
- loader = pkgutil.get_loader(import_name)
-
- # Loader does not exist or we're referring to an unloaded main module
- # or a main module without path (interactive sessions), go with the
- # current working directory.
- if loader is None or import_name == '__main__':
- return os.getcwd()
-
- # For .egg, zipimporter does not have get_filename until Python 2.7.
- # Some other loaders might exhibit the same behavior.
- if hasattr(loader, 'get_filename'):
- filepath = loader.get_filename(import_name)
- else:
- # Fall back to imports.
- __import__(import_name)
- filepath = sys.modules[import_name].__file__
-
- # filepath is import_name.py for a module, or __init__.py for a package.
- return os.path.dirname(os.path.abspath(filepath))
-
-
-def find_package(import_name):
- """Finds a package and returns the prefix (or None if the package is
- not installed) as well as the folder that contains the package or
- module as a tuple. The package path returned is the module that would
- have to be added to the pythonpath in order to make it possible to
- import the module. The prefix is the path below which a UNIX like
- folder structure exists (lib, share etc.).
- """
- root_mod_name = import_name.split('.')[0]
- loader = pkgutil.get_loader(root_mod_name)
- if loader is None or import_name == '__main__':
- # import name is not found, or interactive/main module
- package_path = os.getcwd()
- else:
- # For .egg, zipimporter does not have get_filename until Python 2.7.
- if hasattr(loader, 'get_filename'):
- filename = loader.get_filename(root_mod_name)
- elif hasattr(loader, 'archive'):
- # zipimporter's loader.archive points to the .egg or .zip
- # archive filename is dropped in call to dirname below.
- filename = loader.archive
- else:
- # At least one loader is missing both get_filename and archive:
- # Google App Engine's HardenedModulesHook
- #
- # Fall back to imports.
- __import__(import_name)
- filename = sys.modules[import_name].__file__
- package_path = os.path.abspath(os.path.dirname(filename))
- # package_path ends with __init__.py for a package
- if loader.is_package(root_mod_name):
- package_path = os.path.dirname(package_path)
-
- site_parent, site_folder = os.path.split(package_path)
- py_prefix = os.path.abspath(sys.prefix)
- if package_path.startswith(py_prefix):
- return py_prefix, package_path
- elif site_folder.lower() == 'site-packages':
- parent, folder = os.path.split(site_parent)
- # Windows like installations
- if folder.lower() == 'lib':
- base_dir = parent
- # UNIX like installations
- elif os.path.basename(parent).lower() == 'lib':
- base_dir = os.path.dirname(parent)
- else:
- base_dir = site_parent
- return base_dir, package_path
- return None, package_path
-
-
-class locked_cached_property(object):
- """A decorator that converts a function into a lazy property. The
- function wrapped is called the first time to retrieve the result
- and then that calculated result is used the next time you access
- the value. Works like the one in Werkzeug but has a lock for
- thread safety.
- """
-
- def __init__(self, func, name=None, doc=None):
- self.__name__ = name or func.__name__
- self.__module__ = func.__module__
- self.__doc__ = doc or func.__doc__
- self.func = func
- self.lock = RLock()
-
- def __get__(self, obj, type=None):
- if obj is None:
- return self
- with self.lock:
- value = obj.__dict__.get(self.__name__, _missing)
- if value is _missing:
- value = self.func(obj)
- obj.__dict__[self.__name__] = value
- return value
-
-
-class _PackageBoundObject(object):
-
- def __init__(self, import_name, template_folder=None):
- #: The name of the package or module. Do not change this once
- #: it was set by the constructor.
- self.import_name = import_name
-
- #: location of the templates. `None` if templates should not be
- #: exposed.
- self.template_folder = template_folder
-
- #: Where is the app root located?
- self.root_path = get_root_path(self.import_name)
-
- self._static_folder = None
- self._static_url_path = None
-
- def _get_static_folder(self):
- if self._static_folder is not None:
- return os.path.join(self.root_path, self._static_folder)
- def _set_static_folder(self, value):
- self._static_folder = value
- static_folder = property(_get_static_folder, _set_static_folder)
- del _get_static_folder, _set_static_folder
-
- def _get_static_url_path(self):
- if self._static_url_path is None:
- if self.static_folder is None:
- return None
- return '/' + os.path.basename(self.static_folder)
- return self._static_url_path
- def _set_static_url_path(self, value):
- self._static_url_path = value
- static_url_path = property(_get_static_url_path, _set_static_url_path)
- del _get_static_url_path, _set_static_url_path
-
- @property
- def has_static_folder(self):
- """This is `True` if the package bound object's container has a
- folder named ``'static'``.
-
- .. versionadded:: 0.5
- """
- return self.static_folder is not None
-
- @locked_cached_property
- def jinja_loader(self):
- """The Jinja loader for this package bound object.
-
- .. versionadded:: 0.5
- """
- if self.template_folder is not None:
- return FileSystemLoader(os.path.join(self.root_path,
- self.template_folder))
-
- def get_send_file_max_age(self, filename):
- """Provides default cache_timeout for the :func:`send_file` functions.
-
- By default, this function returns ``SEND_FILE_MAX_AGE_DEFAULT`` from
- the configuration of :data:`~flask.current_app`.
-
- Static file functions such as :func:`send_from_directory` use this
- function, and :func:`send_file` calls this function on
- :data:`~flask.current_app` when the given cache_timeout is `None`. If a
- cache_timeout is given in :func:`send_file`, that timeout is used;
- otherwise, this method is called.
-
- This allows subclasses to change the behavior when sending files based
- on the filename. For example, to set the cache timeout for .js files
- to 60 seconds::
-
- class MyFlask(flask.Flask):
- def get_send_file_max_age(self, name):
- if name.lower().endswith('.js'):
- return 60
- return flask.Flask.get_send_file_max_age(self, name)
-
- .. versionadded:: 0.9
- """
- return current_app.config['SEND_FILE_MAX_AGE_DEFAULT']
-
- def send_static_file(self, filename):
- """Function used internally to send static files from the static
- folder to the browser.
-
- .. versionadded:: 0.5
- """
- if not self.has_static_folder:
- raise RuntimeError('No static folder for this object')
- # Ensure get_send_file_max_age is called in all cases.
- # Here, we ensure get_send_file_max_age is called for Blueprints.
- cache_timeout = self.get_send_file_max_age(filename)
- return send_from_directory(self.static_folder, filename,
- cache_timeout=cache_timeout)
-
- def open_resource(self, resource, mode='rb'):
- """Opens a resource from the application's resource folder. To see
- how this works, consider the following folder structure::
-
- /myapplication.py
- /schema.sql
- /static
- /style.css
- /templates
- /layout.html
- /index.html
-
- If you want to open the `schema.sql` file you would do the
- following::
-
- with app.open_resource('schema.sql') as f:
- contents = f.read()
- do_something_with(contents)
-
- :param resource: the name of the resource. To access resources within
- subfolders use forward slashes as separator.
- :param mode: resource file opening mode, default is 'rb'.
- """
- if mode not in ('r', 'rb'):
- raise ValueError('Resources can only be opened for reading')
- return open(os.path.join(self.root_path, resource), mode)
diff --git a/Darwin/lib/python2.7/site-packages/flask/json.py b/Darwin/lib/python2.7/site-packages/flask/json.py
deleted file mode 100644
index 45ba324..0000000
--- a/Darwin/lib/python2.7/site-packages/flask/json.py
+++ /dev/null
@@ -1,243 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- flask.jsonimpl
- ~~~~~~~~~~~~~~
-
- Implementation helpers for the JSON support in Flask.
-
- :copyright: (c) 2012 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-import io
-import uuid
-from datetime import datetime
-from .globals import current_app, request
-from ._compat import text_type, PY2
-
-from werkzeug.http import http_date
-from jinja2 import Markup
-
-# Use the same json implementation as itsdangerous on which we
-# depend anyways.
-try:
- from itsdangerous import simplejson as _json
-except ImportError:
- from itsdangerous import json as _json
-
-
-# figure out if simplejson escapes slashes. This behavior was changed
-# from one version to another without reason.
-_slash_escape = '\\/' not in _json.dumps('/')
-
-
-__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsafe_dump',
- 'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',
- 'jsonify']
-
-
-def _wrap_reader_for_text(fp, encoding):
- if isinstance(fp.read(0), bytes):
- fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)
- return fp
-
-
-def _wrap_writer_for_text(fp, encoding):
- try:
- fp.write('')
- except TypeError:
- fp = io.TextIOWrapper(fp, encoding)
- return fp
-
-
-class JSONEncoder(_json.JSONEncoder):
- """The default Flask JSON encoder. This one extends the default simplejson
- encoder by also supporting ``datetime`` objects, ``UUID`` as well as
- ``Markup`` objects which are serialized as RFC 822 datetime strings (same
- as the HTTP date format). In order to support more data types override the
- :meth:`default` method.
- """
-
- def default(self, o):
- """Implement this method in a subclass such that it returns a
- serializable object for ``o``, or calls the base implementation (to
- raise a ``TypeError``).
-
- For example, to support arbitrary iterators, you could implement
- default like this::
-
- def default(self, o):
- try:
- iterable = iter(o)
- except TypeError:
- pass
- else:
- return list(iterable)
- return JSONEncoder.default(self, o)
- """
- if isinstance(o, datetime):
- return http_date(o)
- if isinstance(o, uuid.UUID):
- return str(o)
- if hasattr(o, '__html__'):
- return text_type(o.__html__())
- return _json.JSONEncoder.default(self, o)
-
-
-class JSONDecoder(_json.JSONDecoder):
- """The default JSON decoder. This one does not change the behavior from
- the default simplejson encoder. Consult the :mod:`json` documentation
- for more information. This decoder is not only used for the load
- functions of this module but also :attr:`~flask.Request`.
- """
-
-
-def _dump_arg_defaults(kwargs):
- """Inject default arguments for dump functions."""
- if current_app:
- kwargs.setdefault('cls', current_app.json_encoder)
- if not current_app.config['JSON_AS_ASCII']:
- kwargs.setdefault('ensure_ascii', False)
- kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])
- else:
- kwargs.setdefault('sort_keys', True)
- kwargs.setdefault('cls', JSONEncoder)
-
-
-def _load_arg_defaults(kwargs):
- """Inject default arguments for load functions."""
- if current_app:
- kwargs.setdefault('cls', current_app.json_decoder)
- else:
- kwargs.setdefault('cls', JSONDecoder)
-
-
-def dumps(obj, **kwargs):
- """Serialize ``obj`` to a JSON formatted ``str`` by using the application's
- configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an
- application on the stack.
-
- This function can return ``unicode`` strings or ascii-only bytestrings by
- default which coerce into unicode strings automatically. That behavior by
- default is controlled by the ``JSON_AS_ASCII`` configuration variable
- and can be overriden by the simplejson ``ensure_ascii`` parameter.
- """
- _dump_arg_defaults(kwargs)
- encoding = kwargs.pop('encoding', None)
- rv = _json.dumps(obj, **kwargs)
- if encoding is not None and isinstance(rv, text_type):
- rv = rv.encode(encoding)
- return rv
-
-
-def dump(obj, fp, **kwargs):
- """Like :func:`dumps` but writes into a file object."""
- _dump_arg_defaults(kwargs)
- encoding = kwargs.pop('encoding', None)
- if encoding is not None:
- fp = _wrap_writer_for_text(fp, encoding)
- _json.dump(obj, fp, **kwargs)
-
-
-def loads(s, **kwargs):
- """Unserialize a JSON object from a string ``s`` by using the application's
- configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an
- application on the stack.
- """
- _load_arg_defaults(kwargs)
- if isinstance(s, bytes):
- s = s.decode(kwargs.pop('encoding', None) or 'utf-8')
- return _json.loads(s, **kwargs)
-
-
-def load(fp, **kwargs):
- """Like :func:`loads` but reads from a file object.
- """
- _load_arg_defaults(kwargs)
- if not PY2:
- fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8')
- return _json.load(fp, **kwargs)
-
-
-def htmlsafe_dumps(obj, **kwargs):
- """Works exactly like :func:`dumps` but is safe for use in ``')
- self.assert_equal(rv, u'"\\u003c/script\\u003e"')
- self.assert_equal(type(rv), text_type)
- rv = render('{{ ""|tojson }}')
- self.assert_equal(rv, '"\\u003c/script\\u003e"')
- rv = render('{{ "<\0/script>"|tojson }}')
- self.assert_equal(rv, '"\\u003c\\u0000/script\\u003e"')
- rv = render('{{ "' % (
- render_traceback(self, full=full),
- self.render_as_text().decode('utf-8', 'replace')
- )
-
- @property
- def is_template_syntax_error(self):
- """`True` if this is a template syntax error."""
- return isinstance(self.exc_value, TemplateSyntaxError)
-
- @property
- def exc_info(self):
- """Exception info tuple with a proxy around the frame objects."""
- return self.exc_type, self.exc_value, self.frames[0]
-
- @property
- def standard_exc_info(self):
- """Standard python exc_info for re-raising"""
- tb = self.frames[0]
- # the frame will be an actual traceback (or transparent proxy) if
- # we are on pypy or a python implementation with support for tproxy
- if type(tb) is not TracebackType:
- tb = tb.tb
- return self.exc_type, self.exc_value, tb
-
-
-def make_traceback(exc_info, source_hint=None):
- """Creates a processed traceback object from the exc_info."""
- exc_type, exc_value, tb = exc_info
- if isinstance(exc_value, TemplateSyntaxError):
- exc_info = translate_syntax_error(exc_value, source_hint)
- initial_skip = 0
- else:
- initial_skip = 1
- return translate_exception(exc_info, initial_skip)
-
-
-def translate_syntax_error(error, source=None):
- """Rewrites a syntax error to please traceback systems."""
- error.source = source
- error.translated = True
- exc_info = (error.__class__, error, None)
- filename = error.filename
- if filename is None:
- filename = ''
- return fake_exc_info(exc_info, filename, error.lineno)
-
-
-def translate_exception(exc_info, initial_skip=0):
- """If passed an exc_info it will automatically rewrite the exceptions
- all the way down to the correct line numbers and frames.
- """
- tb = exc_info[2]
- frames = []
-
- # skip some internal frames if wanted
- for x in range(initial_skip):
- if tb is not None:
- tb = tb.tb_next
- initial_tb = tb
-
- while tb is not None:
- # skip frames decorated with @internalcode. These are internal
- # calls we can't avoid and that are useless in template debugging
- # output.
- if tb.tb_frame.f_code in internal_code:
- tb = tb.tb_next
- continue
-
- # save a reference to the next frame if we override the current
- # one with a faked one.
- next = tb.tb_next
-
- # fake template exceptions
- template = tb.tb_frame.f_globals.get('__jinja_template__')
- if template is not None:
- lineno = template.get_corresponding_lineno(tb.tb_lineno)
- tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,
- lineno)[2]
-
- frames.append(make_frame_proxy(tb))
- tb = next
-
- # if we don't have any exceptions in the frames left, we have to
- # reraise it unchanged.
- # XXX: can we backup here? when could this happen?
- if not frames:
- reraise(exc_info[0], exc_info[1], exc_info[2])
-
- return ProcessedTraceback(exc_info[0], exc_info[1], frames)
-
-
-def fake_exc_info(exc_info, filename, lineno):
- """Helper for `translate_exception`."""
- exc_type, exc_value, tb = exc_info
-
- # figure the real context out
- if tb is not None:
- real_locals = tb.tb_frame.f_locals.copy()
- ctx = real_locals.get('context')
- if ctx:
- locals = ctx.get_all()
- else:
- locals = {}
- for name, value in iteritems(real_locals):
- if name.startswith('l_') and value is not missing:
- locals[name[2:]] = value
-
- # if there is a local called __jinja_exception__, we get
- # rid of it to not break the debug functionality.
- locals.pop('__jinja_exception__', None)
- else:
- locals = {}
-
- # assamble fake globals we need
- globals = {
- '__name__': filename,
- '__file__': filename,
- '__jinja_exception__': exc_info[:2],
-
- # we don't want to keep the reference to the template around
- # to not cause circular dependencies, but we mark it as Jinja
- # frame for the ProcessedTraceback
- '__jinja_template__': None
- }
-
- # and fake the exception
- code = compile('\n' * (lineno - 1) + raise_helper, filename, 'exec')
-
- # if it's possible, change the name of the code. This won't work
- # on some python environments such as google appengine
- try:
- if tb is None:
- location = 'template'
- else:
- function = tb.tb_frame.f_code.co_name
- if function == 'root':
- location = 'top-level template code'
- elif function.startswith('block_'):
- location = 'block "%s"' % function[6:]
- else:
- location = 'template'
- code = code_type(0, code.co_nlocals, code.co_stacksize,
- code.co_flags, code.co_code, code.co_consts,
- code.co_names, code.co_varnames, filename,
- location, code.co_firstlineno,
- code.co_lnotab, (), ())
- except:
- pass
-
- # execute the code and catch the new traceback
- try:
- exec(code, globals, locals)
- except:
- exc_info = sys.exc_info()
- new_tb = exc_info[2].tb_next
-
- # return without this frame
- return exc_info[:2] + (new_tb,)
-
-
-def _init_ugly_crap():
- """This function implements a few ugly things so that we can patch the
- traceback objects. The function returned allows resetting `tb_next` on
- any python traceback object. Do not attempt to use this on non cpython
- interpreters
- """
- import ctypes
- from types import TracebackType
-
- # figure out side of _Py_ssize_t
- if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
- _Py_ssize_t = ctypes.c_int64
- else:
- _Py_ssize_t = ctypes.c_int
-
- # regular python
- class _PyObject(ctypes.Structure):
- pass
- _PyObject._fields_ = [
- ('ob_refcnt', _Py_ssize_t),
- ('ob_type', ctypes.POINTER(_PyObject))
- ]
-
- # python with trace
- if hasattr(sys, 'getobjects'):
- class _PyObject(ctypes.Structure):
- pass
- _PyObject._fields_ = [
- ('_ob_next', ctypes.POINTER(_PyObject)),
- ('_ob_prev', ctypes.POINTER(_PyObject)),
- ('ob_refcnt', _Py_ssize_t),
- ('ob_type', ctypes.POINTER(_PyObject))
- ]
-
- class _Traceback(_PyObject):
- pass
- _Traceback._fields_ = [
- ('tb_next', ctypes.POINTER(_Traceback)),
- ('tb_frame', ctypes.POINTER(_PyObject)),
- ('tb_lasti', ctypes.c_int),
- ('tb_lineno', ctypes.c_int)
- ]
-
- def tb_set_next(tb, next):
- """Set the tb_next attribute of a traceback object."""
- if not (isinstance(tb, TracebackType) and
- (next is None or isinstance(next, TracebackType))):
- raise TypeError('tb_set_next arguments must be traceback objects')
- obj = _Traceback.from_address(id(tb))
- if tb.tb_next is not None:
- old = _Traceback.from_address(id(tb.tb_next))
- old.ob_refcnt -= 1
- if next is None:
- obj.tb_next = ctypes.POINTER(_Traceback)()
- else:
- next = _Traceback.from_address(id(next))
- next.ob_refcnt += 1
- obj.tb_next = ctypes.pointer(next)
-
- return tb_set_next
-
-
-# try to get a tb_set_next implementation if we don't have transparent
-# proxies.
-tb_set_next = None
-if tproxy is None:
- try:
- tb_set_next = _init_ugly_crap()
- except:
- pass
- del _init_ugly_crap
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/defaults.py b/Darwin/lib/python2.7/site-packages/jinja2/defaults.py
deleted file mode 100644
index a27cb80..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/defaults.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.defaults
- ~~~~~~~~~~~~~~~
-
- Jinja default filters and tags.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2._compat import range_type
-from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner
-
-
-# defaults for the parser / lexer
-BLOCK_START_STRING = '{%'
-BLOCK_END_STRING = '%}'
-VARIABLE_START_STRING = '{{'
-VARIABLE_END_STRING = '}}'
-COMMENT_START_STRING = '{#'
-COMMENT_END_STRING = '#}'
-LINE_STATEMENT_PREFIX = None
-LINE_COMMENT_PREFIX = None
-TRIM_BLOCKS = False
-LSTRIP_BLOCKS = False
-NEWLINE_SEQUENCE = '\n'
-KEEP_TRAILING_NEWLINE = False
-
-
-# default filters, tests and namespace
-from jinja2.filters import FILTERS as DEFAULT_FILTERS
-from jinja2.tests import TESTS as DEFAULT_TESTS
-DEFAULT_NAMESPACE = {
- 'range': range_type,
- 'dict': lambda **kw: kw,
- 'lipsum': generate_lorem_ipsum,
- 'cycler': Cycler,
- 'joiner': Joiner
-}
-
-
-# export all constants
-__all__ = tuple(x for x in locals().keys() if x.isupper())
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/environment.py b/Darwin/lib/python2.7/site-packages/jinja2/environment.py
deleted file mode 100644
index 45fabad..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/environment.py
+++ /dev/null
@@ -1,1191 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.environment
- ~~~~~~~~~~~~~~~~~~
-
- Provides a class that holds runtime and parsing time options.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import os
-import sys
-from jinja2 import nodes
-from jinja2.defaults import BLOCK_START_STRING, \
- BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \
- COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \
- LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \
- DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE, \
- KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS
-from jinja2.lexer import get_lexer, TokenStream
-from jinja2.parser import Parser
-from jinja2.nodes import EvalContext
-from jinja2.optimizer import optimize
-from jinja2.compiler import generate
-from jinja2.runtime import Undefined, new_context
-from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \
- TemplatesNotFound, TemplateRuntimeError
-from jinja2.utils import import_string, LRUCache, Markup, missing, \
- concat, consume, internalcode
-from jinja2._compat import imap, ifilter, string_types, iteritems, \
- text_type, reraise, implements_iterator, implements_to_string, \
- get_next, encode_filename, PY2, PYPY
-from functools import reduce
-
-
-# for direct template usage we have up to ten living environments
-_spontaneous_environments = LRUCache(10)
-
-# the function to create jinja traceback objects. This is dynamically
-# imported on the first exception in the exception handler.
-_make_traceback = None
-
-
-def get_spontaneous_environment(*args):
- """Return a new spontaneous environment. A spontaneous environment is an
- unnamed and unaccessible (in theory) environment that is used for
- templates generated from a string and not from the file system.
- """
- try:
- env = _spontaneous_environments.get(args)
- except TypeError:
- return Environment(*args)
- if env is not None:
- return env
- _spontaneous_environments[args] = env = Environment(*args)
- env.shared = True
- return env
-
-
-def create_cache(size):
- """Return the cache class for the given size."""
- if size == 0:
- return None
- if size < 0:
- return {}
- return LRUCache(size)
-
-
-def copy_cache(cache):
- """Create an empty copy of the given cache."""
- if cache is None:
- return None
- elif type(cache) is dict:
- return {}
- return LRUCache(cache.capacity)
-
-
-def load_extensions(environment, extensions):
- """Load the extensions from the list and bind it to the environment.
- Returns a dict of instantiated environments.
- """
- result = {}
- for extension in extensions:
- if isinstance(extension, string_types):
- extension = import_string(extension)
- result[extension.identifier] = extension(environment)
- return result
-
-
-def _environment_sanity_check(environment):
- """Perform a sanity check on the environment."""
- assert issubclass(environment.undefined, Undefined), 'undefined must ' \
- 'be a subclass of undefined because filters depend on it.'
- assert environment.block_start_string != \
- environment.variable_start_string != \
- environment.comment_start_string, 'block, variable and comment ' \
- 'start strings must be different'
- assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
- 'newline_sequence set to unknown line ending string.'
- return environment
-
-
-class Environment(object):
- r"""The core component of Jinja is the `Environment`. It contains
- important shared variables like configuration, filters, tests,
- globals and others. Instances of this class may be modified if
- they are not shared and if no template was loaded so far.
- Modifications on environments after the first template was loaded
- will lead to surprising effects and undefined behavior.
-
- Here the possible initialization parameters:
-
- `block_start_string`
- The string marking the begin of a block. Defaults to ``'{%'``.
-
- `block_end_string`
- The string marking the end of a block. Defaults to ``'%}'``.
-
- `variable_start_string`
- The string marking the begin of a print statement.
- Defaults to ``'{{'``.
-
- `variable_end_string`
- The string marking the end of a print statement. Defaults to
- ``'}}'``.
-
- `comment_start_string`
- The string marking the begin of a comment. Defaults to ``'{#'``.
-
- `comment_end_string`
- The string marking the end of a comment. Defaults to ``'#}'``.
-
- `line_statement_prefix`
- If given and a string, this will be used as prefix for line based
- statements. See also :ref:`line-statements`.
-
- `line_comment_prefix`
- If given and a string, this will be used as prefix for line based
- based comments. See also :ref:`line-statements`.
-
- .. versionadded:: 2.2
-
- `trim_blocks`
- If this is set to ``True`` the first newline after a block is
- removed (block, not variable tag!). Defaults to `False`.
-
- `lstrip_blocks`
- If this is set to ``True`` leading spaces and tabs are stripped
- from the start of a line to a block. Defaults to `False`.
-
- `newline_sequence`
- The sequence that starts a newline. Must be one of ``'\r'``,
- ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
- useful default for Linux and OS X systems as well as web
- applications.
-
- `keep_trailing_newline`
- Preserve the trailing newline when rendering templates.
- The default is ``False``, which causes a single newline,
- if present, to be stripped from the end of the template.
-
- .. versionadded:: 2.7
-
- `extensions`
- List of Jinja extensions to use. This can either be import paths
- as strings or extension classes. For more information have a
- look at :ref:`the extensions documentation `.
-
- `optimized`
- should the optimizer be enabled? Default is `True`.
-
- `undefined`
- :class:`Undefined` or a subclass of it that is used to represent
- undefined values in the template.
-
- `finalize`
- A callable that can be used to process the result of a variable
- expression before it is output. For example one can convert
- `None` implicitly into an empty string here.
-
- `autoescape`
- If set to true the XML/HTML autoescaping feature is enabled by
- default. For more details about auto escaping see
- :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also
- be a callable that is passed the template name and has to
- return `True` or `False` depending on autoescape should be
- enabled by default.
-
- .. versionchanged:: 2.4
- `autoescape` can now be a function
-
- `loader`
- The template loader for this environment.
-
- `cache_size`
- The size of the cache. Per default this is ``50`` which means
- that if more than 50 templates are loaded the loader will clean
- out the least recently used template. If the cache size is set to
- ``0`` templates are recompiled all the time, if the cache size is
- ``-1`` the cache will not be cleaned.
-
- `auto_reload`
- Some loaders load templates from locations where the template
- sources may change (ie: file system or database). If
- `auto_reload` is set to `True` (default) every time a template is
- requested the loader checks if the source changed and if yes, it
- will reload the template. For higher performance it's possible to
- disable that.
-
- `bytecode_cache`
- If set to a bytecode cache object, this object will provide a
- cache for the internal Jinja bytecode so that templates don't
- have to be parsed if they were not changed.
-
- See :ref:`bytecode-cache` for more information.
- """
-
- #: if this environment is sandboxed. Modifying this variable won't make
- #: the environment sandboxed though. For a real sandboxed environment
- #: have a look at jinja2.sandbox. This flag alone controls the code
- #: generation by the compiler.
- sandboxed = False
-
- #: True if the environment is just an overlay
- overlayed = False
-
- #: the environment this environment is linked to if it is an overlay
- linked_to = None
-
- #: shared environments have this set to `True`. A shared environment
- #: must not be modified
- shared = False
-
- #: these are currently EXPERIMENTAL undocumented features.
- exception_handler = None
- exception_formatter = None
-
- def __init__(self,
- block_start_string=BLOCK_START_STRING,
- block_end_string=BLOCK_END_STRING,
- variable_start_string=VARIABLE_START_STRING,
- variable_end_string=VARIABLE_END_STRING,
- comment_start_string=COMMENT_START_STRING,
- comment_end_string=COMMENT_END_STRING,
- line_statement_prefix=LINE_STATEMENT_PREFIX,
- line_comment_prefix=LINE_COMMENT_PREFIX,
- trim_blocks=TRIM_BLOCKS,
- lstrip_blocks=LSTRIP_BLOCKS,
- newline_sequence=NEWLINE_SEQUENCE,
- keep_trailing_newline=KEEP_TRAILING_NEWLINE,
- extensions=(),
- optimized=True,
- undefined=Undefined,
- finalize=None,
- autoescape=False,
- loader=None,
- cache_size=50,
- auto_reload=True,
- bytecode_cache=None):
- # !!Important notice!!
- # The constructor accepts quite a few arguments that should be
- # passed by keyword rather than position. However it's important to
- # not change the order of arguments because it's used at least
- # internally in those cases:
- # - spontaneous environments (i18n extension and Template)
- # - unittests
- # If parameter changes are required only add parameters at the end
- # and don't change the arguments (or the defaults!) of the arguments
- # existing already.
-
- # lexer / parser information
- self.block_start_string = block_start_string
- self.block_end_string = block_end_string
- self.variable_start_string = variable_start_string
- self.variable_end_string = variable_end_string
- self.comment_start_string = comment_start_string
- self.comment_end_string = comment_end_string
- self.line_statement_prefix = line_statement_prefix
- self.line_comment_prefix = line_comment_prefix
- self.trim_blocks = trim_blocks
- self.lstrip_blocks = lstrip_blocks
- self.newline_sequence = newline_sequence
- self.keep_trailing_newline = keep_trailing_newline
-
- # runtime information
- self.undefined = undefined
- self.optimized = optimized
- self.finalize = finalize
- self.autoescape = autoescape
-
- # defaults
- self.filters = DEFAULT_FILTERS.copy()
- self.tests = DEFAULT_TESTS.copy()
- self.globals = DEFAULT_NAMESPACE.copy()
-
- # set the loader provided
- self.loader = loader
- self.cache = create_cache(cache_size)
- self.bytecode_cache = bytecode_cache
- self.auto_reload = auto_reload
-
- # load extensions
- self.extensions = load_extensions(self, extensions)
-
- _environment_sanity_check(self)
-
- def add_extension(self, extension):
- """Adds an extension after the environment was created.
-
- .. versionadded:: 2.5
- """
- self.extensions.update(load_extensions(self, [extension]))
-
- def extend(self, **attributes):
- """Add the items to the instance of the environment if they do not exist
- yet. This is used by :ref:`extensions ` to register
- callbacks and configuration values without breaking inheritance.
- """
- for key, value in iteritems(attributes):
- if not hasattr(self, key):
- setattr(self, key, value)
-
- def overlay(self, block_start_string=missing, block_end_string=missing,
- variable_start_string=missing, variable_end_string=missing,
- comment_start_string=missing, comment_end_string=missing,
- line_statement_prefix=missing, line_comment_prefix=missing,
- trim_blocks=missing, lstrip_blocks=missing,
- extensions=missing, optimized=missing,
- undefined=missing, finalize=missing, autoescape=missing,
- loader=missing, cache_size=missing, auto_reload=missing,
- bytecode_cache=missing):
- """Create a new overlay environment that shares all the data with the
- current environment except of cache and the overridden attributes.
- Extensions cannot be removed for an overlayed environment. An overlayed
- environment automatically gets all the extensions of the environment it
- is linked to plus optional extra extensions.
-
- Creating overlays should happen after the initial environment was set
- up completely. Not all attributes are truly linked, some are just
- copied over so modifications on the original environment may not shine
- through.
- """
- args = dict(locals())
- del args['self'], args['cache_size'], args['extensions']
-
- rv = object.__new__(self.__class__)
- rv.__dict__.update(self.__dict__)
- rv.overlayed = True
- rv.linked_to = self
-
- for key, value in iteritems(args):
- if value is not missing:
- setattr(rv, key, value)
-
- if cache_size is not missing:
- rv.cache = create_cache(cache_size)
- else:
- rv.cache = copy_cache(self.cache)
-
- rv.extensions = {}
- for key, value in iteritems(self.extensions):
- rv.extensions[key] = value.bind(rv)
- if extensions is not missing:
- rv.extensions.update(load_extensions(rv, extensions))
-
- return _environment_sanity_check(rv)
-
- lexer = property(get_lexer, doc="The lexer for this environment.")
-
- def iter_extensions(self):
- """Iterates over the extensions by priority."""
- return iter(sorted(self.extensions.values(),
- key=lambda x: x.priority))
-
- def getitem(self, obj, argument):
- """Get an item or attribute of an object but prefer the item."""
- try:
- return obj[argument]
- except (TypeError, LookupError):
- if isinstance(argument, string_types):
- try:
- attr = str(argument)
- except Exception:
- pass
- else:
- try:
- return getattr(obj, attr)
- except AttributeError:
- pass
- return self.undefined(obj=obj, name=argument)
-
- def getattr(self, obj, attribute):
- """Get an item or attribute of an object but prefer the attribute.
- Unlike :meth:`getitem` the attribute *must* be a bytestring.
- """
- try:
- return getattr(obj, attribute)
- except AttributeError:
- pass
- try:
- return obj[attribute]
- except (TypeError, LookupError, AttributeError):
- return self.undefined(obj=obj, name=attribute)
-
- def call_filter(self, name, value, args=None, kwargs=None,
- context=None, eval_ctx=None):
- """Invokes a filter on a value the same way the compiler does it.
-
- .. versionadded:: 2.7
- """
- func = self.filters.get(name)
- if func is None:
- raise TemplateRuntimeError('no filter named %r' % name)
- args = [value] + list(args or ())
- if getattr(func, 'contextfilter', False):
- if context is None:
- raise TemplateRuntimeError('Attempted to invoke context '
- 'filter without context')
- args.insert(0, context)
- elif getattr(func, 'evalcontextfilter', False):
- if eval_ctx is None:
- if context is not None:
- eval_ctx = context.eval_ctx
- else:
- eval_ctx = EvalContext(self)
- args.insert(0, eval_ctx)
- elif getattr(func, 'environmentfilter', False):
- args.insert(0, self)
- return func(*args, **(kwargs or {}))
-
- def call_test(self, name, value, args=None, kwargs=None):
- """Invokes a test on a value the same way the compiler does it.
-
- .. versionadded:: 2.7
- """
- func = self.tests.get(name)
- if func is None:
- raise TemplateRuntimeError('no test named %r' % name)
- return func(value, *(args or ()), **(kwargs or {}))
-
- @internalcode
- def parse(self, source, name=None, filename=None):
- """Parse the sourcecode and return the abstract syntax tree. This
- tree of nodes is used by the compiler to convert the template into
- executable source- or bytecode. This is useful for debugging or to
- extract information from templates.
-
- If you are :ref:`developing Jinja2 extensions `
- this gives you a good overview of the node tree generated.
- """
- try:
- return self._parse(source, name, filename)
- except TemplateSyntaxError:
- exc_info = sys.exc_info()
- self.handle_exception(exc_info, source_hint=source)
-
- def _parse(self, source, name, filename):
- """Internal parsing function used by `parse` and `compile`."""
- return Parser(self, source, name, encode_filename(filename)).parse()
-
- def lex(self, source, name=None, filename=None):
- """Lex the given sourcecode and return a generator that yields
- tokens as tuples in the form ``(lineno, token_type, value)``.
- This can be useful for :ref:`extension development `
- and debugging templates.
-
- This does not perform preprocessing. If you want the preprocessing
- of the extensions to be applied you have to filter source through
- the :meth:`preprocess` method.
- """
- source = text_type(source)
- try:
- return self.lexer.tokeniter(source, name, filename)
- except TemplateSyntaxError:
- exc_info = sys.exc_info()
- self.handle_exception(exc_info, source_hint=source)
-
- def preprocess(self, source, name=None, filename=None):
- """Preprocesses the source with all extensions. This is automatically
- called for all parsing and compiling methods but *not* for :meth:`lex`
- because there you usually only want the actual source tokenized.
- """
- return reduce(lambda s, e: e.preprocess(s, name, filename),
- self.iter_extensions(), text_type(source))
-
- def _tokenize(self, source, name, filename=None, state=None):
- """Called by the parser to do the preprocessing and filtering
- for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
- """
- source = self.preprocess(source, name, filename)
- stream = self.lexer.tokenize(source, name, filename, state)
- for ext in self.iter_extensions():
- stream = ext.filter_stream(stream)
- if not isinstance(stream, TokenStream):
- stream = TokenStream(stream, name, filename)
- return stream
-
- def _generate(self, source, name, filename, defer_init=False):
- """Internal hook that can be overridden to hook a different generate
- method in.
-
- .. versionadded:: 2.5
- """
- return generate(source, self, name, filename, defer_init=defer_init)
-
- def _compile(self, source, filename):
- """Internal hook that can be overridden to hook a different compile
- method in.
-
- .. versionadded:: 2.5
- """
- return compile(source, filename, 'exec')
-
- @internalcode
- def compile(self, source, name=None, filename=None, raw=False,
- defer_init=False):
- """Compile a node or template source code. The `name` parameter is
- the load name of the template after it was joined using
- :meth:`join_path` if necessary, not the filename on the file system.
- the `filename` parameter is the estimated filename of the template on
- the file system. If the template came from a database or memory this
- can be omitted.
-
- The return value of this method is a python code object. If the `raw`
- parameter is `True` the return value will be a string with python
- code equivalent to the bytecode returned otherwise. This method is
- mainly used internally.
-
- `defer_init` is use internally to aid the module code generator. This
- causes the generated code to be able to import without the global
- environment variable to be set.
-
- .. versionadded:: 2.4
- `defer_init` parameter added.
- """
- source_hint = None
- try:
- if isinstance(source, string_types):
- source_hint = source
- source = self._parse(source, name, filename)
- if self.optimized:
- source = optimize(source, self)
- source = self._generate(source, name, filename,
- defer_init=defer_init)
- if raw:
- return source
- if filename is None:
- filename = ''
- else:
- filename = encode_filename(filename)
- return self._compile(source, filename)
- except TemplateSyntaxError:
- exc_info = sys.exc_info()
- self.handle_exception(exc_info, source_hint=source)
-
- def compile_expression(self, source, undefined_to_none=True):
- """A handy helper method that returns a callable that accepts keyword
- arguments that appear as variables in the expression. If called it
- returns the result of the expression.
-
- This is useful if applications want to use the same rules as Jinja
- in template "configuration files" or similar situations.
-
- Example usage:
-
- >>> env = Environment()
- >>> expr = env.compile_expression('foo == 42')
- >>> expr(foo=23)
- False
- >>> expr(foo=42)
- True
-
- Per default the return value is converted to `None` if the
- expression returns an undefined value. This can be changed
- by setting `undefined_to_none` to `False`.
-
- >>> env.compile_expression('var')() is None
- True
- >>> env.compile_expression('var', undefined_to_none=False)()
- Undefined
-
- .. versionadded:: 2.1
- """
- parser = Parser(self, source, state='variable')
- exc_info = None
- try:
- expr = parser.parse_expression()
- if not parser.stream.eos:
- raise TemplateSyntaxError('chunk after expression',
- parser.stream.current.lineno,
- None, None)
- expr.set_environment(self)
- except TemplateSyntaxError:
- exc_info = sys.exc_info()
- if exc_info is not None:
- self.handle_exception(exc_info, source_hint=source)
- body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
- template = self.from_string(nodes.Template(body, lineno=1))
- return TemplateExpression(template, undefined_to_none)
-
- def compile_templates(self, target, extensions=None, filter_func=None,
- zip='deflated', log_function=None,
- ignore_errors=True, py_compile=False):
- """Finds all the templates the loader can find, compiles them
- and stores them in `target`. If `zip` is `None`, instead of in a
- zipfile, the templates will be will be stored in a directory.
- By default a deflate zip algorithm is used, to switch to
- the stored algorithm, `zip` can be set to ``'stored'``.
-
- `extensions` and `filter_func` are passed to :meth:`list_templates`.
- Each template returned will be compiled to the target folder or
- zipfile.
-
- By default template compilation errors are ignored. In case a
- log function is provided, errors are logged. If you want template
- syntax errors to abort the compilation you can set `ignore_errors`
- to `False` and you will get an exception on syntax errors.
-
- If `py_compile` is set to `True` .pyc files will be written to the
- target instead of standard .py files. This flag does not do anything
- on pypy and Python 3 where pyc files are not picked up by itself and
- don't give much benefit.
-
- .. versionadded:: 2.4
- """
- from jinja2.loaders import ModuleLoader
-
- if log_function is None:
- log_function = lambda x: None
-
- if py_compile:
- if not PY2 or PYPY:
- from warnings import warn
- warn(Warning('py_compile has no effect on pypy or Python 3'))
- py_compile = False
- else:
- import imp, marshal
- py_header = imp.get_magic() + \
- u'\xff\xff\xff\xff'.encode('iso-8859-15')
-
- # Python 3.3 added a source filesize to the header
- if sys.version_info >= (3, 3):
- py_header += u'\x00\x00\x00\x00'.encode('iso-8859-15')
-
- def write_file(filename, data, mode):
- if zip:
- info = ZipInfo(filename)
- info.external_attr = 0o755 << 16
- zip_file.writestr(info, data)
- else:
- f = open(os.path.join(target, filename), mode)
- try:
- f.write(data)
- finally:
- f.close()
-
- if zip is not None:
- from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
- zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED,
- stored=ZIP_STORED)[zip])
- log_function('Compiling into Zip archive "%s"' % target)
- else:
- if not os.path.isdir(target):
- os.makedirs(target)
- log_function('Compiling into folder "%s"' % target)
-
- try:
- for name in self.list_templates(extensions, filter_func):
- source, filename, _ = self.loader.get_source(self, name)
- try:
- code = self.compile(source, name, filename, True, True)
- except TemplateSyntaxError as e:
- if not ignore_errors:
- raise
- log_function('Could not compile "%s": %s' % (name, e))
- continue
-
- filename = ModuleLoader.get_module_filename(name)
-
- if py_compile:
- c = self._compile(code, encode_filename(filename))
- write_file(filename + 'c', py_header +
- marshal.dumps(c), 'wb')
- log_function('Byte-compiled "%s" as %s' %
- (name, filename + 'c'))
- else:
- write_file(filename, code, 'w')
- log_function('Compiled "%s" as %s' % (name, filename))
- finally:
- if zip:
- zip_file.close()
-
- log_function('Finished compiling templates')
-
- def list_templates(self, extensions=None, filter_func=None):
- """Returns a list of templates for this environment. This requires
- that the loader supports the loader's
- :meth:`~BaseLoader.list_templates` method.
-
- If there are other files in the template folder besides the
- actual templates, the returned list can be filtered. There are two
- ways: either `extensions` is set to a list of file extensions for
- templates, or a `filter_func` can be provided which is a callable that
- is passed a template name and should return `True` if it should end up
- in the result list.
-
- If the loader does not support that, a :exc:`TypeError` is raised.
-
- .. versionadded:: 2.4
- """
- x = self.loader.list_templates()
- if extensions is not None:
- if filter_func is not None:
- raise TypeError('either extensions or filter_func '
- 'can be passed, but not both')
- filter_func = lambda x: '.' in x and \
- x.rsplit('.', 1)[1] in extensions
- if filter_func is not None:
- x = ifilter(filter_func, x)
- return x
-
- def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
- """Exception handling helper. This is used internally to either raise
- rewritten exceptions or return a rendered traceback for the template.
- """
- global _make_traceback
- if exc_info is None:
- exc_info = sys.exc_info()
-
- # the debugging module is imported when it's used for the first time.
- # we're doing a lot of stuff there and for applications that do not
- # get any exceptions in template rendering there is no need to load
- # all of that.
- if _make_traceback is None:
- from jinja2.debug import make_traceback as _make_traceback
- traceback = _make_traceback(exc_info, source_hint)
- if rendered and self.exception_formatter is not None:
- return self.exception_formatter(traceback)
- if self.exception_handler is not None:
- self.exception_handler(traceback)
- exc_type, exc_value, tb = traceback.standard_exc_info
- reraise(exc_type, exc_value, tb)
-
- def join_path(self, template, parent):
- """Join a template with the parent. By default all the lookups are
- relative to the loader root so this method returns the `template`
- parameter unchanged, but if the paths should be relative to the
- parent template, this function can be used to calculate the real
- template name.
-
- Subclasses may override this method and implement template path
- joining here.
- """
- return template
-
- @internalcode
- def _load_template(self, name, globals):
- if self.loader is None:
- raise TypeError('no loader for this environment specified')
- if self.cache is not None:
- template = self.cache.get(name)
- if template is not None and (not self.auto_reload or \
- template.is_up_to_date):
- return template
- template = self.loader.load(self, name, globals)
- if self.cache is not None:
- self.cache[name] = template
- return template
-
- @internalcode
- def get_template(self, name, parent=None, globals=None):
- """Load a template from the loader. If a loader is configured this
- method ask the loader for the template and returns a :class:`Template`.
- If the `parent` parameter is not `None`, :meth:`join_path` is called
- to get the real template name before loading.
-
- The `globals` parameter can be used to provide template wide globals.
- These variables are available in the context at render time.
-
- If the template does not exist a :exc:`TemplateNotFound` exception is
- raised.
-
- .. versionchanged:: 2.4
- If `name` is a :class:`Template` object it is returned from the
- function unchanged.
- """
- if isinstance(name, Template):
- return name
- if parent is not None:
- name = self.join_path(name, parent)
- return self._load_template(name, self.make_globals(globals))
-
- @internalcode
- def select_template(self, names, parent=None, globals=None):
- """Works like :meth:`get_template` but tries a number of templates
- before it fails. If it cannot find any of the templates, it will
- raise a :exc:`TemplatesNotFound` exception.
-
- .. versionadded:: 2.3
-
- .. versionchanged:: 2.4
- If `names` contains a :class:`Template` object it is returned
- from the function unchanged.
- """
- if not names:
- raise TemplatesNotFound(message=u'Tried to select from an empty list '
- u'of templates.')
- globals = self.make_globals(globals)
- for name in names:
- if isinstance(name, Template):
- return name
- if parent is not None:
- name = self.join_path(name, parent)
- try:
- return self._load_template(name, globals)
- except TemplateNotFound:
- pass
- raise TemplatesNotFound(names)
-
- @internalcode
- def get_or_select_template(self, template_name_or_list,
- parent=None, globals=None):
- """Does a typecheck and dispatches to :meth:`select_template`
- if an iterable of template names is given, otherwise to
- :meth:`get_template`.
-
- .. versionadded:: 2.3
- """
- if isinstance(template_name_or_list, string_types):
- return self.get_template(template_name_or_list, parent, globals)
- elif isinstance(template_name_or_list, Template):
- return template_name_or_list
- return self.select_template(template_name_or_list, parent, globals)
-
- def from_string(self, source, globals=None, template_class=None):
- """Load a template from a string. This parses the source given and
- returns a :class:`Template` object.
- """
- globals = self.make_globals(globals)
- cls = template_class or self.template_class
- return cls.from_code(self, self.compile(source), globals, None)
-
- def make_globals(self, d):
- """Return a dict for the globals."""
- if not d:
- return self.globals
- return dict(self.globals, **d)
-
-
-class Template(object):
- """The central template object. This class represents a compiled template
- and is used to evaluate it.
-
- Normally the template object is generated from an :class:`Environment` but
- it also has a constructor that makes it possible to create a template
- instance directly using the constructor. It takes the same arguments as
- the environment constructor but it's not possible to specify a loader.
-
- Every template object has a few methods and members that are guaranteed
- to exist. However it's important that a template object should be
- considered immutable. Modifications on the object are not supported.
-
- Template objects created from the constructor rather than an environment
- do have an `environment` attribute that points to a temporary environment
- that is probably shared with other templates created with the constructor
- and compatible settings.
-
- >>> template = Template('Hello {{ name }}!')
- >>> template.render(name='John Doe')
- u'Hello John Doe!'
-
- >>> stream = template.stream(name='John Doe')
- >>> stream.next()
- u'Hello John Doe!'
- >>> stream.next()
- Traceback (most recent call last):
- ...
- StopIteration
- """
-
- def __new__(cls, source,
- block_start_string=BLOCK_START_STRING,
- block_end_string=BLOCK_END_STRING,
- variable_start_string=VARIABLE_START_STRING,
- variable_end_string=VARIABLE_END_STRING,
- comment_start_string=COMMENT_START_STRING,
- comment_end_string=COMMENT_END_STRING,
- line_statement_prefix=LINE_STATEMENT_PREFIX,
- line_comment_prefix=LINE_COMMENT_PREFIX,
- trim_blocks=TRIM_BLOCKS,
- lstrip_blocks=LSTRIP_BLOCKS,
- newline_sequence=NEWLINE_SEQUENCE,
- keep_trailing_newline=KEEP_TRAILING_NEWLINE,
- extensions=(),
- optimized=True,
- undefined=Undefined,
- finalize=None,
- autoescape=False):
- env = get_spontaneous_environment(
- block_start_string, block_end_string, variable_start_string,
- variable_end_string, comment_start_string, comment_end_string,
- line_statement_prefix, line_comment_prefix, trim_blocks,
- lstrip_blocks, newline_sequence, keep_trailing_newline,
- frozenset(extensions), optimized, undefined, finalize, autoescape,
- None, 0, False, None)
- return env.from_string(source, template_class=cls)
-
- @classmethod
- def from_code(cls, environment, code, globals, uptodate=None):
- """Creates a template object from compiled code and the globals. This
- is used by the loaders and environment to create a template object.
- """
- namespace = {
- 'environment': environment,
- '__file__': code.co_filename
- }
- exec(code, namespace)
- rv = cls._from_namespace(environment, namespace, globals)
- rv._uptodate = uptodate
- return rv
-
- @classmethod
- def from_module_dict(cls, environment, module_dict, globals):
- """Creates a template object from a module. This is used by the
- module loader to create a template object.
-
- .. versionadded:: 2.4
- """
- return cls._from_namespace(environment, module_dict, globals)
-
- @classmethod
- def _from_namespace(cls, environment, namespace, globals):
- t = object.__new__(cls)
- t.environment = environment
- t.globals = globals
- t.name = namespace['name']
- t.filename = namespace['__file__']
- t.blocks = namespace['blocks']
-
- # render function and module
- t.root_render_func = namespace['root']
- t._module = None
-
- # debug and loader helpers
- t._debug_info = namespace['debug_info']
- t._uptodate = None
-
- # store the reference
- namespace['environment'] = environment
- namespace['__jinja_template__'] = t
-
- return t
-
- def render(self, *args, **kwargs):
- """This method accepts the same arguments as the `dict` constructor:
- A dict, a dict subclass or some keyword arguments. If no arguments
- are given the context will be empty. These two calls do the same::
-
- template.render(knights='that say nih')
- template.render({'knights': 'that say nih'})
-
- This will return the rendered template as unicode string.
- """
- vars = dict(*args, **kwargs)
- try:
- return concat(self.root_render_func(self.new_context(vars)))
- except Exception:
- exc_info = sys.exc_info()
- return self.environment.handle_exception(exc_info, True)
-
- def stream(self, *args, **kwargs):
- """Works exactly like :meth:`generate` but returns a
- :class:`TemplateStream`.
- """
- return TemplateStream(self.generate(*args, **kwargs))
-
- def generate(self, *args, **kwargs):
- """For very large templates it can be useful to not render the whole
- template at once but evaluate each statement after another and yield
- piece for piece. This method basically does exactly that and returns
- a generator that yields one item after another as unicode strings.
-
- It accepts the same arguments as :meth:`render`.
- """
- vars = dict(*args, **kwargs)
- try:
- for event in self.root_render_func(self.new_context(vars)):
- yield event
- except Exception:
- exc_info = sys.exc_info()
- else:
- return
- yield self.environment.handle_exception(exc_info, True)
-
- def new_context(self, vars=None, shared=False, locals=None):
- """Create a new :class:`Context` for this template. The vars
- provided will be passed to the template. Per default the globals
- are added to the context. If shared is set to `True` the data
- is passed as it to the context without adding the globals.
-
- `locals` can be a dict of local variables for internal usage.
- """
- return new_context(self.environment, self.name, self.blocks,
- vars, shared, self.globals, locals)
-
- def make_module(self, vars=None, shared=False, locals=None):
- """This method works like the :attr:`module` attribute when called
- without arguments but it will evaluate the template on every call
- rather than caching it. It's also possible to provide
- a dict which is then used as context. The arguments are the same
- as for the :meth:`new_context` method.
- """
- return TemplateModule(self, self.new_context(vars, shared, locals))
-
- @property
- def module(self):
- """The template as module. This is used for imports in the
- template runtime but is also useful if one wants to access
- exported template variables from the Python layer:
-
- >>> t = Template('{% macro foo() %}42{% endmacro %}23')
- >>> unicode(t.module)
- u'23'
- >>> t.module.foo()
- u'42'
- """
- if self._module is not None:
- return self._module
- self._module = rv = self.make_module()
- return rv
-
- def get_corresponding_lineno(self, lineno):
- """Return the source line number of a line number in the
- generated bytecode as they are not in sync.
- """
- for template_line, code_line in reversed(self.debug_info):
- if code_line <= lineno:
- return template_line
- return 1
-
- @property
- def is_up_to_date(self):
- """If this variable is `False` there is a newer version available."""
- if self._uptodate is None:
- return True
- return self._uptodate()
-
- @property
- def debug_info(self):
- """The debug info mapping."""
- return [tuple(imap(int, x.split('='))) for x in
- self._debug_info.split('&')]
-
- def __repr__(self):
- if self.name is None:
- name = 'memory:%x' % id(self)
- else:
- name = repr(self.name)
- return '<%s %s>' % (self.__class__.__name__, name)
-
-
-@implements_to_string
-class TemplateModule(object):
- """Represents an imported template. All the exported names of the
- template are available as attributes on this object. Additionally
- converting it into an unicode- or bytestrings renders the contents.
- """
-
- def __init__(self, template, context):
- self._body_stream = list(template.root_render_func(context))
- self.__dict__.update(context.get_exported())
- self.__name__ = template.name
-
- def __html__(self):
- return Markup(concat(self._body_stream))
-
- def __str__(self):
- return concat(self._body_stream)
-
- def __repr__(self):
- if self.__name__ is None:
- name = 'memory:%x' % id(self)
- else:
- name = repr(self.__name__)
- return '<%s %s>' % (self.__class__.__name__, name)
-
-
-class TemplateExpression(object):
- """The :meth:`jinja2.Environment.compile_expression` method returns an
- instance of this object. It encapsulates the expression-like access
- to the template with an expression it wraps.
- """
-
- def __init__(self, template, undefined_to_none):
- self._template = template
- self._undefined_to_none = undefined_to_none
-
- def __call__(self, *args, **kwargs):
- context = self._template.new_context(dict(*args, **kwargs))
- consume(self._template.root_render_func(context))
- rv = context.vars['result']
- if self._undefined_to_none and isinstance(rv, Undefined):
- rv = None
- return rv
-
-
-@implements_iterator
-class TemplateStream(object):
- """A template stream works pretty much like an ordinary python generator
- but it can buffer multiple items to reduce the number of total iterations.
- Per default the output is unbuffered which means that for every unbuffered
- instruction in the template one unicode string is yielded.
-
- If buffering is enabled with a buffer size of 5, five items are combined
- into a new unicode string. This is mainly useful if you are streaming
- big templates to a client via WSGI which flushes after each iteration.
- """
-
- def __init__(self, gen):
- self._gen = gen
- self.disable_buffering()
-
- def dump(self, fp, encoding=None, errors='strict'):
- """Dump the complete stream into a file or file-like object.
- Per default unicode strings are written, if you want to encode
- before writing specify an `encoding`.
-
- Example usage::
-
- Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
- """
- close = False
- if isinstance(fp, string_types):
- fp = open(fp, encoding is None and 'w' or 'wb')
- close = True
- try:
- if encoding is not None:
- iterable = (x.encode(encoding, errors) for x in self)
- else:
- iterable = self
- if hasattr(fp, 'writelines'):
- fp.writelines(iterable)
- else:
- for item in iterable:
- fp.write(item)
- finally:
- if close:
- fp.close()
-
- def disable_buffering(self):
- """Disable the output buffering."""
- self._next = get_next(self._gen)
- self.buffered = False
-
- def enable_buffering(self, size=5):
- """Enable buffering. Buffer `size` items before yielding them."""
- if size <= 1:
- raise ValueError('buffer size too small')
-
- def generator(next):
- buf = []
- c_size = 0
- push = buf.append
-
- while 1:
- try:
- while c_size < size:
- c = next()
- push(c)
- if c:
- c_size += 1
- except StopIteration:
- if not c_size:
- return
- yield concat(buf)
- del buf[:]
- c_size = 0
-
- self.buffered = True
- self._next = get_next(generator(get_next(self._gen)))
-
- def __iter__(self):
- return self
-
- def __next__(self):
- return self._next()
-
-
-# hook in default template class. if anyone reads this comment: ignore that
-# it's possible to use custom templates ;-)
-Environment.template_class = Template
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/exceptions.py b/Darwin/lib/python2.7/site-packages/jinja2/exceptions.py
deleted file mode 100644
index c9df6dc..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/exceptions.py
+++ /dev/null
@@ -1,146 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.exceptions
- ~~~~~~~~~~~~~~~~~
-
- Jinja exceptions.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2._compat import imap, text_type, PY2, implements_to_string
-
-
-class TemplateError(Exception):
- """Baseclass for all template errors."""
-
- if PY2:
- def __init__(self, message=None):
- if message is not None:
- message = text_type(message).encode('utf-8')
- Exception.__init__(self, message)
-
- @property
- def message(self):
- if self.args:
- message = self.args[0]
- if message is not None:
- return message.decode('utf-8', 'replace')
-
- def __unicode__(self):
- return self.message or u''
- else:
- def __init__(self, message=None):
- Exception.__init__(self, message)
-
- @property
- def message(self):
- if self.args:
- message = self.args[0]
- if message is not None:
- return message
-
-
-@implements_to_string
-class TemplateNotFound(IOError, LookupError, TemplateError):
- """Raised if a template does not exist."""
-
- # looks weird, but removes the warning descriptor that just
- # bogusly warns us about message being deprecated
- message = None
-
- def __init__(self, name, message=None):
- IOError.__init__(self)
- if message is None:
- message = name
- self.message = message
- self.name = name
- self.templates = [name]
-
- def __str__(self):
- return self.message
-
-
-class TemplatesNotFound(TemplateNotFound):
- """Like :class:`TemplateNotFound` but raised if multiple templates
- are selected. This is a subclass of :class:`TemplateNotFound`
- exception, so just catching the base exception will catch both.
-
- .. versionadded:: 2.2
- """
-
- def __init__(self, names=(), message=None):
- if message is None:
- message = u'none of the templates given were found: ' + \
- u', '.join(imap(text_type, names))
- TemplateNotFound.__init__(self, names and names[-1] or None, message)
- self.templates = list(names)
-
-
-@implements_to_string
-class TemplateSyntaxError(TemplateError):
- """Raised to tell the user that there is a problem with the template."""
-
- def __init__(self, message, lineno, name=None, filename=None):
- TemplateError.__init__(self, message)
- self.lineno = lineno
- self.name = name
- self.filename = filename
- self.source = None
-
- # this is set to True if the debug.translate_syntax_error
- # function translated the syntax error into a new traceback
- self.translated = False
-
- def __str__(self):
- # for translated errors we only return the message
- if self.translated:
- return self.message
-
- # otherwise attach some stuff
- location = 'line %d' % self.lineno
- name = self.filename or self.name
- if name:
- location = 'File "%s", %s' % (name, location)
- lines = [self.message, ' ' + location]
-
- # if the source is set, add the line to the output
- if self.source is not None:
- try:
- line = self.source.splitlines()[self.lineno - 1]
- except IndexError:
- line = None
- if line:
- lines.append(' ' + line.strip())
-
- return u'\n'.join(lines)
-
-
-class TemplateAssertionError(TemplateSyntaxError):
- """Like a template syntax error, but covers cases where something in the
- template caused an error at compile time that wasn't necessarily caused
- by a syntax error. However it's a direct subclass of
- :exc:`TemplateSyntaxError` and has the same attributes.
- """
-
-
-class TemplateRuntimeError(TemplateError):
- """A generic runtime error in the template engine. Under some situations
- Jinja may raise this exception.
- """
-
-
-class UndefinedError(TemplateRuntimeError):
- """Raised if a template tries to operate on :class:`Undefined`."""
-
-
-class SecurityError(TemplateRuntimeError):
- """Raised if a template tries to do something insecure if the
- sandbox is enabled.
- """
-
-
-class FilterArgumentError(TemplateRuntimeError):
- """This error is raised if a filter was called with inappropriate
- arguments
- """
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/ext.py b/Darwin/lib/python2.7/site-packages/jinja2/ext.py
deleted file mode 100644
index c2df12d..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/ext.py
+++ /dev/null
@@ -1,636 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.ext
- ~~~~~~~~~~
-
- Jinja extensions allow to add custom tags similar to the way django custom
- tags work. By default two example extensions exist: an i18n and a cache
- extension.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD.
-"""
-from jinja2 import nodes
-from jinja2.defaults import BLOCK_START_STRING, \
- BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \
- COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \
- LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \
- KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS
-from jinja2.environment import Environment
-from jinja2.runtime import concat
-from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError
-from jinja2.utils import contextfunction, import_string, Markup
-from jinja2._compat import next, with_metaclass, string_types, iteritems
-
-
-# the only real useful gettext functions for a Jinja template. Note
-# that ugettext must be assigned to gettext as Jinja doesn't support
-# non unicode strings.
-GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')
-
-
-class ExtensionRegistry(type):
- """Gives the extension an unique identifier."""
-
- def __new__(cls, name, bases, d):
- rv = type.__new__(cls, name, bases, d)
- rv.identifier = rv.__module__ + '.' + rv.__name__
- return rv
-
-
-class Extension(with_metaclass(ExtensionRegistry, object)):
- """Extensions can be used to add extra functionality to the Jinja template
- system at the parser level. Custom extensions are bound to an environment
- but may not store environment specific data on `self`. The reason for
- this is that an extension can be bound to another environment (for
- overlays) by creating a copy and reassigning the `environment` attribute.
-
- As extensions are created by the environment they cannot accept any
- arguments for configuration. One may want to work around that by using
- a factory function, but that is not possible as extensions are identified
- by their import name. The correct way to configure the extension is
- storing the configuration values on the environment. Because this way the
- environment ends up acting as central configuration storage the
- attributes may clash which is why extensions have to ensure that the names
- they choose for configuration are not too generic. ``prefix`` for example
- is a terrible name, ``fragment_cache_prefix`` on the other hand is a good
- name as includes the name of the extension (fragment cache).
- """
-
- #: if this extension parses this is the list of tags it's listening to.
- tags = set()
-
- #: the priority of that extension. This is especially useful for
- #: extensions that preprocess values. A lower value means higher
- #: priority.
- #:
- #: .. versionadded:: 2.4
- priority = 100
-
- def __init__(self, environment):
- self.environment = environment
-
- def bind(self, environment):
- """Create a copy of this extension bound to another environment."""
- rv = object.__new__(self.__class__)
- rv.__dict__.update(self.__dict__)
- rv.environment = environment
- return rv
-
- def preprocess(self, source, name, filename=None):
- """This method is called before the actual lexing and can be used to
- preprocess the source. The `filename` is optional. The return value
- must be the preprocessed source.
- """
- return source
-
- def filter_stream(self, stream):
- """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
- to filter tokens returned. This method has to return an iterable of
- :class:`~jinja2.lexer.Token`\s, but it doesn't have to return a
- :class:`~jinja2.lexer.TokenStream`.
-
- In the `ext` folder of the Jinja2 source distribution there is a file
- called `inlinegettext.py` which implements a filter that utilizes this
- method.
- """
- return stream
-
- def parse(self, parser):
- """If any of the :attr:`tags` matched this method is called with the
- parser as first argument. The token the parser stream is pointing at
- is the name token that matched. This method has to return one or a
- list of multiple nodes.
- """
- raise NotImplementedError()
-
- def attr(self, name, lineno=None):
- """Return an attribute node for the current extension. This is useful
- to pass constants on extensions to generated template code.
-
- ::
-
- self.attr('_my_attribute', lineno=lineno)
- """
- return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
-
- def call_method(self, name, args=None, kwargs=None, dyn_args=None,
- dyn_kwargs=None, lineno=None):
- """Call a method of the extension. This is a shortcut for
- :meth:`attr` + :class:`jinja2.nodes.Call`.
- """
- if args is None:
- args = []
- if kwargs is None:
- kwargs = []
- return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
- dyn_args, dyn_kwargs, lineno=lineno)
-
-
-@contextfunction
-def _gettext_alias(__context, *args, **kwargs):
- return __context.call(__context.resolve('gettext'), *args, **kwargs)
-
-
-def _make_new_gettext(func):
- @contextfunction
- def gettext(__context, __string, **variables):
- rv = __context.call(func, __string)
- if __context.eval_ctx.autoescape:
- rv = Markup(rv)
- return rv % variables
- return gettext
-
-
-def _make_new_ngettext(func):
- @contextfunction
- def ngettext(__context, __singular, __plural, __num, **variables):
- variables.setdefault('num', __num)
- rv = __context.call(func, __singular, __plural, __num)
- if __context.eval_ctx.autoescape:
- rv = Markup(rv)
- return rv % variables
- return ngettext
-
-
-class InternationalizationExtension(Extension):
- """This extension adds gettext support to Jinja2."""
- tags = set(['trans'])
-
- # TODO: the i18n extension is currently reevaluating values in a few
- # situations. Take this example:
- # {% trans count=something() %}{{ count }} foo{% pluralize
- # %}{{ count }} fooss{% endtrans %}
- # something is called twice here. One time for the gettext value and
- # the other time for the n-parameter of the ngettext function.
-
- def __init__(self, environment):
- Extension.__init__(self, environment)
- environment.globals['_'] = _gettext_alias
- environment.extend(
- install_gettext_translations=self._install,
- install_null_translations=self._install_null,
- install_gettext_callables=self._install_callables,
- uninstall_gettext_translations=self._uninstall,
- extract_translations=self._extract,
- newstyle_gettext=False
- )
-
- def _install(self, translations, newstyle=None):
- gettext = getattr(translations, 'ugettext', None)
- if gettext is None:
- gettext = translations.gettext
- ngettext = getattr(translations, 'ungettext', None)
- if ngettext is None:
- ngettext = translations.ngettext
- self._install_callables(gettext, ngettext, newstyle)
-
- def _install_null(self, newstyle=None):
- self._install_callables(
- lambda x: x,
- lambda s, p, n: (n != 1 and (p,) or (s,))[0],
- newstyle
- )
-
- def _install_callables(self, gettext, ngettext, newstyle=None):
- if newstyle is not None:
- self.environment.newstyle_gettext = newstyle
- if self.environment.newstyle_gettext:
- gettext = _make_new_gettext(gettext)
- ngettext = _make_new_ngettext(ngettext)
- self.environment.globals.update(
- gettext=gettext,
- ngettext=ngettext
- )
-
- def _uninstall(self, translations):
- for key in 'gettext', 'ngettext':
- self.environment.globals.pop(key, None)
-
- def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):
- if isinstance(source, string_types):
- source = self.environment.parse(source)
- return extract_from_ast(source, gettext_functions)
-
- def parse(self, parser):
- """Parse a translatable tag."""
- lineno = next(parser.stream).lineno
- num_called_num = False
-
- # find all the variables referenced. Additionally a variable can be
- # defined in the body of the trans block too, but this is checked at
- # a later state.
- plural_expr = None
- plural_expr_assignment = None
- variables = {}
- while parser.stream.current.type != 'block_end':
- if variables:
- parser.stream.expect('comma')
-
- # skip colon for python compatibility
- if parser.stream.skip_if('colon'):
- break
-
- name = parser.stream.expect('name')
- if name.value in variables:
- parser.fail('translatable variable %r defined twice.' %
- name.value, name.lineno,
- exc=TemplateAssertionError)
-
- # expressions
- if parser.stream.current.type == 'assign':
- next(parser.stream)
- variables[name.value] = var = parser.parse_expression()
- else:
- variables[name.value] = var = nodes.Name(name.value, 'load')
-
- if plural_expr is None:
- if isinstance(var, nodes.Call):
- plural_expr = nodes.Name('_trans', 'load')
- variables[name.value] = plural_expr
- plural_expr_assignment = nodes.Assign(
- nodes.Name('_trans', 'store'), var)
- else:
- plural_expr = var
- num_called_num = name.value == 'num'
-
- parser.stream.expect('block_end')
-
- plural = plural_names = None
- have_plural = False
- referenced = set()
-
- # now parse until endtrans or pluralize
- singular_names, singular = self._parse_block(parser, True)
- if singular_names:
- referenced.update(singular_names)
- if plural_expr is None:
- plural_expr = nodes.Name(singular_names[0], 'load')
- num_called_num = singular_names[0] == 'num'
-
- # if we have a pluralize block, we parse that too
- if parser.stream.current.test('name:pluralize'):
- have_plural = True
- next(parser.stream)
- if parser.stream.current.type != 'block_end':
- name = parser.stream.expect('name')
- if name.value not in variables:
- parser.fail('unknown variable %r for pluralization' %
- name.value, name.lineno,
- exc=TemplateAssertionError)
- plural_expr = variables[name.value]
- num_called_num = name.value == 'num'
- parser.stream.expect('block_end')
- plural_names, plural = self._parse_block(parser, False)
- next(parser.stream)
- referenced.update(plural_names)
- else:
- next(parser.stream)
-
- # register free names as simple name expressions
- for var in referenced:
- if var not in variables:
- variables[var] = nodes.Name(var, 'load')
-
- if not have_plural:
- plural_expr = None
- elif plural_expr is None:
- parser.fail('pluralize without variables', lineno)
-
- node = self._make_node(singular, plural, variables, plural_expr,
- bool(referenced),
- num_called_num and have_plural)
- node.set_lineno(lineno)
- if plural_expr_assignment is not None:
- return [plural_expr_assignment, node]
- else:
- return node
-
- def _parse_block(self, parser, allow_pluralize):
- """Parse until the next block tag with a given name."""
- referenced = []
- buf = []
- while 1:
- if parser.stream.current.type == 'data':
- buf.append(parser.stream.current.value.replace('%', '%%'))
- next(parser.stream)
- elif parser.stream.current.type == 'variable_begin':
- next(parser.stream)
- name = parser.stream.expect('name').value
- referenced.append(name)
- buf.append('%%(%s)s' % name)
- parser.stream.expect('variable_end')
- elif parser.stream.current.type == 'block_begin':
- next(parser.stream)
- if parser.stream.current.test('name:endtrans'):
- break
- elif parser.stream.current.test('name:pluralize'):
- if allow_pluralize:
- break
- parser.fail('a translatable section can have only one '
- 'pluralize section')
- parser.fail('control structures in translatable sections are '
- 'not allowed')
- elif parser.stream.eos:
- parser.fail('unclosed translation block')
- else:
- assert False, 'internal parser error'
-
- return referenced, concat(buf)
-
- def _make_node(self, singular, plural, variables, plural_expr,
- vars_referenced, num_called_num):
- """Generates a useful node from the data provided."""
- # no variables referenced? no need to escape for old style
- # gettext invocations only if there are vars.
- if not vars_referenced and not self.environment.newstyle_gettext:
- singular = singular.replace('%%', '%')
- if plural:
- plural = plural.replace('%%', '%')
-
- # singular only:
- if plural_expr is None:
- gettext = nodes.Name('gettext', 'load')
- node = nodes.Call(gettext, [nodes.Const(singular)],
- [], None, None)
-
- # singular and plural
- else:
- ngettext = nodes.Name('ngettext', 'load')
- node = nodes.Call(ngettext, [
- nodes.Const(singular),
- nodes.Const(plural),
- plural_expr
- ], [], None, None)
-
- # in case newstyle gettext is used, the method is powerful
- # enough to handle the variable expansion and autoescape
- # handling itself
- if self.environment.newstyle_gettext:
- for key, value in iteritems(variables):
- # the function adds that later anyways in case num was
- # called num, so just skip it.
- if num_called_num and key == 'num':
- continue
- node.kwargs.append(nodes.Keyword(key, value))
-
- # otherwise do that here
- else:
- # mark the return value as safe if we are in an
- # environment with autoescaping turned on
- node = nodes.MarkSafeIfAutoescape(node)
- if variables:
- node = nodes.Mod(node, nodes.Dict([
- nodes.Pair(nodes.Const(key), value)
- for key, value in variables.items()
- ]))
- return nodes.Output([node])
-
-
-class ExprStmtExtension(Extension):
- """Adds a `do` tag to Jinja2 that works like the print statement just
- that it doesn't print the return value.
- """
- tags = set(['do'])
-
- def parse(self, parser):
- node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
- node.node = parser.parse_tuple()
- return node
-
-
-class LoopControlExtension(Extension):
- """Adds break and continue to the template engine."""
- tags = set(['break', 'continue'])
-
- def parse(self, parser):
- token = next(parser.stream)
- if token.value == 'break':
- return nodes.Break(lineno=token.lineno)
- return nodes.Continue(lineno=token.lineno)
-
-
-class WithExtension(Extension):
- """Adds support for a django-like with block."""
- tags = set(['with'])
-
- def parse(self, parser):
- node = nodes.Scope(lineno=next(parser.stream).lineno)
- assignments = []
- while parser.stream.current.type != 'block_end':
- lineno = parser.stream.current.lineno
- if assignments:
- parser.stream.expect('comma')
- target = parser.parse_assign_target()
- parser.stream.expect('assign')
- expr = parser.parse_expression()
- assignments.append(nodes.Assign(target, expr, lineno=lineno))
- node.body = assignments + \
- list(parser.parse_statements(('name:endwith',),
- drop_needle=True))
- return node
-
-
-class AutoEscapeExtension(Extension):
- """Changes auto escape rules for a scope."""
- tags = set(['autoescape'])
-
- def parse(self, parser):
- node = nodes.ScopedEvalContextModifier(lineno=next(parser.stream).lineno)
- node.options = [
- nodes.Keyword('autoescape', parser.parse_expression())
- ]
- node.body = parser.parse_statements(('name:endautoescape',),
- drop_needle=True)
- return nodes.Scope([node])
-
-
-def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,
- babel_style=True):
- """Extract localizable strings from the given template node. Per
- default this function returns matches in babel style that means non string
- parameters as well as keyword arguments are returned as `None`. This
- allows Babel to figure out what you really meant if you are using
- gettext functions that allow keyword arguments for placeholder expansion.
- If you don't want that behavior set the `babel_style` parameter to `False`
- which causes only strings to be returned and parameters are always stored
- in tuples. As a consequence invalid gettext calls (calls without a single
- string parameter or string parameters after non-string parameters) are
- skipped.
-
- This example explains the behavior:
-
- >>> from jinja2 import Environment
- >>> env = Environment()
- >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')
- >>> list(extract_from_ast(node))
- [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
- >>> list(extract_from_ast(node, babel_style=False))
- [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
-
- For every string found this function yields a ``(lineno, function,
- message)`` tuple, where:
-
- * ``lineno`` is the number of the line on which the string was found,
- * ``function`` is the name of the ``gettext`` function used (if the
- string was extracted from embedded Python code), and
- * ``message`` is the string itself (a ``unicode`` object, or a tuple
- of ``unicode`` objects for functions with multiple string arguments).
-
- This extraction function operates on the AST and is because of that unable
- to extract any comments. For comment support you have to use the babel
- extraction interface or extract comments yourself.
- """
- for node in node.find_all(nodes.Call):
- if not isinstance(node.node, nodes.Name) or \
- node.node.name not in gettext_functions:
- continue
-
- strings = []
- for arg in node.args:
- if isinstance(arg, nodes.Const) and \
- isinstance(arg.value, string_types):
- strings.append(arg.value)
- else:
- strings.append(None)
-
- for arg in node.kwargs:
- strings.append(None)
- if node.dyn_args is not None:
- strings.append(None)
- if node.dyn_kwargs is not None:
- strings.append(None)
-
- if not babel_style:
- strings = tuple(x for x in strings if x is not None)
- if not strings:
- continue
- else:
- if len(strings) == 1:
- strings = strings[0]
- else:
- strings = tuple(strings)
- yield node.lineno, node.node.name, strings
-
-
-class _CommentFinder(object):
- """Helper class to find comments in a token stream. Can only
- find comments for gettext calls forwards. Once the comment
- from line 4 is found, a comment for line 1 will not return a
- usable value.
- """
-
- def __init__(self, tokens, comment_tags):
- self.tokens = tokens
- self.comment_tags = comment_tags
- self.offset = 0
- self.last_lineno = 0
-
- def find_backwards(self, offset):
- try:
- for _, token_type, token_value in \
- reversed(self.tokens[self.offset:offset]):
- if token_type in ('comment', 'linecomment'):
- try:
- prefix, comment = token_value.split(None, 1)
- except ValueError:
- continue
- if prefix in self.comment_tags:
- return [comment.rstrip()]
- return []
- finally:
- self.offset = offset
-
- def find_comments(self, lineno):
- if not self.comment_tags or self.last_lineno > lineno:
- return []
- for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset:]):
- if token_lineno > lineno:
- return self.find_backwards(self.offset + idx)
- return self.find_backwards(len(self.tokens))
-
-
-def babel_extract(fileobj, keywords, comment_tags, options):
- """Babel extraction method for Jinja templates.
-
- .. versionchanged:: 2.3
- Basic support for translation comments was added. If `comment_tags`
- is now set to a list of keywords for extraction, the extractor will
- try to find the best preceeding comment that begins with one of the
- keywords. For best results, make sure to not have more than one
- gettext call in one line of code and the matching comment in the
- same line or the line before.
-
- .. versionchanged:: 2.5.1
- The `newstyle_gettext` flag can be set to `True` to enable newstyle
- gettext calls.
-
- .. versionchanged:: 2.7
- A `silent` option can now be provided. If set to `False` template
- syntax errors are propagated instead of being ignored.
-
- :param fileobj: the file-like object the messages should be extracted from
- :param keywords: a list of keywords (i.e. function names) that should be
- recognized as translation functions
- :param comment_tags: a list of translator tags to search for and include
- in the results.
- :param options: a dictionary of additional options (optional)
- :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
- (comments will be empty currently)
- """
- extensions = set()
- for extension in options.get('extensions', '').split(','):
- extension = extension.strip()
- if not extension:
- continue
- extensions.add(import_string(extension))
- if InternationalizationExtension not in extensions:
- extensions.add(InternationalizationExtension)
-
- def getbool(options, key, default=False):
- return options.get(key, str(default)).lower() in \
- ('1', 'on', 'yes', 'true')
-
- silent = getbool(options, 'silent', True)
- environment = Environment(
- options.get('block_start_string', BLOCK_START_STRING),
- options.get('block_end_string', BLOCK_END_STRING),
- options.get('variable_start_string', VARIABLE_START_STRING),
- options.get('variable_end_string', VARIABLE_END_STRING),
- options.get('comment_start_string', COMMENT_START_STRING),
- options.get('comment_end_string', COMMENT_END_STRING),
- options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
- options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
- getbool(options, 'trim_blocks', TRIM_BLOCKS),
- getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS),
- NEWLINE_SEQUENCE,
- getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE),
- frozenset(extensions),
- cache_size=0,
- auto_reload=False
- )
-
- if getbool(options, 'newstyle_gettext'):
- environment.newstyle_gettext = True
-
- source = fileobj.read().decode(options.get('encoding', 'utf-8'))
- try:
- node = environment.parse(source)
- tokens = list(environment.lex(environment.preprocess(source)))
- except TemplateSyntaxError as e:
- if not silent:
- raise
- # skip templates with syntax errors
- return
-
- finder = _CommentFinder(tokens, comment_tags)
- for lineno, func, message in extract_from_ast(node, keywords):
- yield lineno, func, message, finder.find_comments(lineno)
-
-
-#: nicer import names
-i18n = InternationalizationExtension
-do = ExprStmtExtension
-loopcontrols = LoopControlExtension
-with_ = WithExtension
-autoescape = AutoEscapeExtension
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/filters.py b/Darwin/lib/python2.7/site-packages/jinja2/filters.py
deleted file mode 100644
index fd0db04..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/filters.py
+++ /dev/null
@@ -1,987 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.filters
- ~~~~~~~~~~~~~~
-
- Bundled jinja filters.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import re
-import math
-
-from random import choice
-from operator import itemgetter
-from itertools import groupby
-from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \
- unicode_urlencode
-from jinja2.runtime import Undefined
-from jinja2.exceptions import FilterArgumentError
-from jinja2._compat import next, imap, string_types, text_type, iteritems
-
-
-_word_re = re.compile(r'\w+(?u)')
-
-
-def contextfilter(f):
- """Decorator for marking context dependent filters. The current
- :class:`Context` will be passed as first argument.
- """
- f.contextfilter = True
- return f
-
-
-def evalcontextfilter(f):
- """Decorator for marking eval-context dependent filters. An eval
- context object is passed as first argument. For more information
- about the eval context, see :ref:`eval-context`.
-
- .. versionadded:: 2.4
- """
- f.evalcontextfilter = True
- return f
-
-
-def environmentfilter(f):
- """Decorator for marking evironment dependent filters. The current
- :class:`Environment` is passed to the filter as first argument.
- """
- f.environmentfilter = True
- return f
-
-
-def make_attrgetter(environment, attribute):
- """Returns a callable that looks up the given attribute from a
- passed object with the rules of the environment. Dots are allowed
- to access attributes of attributes. Integer parts in paths are
- looked up as integers.
- """
- if not isinstance(attribute, string_types) \
- or ('.' not in attribute and not attribute.isdigit()):
- return lambda x: environment.getitem(x, attribute)
- attribute = attribute.split('.')
- def attrgetter(item):
- for part in attribute:
- if part.isdigit():
- part = int(part)
- item = environment.getitem(item, part)
- return item
- return attrgetter
-
-
-def do_forceescape(value):
- """Enforce HTML escaping. This will probably double escape variables."""
- if hasattr(value, '__html__'):
- value = value.__html__()
- return escape(text_type(value))
-
-
-def do_urlencode(value):
- """Escape strings for use in URLs (uses UTF-8 encoding). It accepts both
- dictionaries and regular strings as well as pairwise iterables.
-
- .. versionadded:: 2.7
- """
- itemiter = None
- if isinstance(value, dict):
- itemiter = iteritems(value)
- elif not isinstance(value, string_types):
- try:
- itemiter = iter(value)
- except TypeError:
- pass
- if itemiter is None:
- return unicode_urlencode(value)
- return u'&'.join(unicode_urlencode(k) + '=' +
- unicode_urlencode(v) for k, v in itemiter)
-
-
-@evalcontextfilter
-def do_replace(eval_ctx, s, old, new, count=None):
- """Return a copy of the value with all occurrences of a substring
- replaced with a new one. The first argument is the substring
- that should be replaced, the second is the replacement string.
- If the optional third argument ``count`` is given, only the first
- ``count`` occurrences are replaced:
-
- .. sourcecode:: jinja
-
- {{ "Hello World"|replace("Hello", "Goodbye") }}
- -> Goodbye World
-
- {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}
- -> d'oh, d'oh, aaargh
- """
- if count is None:
- count = -1
- if not eval_ctx.autoescape:
- return text_type(s).replace(text_type(old), text_type(new), count)
- if hasattr(old, '__html__') or hasattr(new, '__html__') and \
- not hasattr(s, '__html__'):
- s = escape(s)
- else:
- s = soft_unicode(s)
- return s.replace(soft_unicode(old), soft_unicode(new), count)
-
-
-def do_upper(s):
- """Convert a value to uppercase."""
- return soft_unicode(s).upper()
-
-
-def do_lower(s):
- """Convert a value to lowercase."""
- return soft_unicode(s).lower()
-
-
-@evalcontextfilter
-def do_xmlattr(_eval_ctx, d, autospace=True):
- """Create an SGML/XML attribute string based on the items in a dict.
- All values that are neither `none` nor `undefined` are automatically
- escaped:
-
- .. sourcecode:: html+jinja
-
-
-
- Results in something like this:
-
- .. sourcecode:: html
-
-
-
- As you can see it automatically prepends a space in front of the item
- if the filter returned something unless the second parameter is false.
- """
- rv = u' '.join(
- u'%s="%s"' % (escape(key), escape(value))
- for key, value in iteritems(d)
- if value is not None and not isinstance(value, Undefined)
- )
- if autospace and rv:
- rv = u' ' + rv
- if _eval_ctx.autoescape:
- rv = Markup(rv)
- return rv
-
-
-def do_capitalize(s):
- """Capitalize a value. The first character will be uppercase, all others
- lowercase.
- """
- return soft_unicode(s).capitalize()
-
-
-def do_title(s):
- """Return a titlecased version of the value. I.e. words will start with
- uppercase letters, all remaining characters are lowercase.
- """
- rv = []
- for item in re.compile(r'([-\s]+)(?u)').split(s):
- if not item:
- continue
- rv.append(item[0].upper() + item[1:].lower())
- return ''.join(rv)
-
-
-def do_dictsort(value, case_sensitive=False, by='key'):
- """Sort a dict and yield (key, value) pairs. Because python dicts are
- unsorted you may want to use this function to order them by either
- key or value:
-
- .. sourcecode:: jinja
-
- {% for item in mydict|dictsort %}
- sort the dict by key, case insensitive
-
- {% for item in mydict|dictsort(true) %}
- sort the dict by key, case sensitive
-
- {% for item in mydict|dictsort(false, 'value') %}
- sort the dict by key, case insensitive, sorted
- normally and ordered by value.
- """
- if by == 'key':
- pos = 0
- elif by == 'value':
- pos = 1
- else:
- raise FilterArgumentError('You can only sort by either '
- '"key" or "value"')
- def sort_func(item):
- value = item[pos]
- if isinstance(value, string_types) and not case_sensitive:
- value = value.lower()
- return value
-
- return sorted(value.items(), key=sort_func)
-
-
-@environmentfilter
-def do_sort(environment, value, reverse=False, case_sensitive=False,
- attribute=None):
- """Sort an iterable. Per default it sorts ascending, if you pass it
- true as first argument it will reverse the sorting.
-
- If the iterable is made of strings the third parameter can be used to
- control the case sensitiveness of the comparison which is disabled by
- default.
-
- .. sourcecode:: jinja
-
- {% for item in iterable|sort %}
- ...
- {% endfor %}
-
- It is also possible to sort by an attribute (for example to sort
- by the date of an object) by specifying the `attribute` parameter:
-
- .. sourcecode:: jinja
-
- {% for item in iterable|sort(attribute='date') %}
- ...
- {% endfor %}
-
- .. versionchanged:: 2.6
- The `attribute` parameter was added.
- """
- if not case_sensitive:
- def sort_func(item):
- if isinstance(item, string_types):
- item = item.lower()
- return item
- else:
- sort_func = None
- if attribute is not None:
- getter = make_attrgetter(environment, attribute)
- def sort_func(item, processor=sort_func or (lambda x: x)):
- return processor(getter(item))
- return sorted(value, key=sort_func, reverse=reverse)
-
-
-def do_default(value, default_value=u'', boolean=False):
- """If the value is undefined it will return the passed default value,
- otherwise the value of the variable:
-
- .. sourcecode:: jinja
-
- {{ my_variable|default('my_variable is not defined') }}
-
- This will output the value of ``my_variable`` if the variable was
- defined, otherwise ``'my_variable is not defined'``. If you want
- to use default with variables that evaluate to false you have to
- set the second parameter to `true`:
-
- .. sourcecode:: jinja
-
- {{ ''|default('the string was empty', true) }}
- """
- if isinstance(value, Undefined) or (boolean and not value):
- return default_value
- return value
-
-
-@evalcontextfilter
-def do_join(eval_ctx, value, d=u'', attribute=None):
- """Return a string which is the concatenation of the strings in the
- sequence. The separator between elements is an empty string per
- default, you can define it with the optional parameter:
-
- .. sourcecode:: jinja
-
- {{ [1, 2, 3]|join('|') }}
- -> 1|2|3
-
- {{ [1, 2, 3]|join }}
- -> 123
-
- It is also possible to join certain attributes of an object:
-
- .. sourcecode:: jinja
-
- {{ users|join(', ', attribute='username') }}
-
- .. versionadded:: 2.6
- The `attribute` parameter was added.
- """
- if attribute is not None:
- value = imap(make_attrgetter(eval_ctx.environment, attribute), value)
-
- # no automatic escaping? joining is a lot eaiser then
- if not eval_ctx.autoescape:
- return text_type(d).join(imap(text_type, value))
-
- # if the delimiter doesn't have an html representation we check
- # if any of the items has. If yes we do a coercion to Markup
- if not hasattr(d, '__html__'):
- value = list(value)
- do_escape = False
- for idx, item in enumerate(value):
- if hasattr(item, '__html__'):
- do_escape = True
- else:
- value[idx] = text_type(item)
- if do_escape:
- d = escape(d)
- else:
- d = text_type(d)
- return d.join(value)
-
- # no html involved, to normal joining
- return soft_unicode(d).join(imap(soft_unicode, value))
-
-
-def do_center(value, width=80):
- """Centers the value in a field of a given width."""
- return text_type(value).center(width)
-
-
-@environmentfilter
-def do_first(environment, seq):
- """Return the first item of a sequence."""
- try:
- return next(iter(seq))
- except StopIteration:
- return environment.undefined('No first item, sequence was empty.')
-
-
-@environmentfilter
-def do_last(environment, seq):
- """Return the last item of a sequence."""
- try:
- return next(iter(reversed(seq)))
- except StopIteration:
- return environment.undefined('No last item, sequence was empty.')
-
-
-@environmentfilter
-def do_random(environment, seq):
- """Return a random item from the sequence."""
- try:
- return choice(seq)
- except IndexError:
- return environment.undefined('No random item, sequence was empty.')
-
-
-def do_filesizeformat(value, binary=False):
- """Format the value like a 'human-readable' file size (i.e. 13 kB,
- 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,
- Giga, etc.), if the second parameter is set to `True` the binary
- prefixes are used (Mebi, Gibi).
- """
- bytes = float(value)
- base = binary and 1024 or 1000
- prefixes = [
- (binary and 'KiB' or 'kB'),
- (binary and 'MiB' or 'MB'),
- (binary and 'GiB' or 'GB'),
- (binary and 'TiB' or 'TB'),
- (binary and 'PiB' or 'PB'),
- (binary and 'EiB' or 'EB'),
- (binary and 'ZiB' or 'ZB'),
- (binary and 'YiB' or 'YB')
- ]
- if bytes == 1:
- return '1 Byte'
- elif bytes < base:
- return '%d Bytes' % bytes
- else:
- for i, prefix in enumerate(prefixes):
- unit = base ** (i + 2)
- if bytes < unit:
- return '%.1f %s' % ((base * bytes / unit), prefix)
- return '%.1f %s' % ((base * bytes / unit), prefix)
-
-
-def do_pprint(value, verbose=False):
- """Pretty print a variable. Useful for debugging.
-
- With Jinja 1.2 onwards you can pass it a parameter. If this parameter
- is truthy the output will be more verbose (this requires `pretty`)
- """
- return pformat(value, verbose=verbose)
-
-
-@evalcontextfilter
-def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False):
- """Converts URLs in plain text into clickable links.
-
- If you pass the filter an additional integer it will shorten the urls
- to that number. Also a third argument exists that makes the urls
- "nofollow":
-
- .. sourcecode:: jinja
-
- {{ mytext|urlize(40, true) }}
- links are shortened to 40 chars and defined with rel="nofollow"
- """
- rv = urlize(value, trim_url_limit, nofollow)
- if eval_ctx.autoescape:
- rv = Markup(rv)
- return rv
-
-
-def do_indent(s, width=4, indentfirst=False):
- """Return a copy of the passed string, each line indented by
- 4 spaces. The first line is not indented. If you want to
- change the number of spaces or indent the first line too
- you can pass additional parameters to the filter:
-
- .. sourcecode:: jinja
-
- {{ mytext|indent(2, true) }}
- indent by two spaces and indent the first line too.
- """
- indention = u' ' * width
- rv = (u'\n' + indention).join(s.splitlines())
- if indentfirst:
- rv = indention + rv
- return rv
-
-
-def do_truncate(s, length=255, killwords=False, end='...'):
- """Return a truncated copy of the string. The length is specified
- with the first parameter which defaults to ``255``. If the second
- parameter is ``true`` the filter will cut the text at length. Otherwise
- it will discard the last word. If the text was in fact
- truncated it will append an ellipsis sign (``"..."``). If you want a
- different ellipsis sign than ``"..."`` you can specify it using the
- third parameter.
-
- .. sourcecode:: jinja
-
- {{ "foo bar"|truncate(5) }}
- -> "foo ..."
- {{ "foo bar"|truncate(5, True) }}
- -> "foo b..."
- """
- if len(s) <= length:
- return s
- elif killwords:
- return s[:length] + end
- words = s.split(' ')
- result = []
- m = 0
- for word in words:
- m += len(word) + 1
- if m > length:
- break
- result.append(word)
- result.append(end)
- return u' '.join(result)
-
-@environmentfilter
-def do_wordwrap(environment, s, width=79, break_long_words=True,
- wrapstring=None):
- """
- Return a copy of the string passed to the filter wrapped after
- ``79`` characters. You can override this default using the first
- parameter. If you set the second parameter to `false` Jinja will not
- split words apart if they are longer than `width`. By default, the newlines
- will be the default newlines for the environment, but this can be changed
- using the wrapstring keyword argument.
-
- .. versionadded:: 2.7
- Added support for the `wrapstring` parameter.
- """
- if not wrapstring:
- wrapstring = environment.newline_sequence
- import textwrap
- return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
- replace_whitespace=False,
- break_long_words=break_long_words))
-
-
-def do_wordcount(s):
- """Count the words in that string."""
- return len(_word_re.findall(s))
-
-
-def do_int(value, default=0):
- """Convert the value into an integer. If the
- conversion doesn't work it will return ``0``. You can
- override this default using the first parameter.
- """
- try:
- return int(value)
- except (TypeError, ValueError):
- # this quirk is necessary so that "42.23"|int gives 42.
- try:
- return int(float(value))
- except (TypeError, ValueError):
- return default
-
-
-def do_float(value, default=0.0):
- """Convert the value into a floating point number. If the
- conversion doesn't work it will return ``0.0``. You can
- override this default using the first parameter.
- """
- try:
- return float(value)
- except (TypeError, ValueError):
- return default
-
-
-def do_format(value, *args, **kwargs):
- """
- Apply python string formatting on an object:
-
- .. sourcecode:: jinja
-
- {{ "%s - %s"|format("Hello?", "Foo!") }}
- -> Hello? - Foo!
- """
- if args and kwargs:
- raise FilterArgumentError('can\'t handle positional and keyword '
- 'arguments at the same time')
- return soft_unicode(value) % (kwargs or args)
-
-
-def do_trim(value):
- """Strip leading and trailing whitespace."""
- return soft_unicode(value).strip()
-
-
-def do_striptags(value):
- """Strip SGML/XML tags and replace adjacent whitespace by one space.
- """
- if hasattr(value, '__html__'):
- value = value.__html__()
- return Markup(text_type(value)).striptags()
-
-
-def do_slice(value, slices, fill_with=None):
- """Slice an iterator and return a list of lists containing
- those items. Useful if you want to create a div containing
- three ul tags that represent columns:
-
- .. sourcecode:: html+jinja
-
-
- {%- for column in items|slice(3) %}
-
- {%- for item in column %}
- - {{ item }}
- {%- endfor %}
-
- {%- endfor %}
-
-
- If you pass it a second argument it's used to fill missing
- values on the last iteration.
- """
- seq = list(value)
- length = len(seq)
- items_per_slice = length // slices
- slices_with_extra = length % slices
- offset = 0
- for slice_number in range(slices):
- start = offset + slice_number * items_per_slice
- if slice_number < slices_with_extra:
- offset += 1
- end = offset + (slice_number + 1) * items_per_slice
- tmp = seq[start:end]
- if fill_with is not None and slice_number >= slices_with_extra:
- tmp.append(fill_with)
- yield tmp
-
-
-def do_batch(value, linecount, fill_with=None):
- """
- A filter that batches items. It works pretty much like `slice`
- just the other way round. It returns a list of lists with the
- given number of items. If you provide a second parameter this
- is used to fill up missing items. See this example:
-
- .. sourcecode:: html+jinja
-
-
- {%- for row in items|batch(3, ' ') %}
-
- {%- for column in row %}
- {{ column }} |
- {%- endfor %}
-
- {%- endfor %}
-
- """
- result = []
- tmp = []
- for item in value:
- if len(tmp) == linecount:
- yield tmp
- tmp = []
- tmp.append(item)
- if tmp:
- if fill_with is not None and len(tmp) < linecount:
- tmp += [fill_with] * (linecount - len(tmp))
- yield tmp
-
-
-def do_round(value, precision=0, method='common'):
- """Round the number to a given precision. The first
- parameter specifies the precision (default is ``0``), the
- second the rounding method:
-
- - ``'common'`` rounds either up or down
- - ``'ceil'`` always rounds up
- - ``'floor'`` always rounds down
-
- If you don't specify a method ``'common'`` is used.
-
- .. sourcecode:: jinja
-
- {{ 42.55|round }}
- -> 43.0
- {{ 42.55|round(1, 'floor') }}
- -> 42.5
-
- Note that even if rounded to 0 precision, a float is returned. If
- you need a real integer, pipe it through `int`:
-
- .. sourcecode:: jinja
-
- {{ 42.55|round|int }}
- -> 43
- """
- if not method in ('common', 'ceil', 'floor'):
- raise FilterArgumentError('method must be common, ceil or floor')
- if method == 'common':
- return round(value, precision)
- func = getattr(math, method)
- return func(value * (10 ** precision)) / (10 ** precision)
-
-
-@environmentfilter
-def do_groupby(environment, value, attribute):
- """Group a sequence of objects by a common attribute.
-
- If you for example have a list of dicts or objects that represent persons
- with `gender`, `first_name` and `last_name` attributes and you want to
- group all users by genders you can do something like the following
- snippet:
-
- .. sourcecode:: html+jinja
-
-
- {% for group in persons|groupby('gender') %}
- - {{ group.grouper }}
- {% for person in group.list %}
- - {{ person.first_name }} {{ person.last_name }}
- {% endfor %}
- {% endfor %}
-
-
- Additionally it's possible to use tuple unpacking for the grouper and
- list:
-
- .. sourcecode:: html+jinja
-
-
- {% for grouper, list in persons|groupby('gender') %}
- ...
- {% endfor %}
-
-
- As you can see the item we're grouping by is stored in the `grouper`
- attribute and the `list` contains all the objects that have this grouper
- in common.
-
- .. versionchanged:: 2.6
- It's now possible to use dotted notation to group by the child
- attribute of another attribute.
- """
- expr = make_attrgetter(environment, attribute)
- return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))
-
-
-class _GroupTuple(tuple):
- __slots__ = ()
- grouper = property(itemgetter(0))
- list = property(itemgetter(1))
-
- def __new__(cls, xxx_todo_changeme):
- (key, value) = xxx_todo_changeme
- return tuple.__new__(cls, (key, list(value)))
-
-
-@environmentfilter
-def do_sum(environment, iterable, attribute=None, start=0):
- """Returns the sum of a sequence of numbers plus the value of parameter
- 'start' (which defaults to 0). When the sequence is empty it returns
- start.
-
- It is also possible to sum up only certain attributes:
-
- .. sourcecode:: jinja
-
- Total: {{ items|sum(attribute='price') }}
-
- .. versionchanged:: 2.6
- The `attribute` parameter was added to allow suming up over
- attributes. Also the `start` parameter was moved on to the right.
- """
- if attribute is not None:
- iterable = imap(make_attrgetter(environment, attribute), iterable)
- return sum(iterable, start)
-
-
-def do_list(value):
- """Convert the value into a list. If it was a string the returned list
- will be a list of characters.
- """
- return list(value)
-
-
-def do_mark_safe(value):
- """Mark the value as safe which means that in an environment with automatic
- escaping enabled this variable will not be escaped.
- """
- return Markup(value)
-
-
-def do_mark_unsafe(value):
- """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""
- return text_type(value)
-
-
-def do_reverse(value):
- """Reverse the object or return an iterator the iterates over it the other
- way round.
- """
- if isinstance(value, string_types):
- return value[::-1]
- try:
- return reversed(value)
- except TypeError:
- try:
- rv = list(value)
- rv.reverse()
- return rv
- except TypeError:
- raise FilterArgumentError('argument must be iterable')
-
-
-@environmentfilter
-def do_attr(environment, obj, name):
- """Get an attribute of an object. ``foo|attr("bar")`` works like
- ``foo["bar"]`` just that always an attribute is returned and items are not
- looked up.
-
- See :ref:`Notes on subscriptions ` for more details.
- """
- try:
- name = str(name)
- except UnicodeError:
- pass
- else:
- try:
- value = getattr(obj, name)
- except AttributeError:
- pass
- else:
- if environment.sandboxed and not \
- environment.is_safe_attribute(obj, name, value):
- return environment.unsafe_undefined(obj, name)
- return value
- return environment.undefined(obj=obj, name=name)
-
-
-@contextfilter
-def do_map(*args, **kwargs):
- """Applies a filter on a sequence of objects or looks up an attribute.
- This is useful when dealing with lists of objects but you are really
- only interested in a certain value of it.
-
- The basic usage is mapping on an attribute. Imagine you have a list
- of users but you are only interested in a list of usernames:
-
- .. sourcecode:: jinja
-
- Users on this page: {{ users|map(attribute='username')|join(', ') }}
-
- Alternatively you can let it invoke a filter by passing the name of the
- filter and the arguments afterwards. A good example would be applying a
- text conversion filter on a sequence:
-
- .. sourcecode:: jinja
-
- Users on this page: {{ titles|map('lower')|join(', ') }}
-
- .. versionadded:: 2.7
- """
- context = args[0]
- seq = args[1]
-
- if len(args) == 2 and 'attribute' in kwargs:
- attribute = kwargs.pop('attribute')
- if kwargs:
- raise FilterArgumentError('Unexpected keyword argument %r' %
- next(iter(kwargs)))
- func = make_attrgetter(context.environment, attribute)
- else:
- try:
- name = args[2]
- args = args[3:]
- except LookupError:
- raise FilterArgumentError('map requires a filter argument')
- func = lambda item: context.environment.call_filter(
- name, item, args, kwargs, context=context)
-
- if seq:
- for item in seq:
- yield func(item)
-
-
-@contextfilter
-def do_select(*args, **kwargs):
- """Filters a sequence of objects by appying a test to either the object
- or the attribute and only selecting the ones with the test succeeding.
-
- Example usage:
-
- .. sourcecode:: jinja
-
- {{ numbers|select("odd") }}
-
- .. versionadded:: 2.7
- """
- return _select_or_reject(args, kwargs, lambda x: x, False)
-
-
-@contextfilter
-def do_reject(*args, **kwargs):
- """Filters a sequence of objects by appying a test to either the object
- or the attribute and rejecting the ones with the test succeeding.
-
- Example usage:
-
- .. sourcecode:: jinja
-
- {{ numbers|reject("odd") }}
-
- .. versionadded:: 2.7
- """
- return _select_or_reject(args, kwargs, lambda x: not x, False)
-
-
-@contextfilter
-def do_selectattr(*args, **kwargs):
- """Filters a sequence of objects by appying a test to either the object
- or the attribute and only selecting the ones with the test succeeding.
-
- Example usage:
-
- .. sourcecode:: jinja
-
- {{ users|selectattr("is_active") }}
- {{ users|selectattr("email", "none") }}
-
- .. versionadded:: 2.7
- """
- return _select_or_reject(args, kwargs, lambda x: x, True)
-
-
-@contextfilter
-def do_rejectattr(*args, **kwargs):
- """Filters a sequence of objects by appying a test to either the object
- or the attribute and rejecting the ones with the test succeeding.
-
- .. sourcecode:: jinja
-
- {{ users|rejectattr("is_active") }}
- {{ users|rejectattr("email", "none") }}
-
- .. versionadded:: 2.7
- """
- return _select_or_reject(args, kwargs, lambda x: not x, True)
-
-
-def _select_or_reject(args, kwargs, modfunc, lookup_attr):
- context = args[0]
- seq = args[1]
- if lookup_attr:
- try:
- attr = args[2]
- except LookupError:
- raise FilterArgumentError('Missing parameter for attribute name')
- transfunc = make_attrgetter(context.environment, attr)
- off = 1
- else:
- off = 0
- transfunc = lambda x: x
-
- try:
- name = args[2 + off]
- args = args[3 + off:]
- func = lambda item: context.environment.call_test(
- name, item, args, kwargs)
- except LookupError:
- func = bool
-
- if seq:
- for item in seq:
- if modfunc(func(transfunc(item))):
- yield item
-
-
-FILTERS = {
- 'attr': do_attr,
- 'replace': do_replace,
- 'upper': do_upper,
- 'lower': do_lower,
- 'escape': escape,
- 'e': escape,
- 'forceescape': do_forceescape,
- 'capitalize': do_capitalize,
- 'title': do_title,
- 'default': do_default,
- 'd': do_default,
- 'join': do_join,
- 'count': len,
- 'dictsort': do_dictsort,
- 'sort': do_sort,
- 'length': len,
- 'reverse': do_reverse,
- 'center': do_center,
- 'indent': do_indent,
- 'title': do_title,
- 'capitalize': do_capitalize,
- 'first': do_first,
- 'last': do_last,
- 'map': do_map,
- 'random': do_random,
- 'reject': do_reject,
- 'rejectattr': do_rejectattr,
- 'filesizeformat': do_filesizeformat,
- 'pprint': do_pprint,
- 'truncate': do_truncate,
- 'wordwrap': do_wordwrap,
- 'wordcount': do_wordcount,
- 'int': do_int,
- 'float': do_float,
- 'string': soft_unicode,
- 'list': do_list,
- 'urlize': do_urlize,
- 'format': do_format,
- 'trim': do_trim,
- 'striptags': do_striptags,
- 'select': do_select,
- 'selectattr': do_selectattr,
- 'slice': do_slice,
- 'batch': do_batch,
- 'sum': do_sum,
- 'abs': abs,
- 'round': do_round,
- 'groupby': do_groupby,
- 'safe': do_mark_safe,
- 'xmlattr': do_xmlattr,
- 'urlencode': do_urlencode
-}
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/lexer.py b/Darwin/lib/python2.7/site-packages/jinja2/lexer.py
deleted file mode 100644
index a501285..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/lexer.py
+++ /dev/null
@@ -1,733 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.lexer
- ~~~~~~~~~~~~
-
- This module implements a Jinja / Python combination lexer. The
- `Lexer` class provided by this module is used to do some preprocessing
- for Jinja.
-
- On the one hand it filters out invalid operators like the bitshift
- operators we don't allow in templates. On the other hand it separates
- template code and python code in expressions.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import re
-
-from operator import itemgetter
-from collections import deque
-from jinja2.exceptions import TemplateSyntaxError
-from jinja2.utils import LRUCache
-from jinja2._compat import next, iteritems, implements_iterator, text_type, \
- intern
-
-
-# cache for the lexers. Exists in order to be able to have multiple
-# environments with the same lexer
-_lexer_cache = LRUCache(50)
-
-# static regular expressions
-whitespace_re = re.compile(r'\s+', re.U)
-string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
- r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)
-integer_re = re.compile(r'\d+')
-
-# we use the unicode identifier rule if this python version is able
-# to handle unicode identifiers, otherwise the standard ASCII one.
-try:
- compile('föö', '', 'eval')
-except SyntaxError:
- name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')
-else:
- from jinja2 import _stringdefs
- name_re = re.compile(r'[%s][%s]*' % (_stringdefs.xid_start,
- _stringdefs.xid_continue))
-
-float_re = re.compile(r'(?': TOKEN_GT,
- '>=': TOKEN_GTEQ,
- '<': TOKEN_LT,
- '<=': TOKEN_LTEQ,
- '=': TOKEN_ASSIGN,
- '.': TOKEN_DOT,
- ':': TOKEN_COLON,
- '|': TOKEN_PIPE,
- ',': TOKEN_COMMA,
- ';': TOKEN_SEMICOLON
-}
-
-reverse_operators = dict([(v, k) for k, v in iteritems(operators)])
-assert len(operators) == len(reverse_operators), 'operators dropped'
-operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in
- sorted(operators, key=lambda x: -len(x))))
-
-ignored_tokens = frozenset([TOKEN_COMMENT_BEGIN, TOKEN_COMMENT,
- TOKEN_COMMENT_END, TOKEN_WHITESPACE,
- TOKEN_WHITESPACE, TOKEN_LINECOMMENT_BEGIN,
- TOKEN_LINECOMMENT_END, TOKEN_LINECOMMENT])
-ignore_if_empty = frozenset([TOKEN_WHITESPACE, TOKEN_DATA,
- TOKEN_COMMENT, TOKEN_LINECOMMENT])
-
-
-def _describe_token_type(token_type):
- if token_type in reverse_operators:
- return reverse_operators[token_type]
- return {
- TOKEN_COMMENT_BEGIN: 'begin of comment',
- TOKEN_COMMENT_END: 'end of comment',
- TOKEN_COMMENT: 'comment',
- TOKEN_LINECOMMENT: 'comment',
- TOKEN_BLOCK_BEGIN: 'begin of statement block',
- TOKEN_BLOCK_END: 'end of statement block',
- TOKEN_VARIABLE_BEGIN: 'begin of print statement',
- TOKEN_VARIABLE_END: 'end of print statement',
- TOKEN_LINESTATEMENT_BEGIN: 'begin of line statement',
- TOKEN_LINESTATEMENT_END: 'end of line statement',
- TOKEN_DATA: 'template data / text',
- TOKEN_EOF: 'end of template'
- }.get(token_type, token_type)
-
-
-def describe_token(token):
- """Returns a description of the token."""
- if token.type == 'name':
- return token.value
- return _describe_token_type(token.type)
-
-
-def describe_token_expr(expr):
- """Like `describe_token` but for token expressions."""
- if ':' in expr:
- type, value = expr.split(':', 1)
- if type == 'name':
- return value
- else:
- type = expr
- return _describe_token_type(type)
-
-
-def count_newlines(value):
- """Count the number of newline characters in the string. This is
- useful for extensions that filter a stream.
- """
- return len(newline_re.findall(value))
-
-
-def compile_rules(environment):
- """Compiles all the rules from the environment into a list of rules."""
- e = re.escape
- rules = [
- (len(environment.comment_start_string), 'comment',
- e(environment.comment_start_string)),
- (len(environment.block_start_string), 'block',
- e(environment.block_start_string)),
- (len(environment.variable_start_string), 'variable',
- e(environment.variable_start_string))
- ]
-
- if environment.line_statement_prefix is not None:
- rules.append((len(environment.line_statement_prefix), 'linestatement',
- r'^[ \t\v]*' + e(environment.line_statement_prefix)))
- if environment.line_comment_prefix is not None:
- rules.append((len(environment.line_comment_prefix), 'linecomment',
- r'(?:^|(?<=\S))[^\S\r\n]*' +
- e(environment.line_comment_prefix)))
-
- return [x[1:] for x in sorted(rules, reverse=True)]
-
-
-class Failure(object):
- """Class that raises a `TemplateSyntaxError` if called.
- Used by the `Lexer` to specify known errors.
- """
-
- def __init__(self, message, cls=TemplateSyntaxError):
- self.message = message
- self.error_class = cls
-
- def __call__(self, lineno, filename):
- raise self.error_class(self.message, lineno, filename)
-
-
-class Token(tuple):
- """Token class."""
- __slots__ = ()
- lineno, type, value = (property(itemgetter(x)) for x in range(3))
-
- def __new__(cls, lineno, type, value):
- return tuple.__new__(cls, (lineno, intern(str(type)), value))
-
- def __str__(self):
- if self.type in reverse_operators:
- return reverse_operators[self.type]
- elif self.type == 'name':
- return self.value
- return self.type
-
- def test(self, expr):
- """Test a token against a token expression. This can either be a
- token type or ``'token_type:token_value'``. This can only test
- against string values and types.
- """
- # here we do a regular string equality check as test_any is usually
- # passed an iterable of not interned strings.
- if self.type == expr:
- return True
- elif ':' in expr:
- return expr.split(':', 1) == [self.type, self.value]
- return False
-
- def test_any(self, *iterable):
- """Test against multiple token expressions."""
- for expr in iterable:
- if self.test(expr):
- return True
- return False
-
- def __repr__(self):
- return 'Token(%r, %r, %r)' % (
- self.lineno,
- self.type,
- self.value
- )
-
-
-@implements_iterator
-class TokenStreamIterator(object):
- """The iterator for tokenstreams. Iterate over the stream
- until the eof token is reached.
- """
-
- def __init__(self, stream):
- self.stream = stream
-
- def __iter__(self):
- return self
-
- def __next__(self):
- token = self.stream.current
- if token.type is TOKEN_EOF:
- self.stream.close()
- raise StopIteration()
- next(self.stream)
- return token
-
-
-@implements_iterator
-class TokenStream(object):
- """A token stream is an iterable that yields :class:`Token`\s. The
- parser however does not iterate over it but calls :meth:`next` to go
- one token ahead. The current active token is stored as :attr:`current`.
- """
-
- def __init__(self, generator, name, filename):
- self._iter = iter(generator)
- self._pushed = deque()
- self.name = name
- self.filename = filename
- self.closed = False
- self.current = Token(1, TOKEN_INITIAL, '')
- next(self)
-
- def __iter__(self):
- return TokenStreamIterator(self)
-
- def __bool__(self):
- return bool(self._pushed) or self.current.type is not TOKEN_EOF
- __nonzero__ = __bool__ # py2
-
- eos = property(lambda x: not x, doc="Are we at the end of the stream?")
-
- def push(self, token):
- """Push a token back to the stream."""
- self._pushed.append(token)
-
- def look(self):
- """Look at the next token."""
- old_token = next(self)
- result = self.current
- self.push(result)
- self.current = old_token
- return result
-
- def skip(self, n=1):
- """Got n tokens ahead."""
- for x in range(n):
- next(self)
-
- def next_if(self, expr):
- """Perform the token test and return the token if it matched.
- Otherwise the return value is `None`.
- """
- if self.current.test(expr):
- return next(self)
-
- def skip_if(self, expr):
- """Like :meth:`next_if` but only returns `True` or `False`."""
- return self.next_if(expr) is not None
-
- def __next__(self):
- """Go one token ahead and return the old one"""
- rv = self.current
- if self._pushed:
- self.current = self._pushed.popleft()
- elif self.current.type is not TOKEN_EOF:
- try:
- self.current = next(self._iter)
- except StopIteration:
- self.close()
- return rv
-
- def close(self):
- """Close the stream."""
- self.current = Token(self.current.lineno, TOKEN_EOF, '')
- self._iter = None
- self.closed = True
-
- def expect(self, expr):
- """Expect a given token type and return it. This accepts the same
- argument as :meth:`jinja2.lexer.Token.test`.
- """
- if not self.current.test(expr):
- expr = describe_token_expr(expr)
- if self.current.type is TOKEN_EOF:
- raise TemplateSyntaxError('unexpected end of template, '
- 'expected %r.' % expr,
- self.current.lineno,
- self.name, self.filename)
- raise TemplateSyntaxError("expected token %r, got %r" %
- (expr, describe_token(self.current)),
- self.current.lineno,
- self.name, self.filename)
- try:
- return self.current
- finally:
- next(self)
-
-
-def get_lexer(environment):
- """Return a lexer which is probably cached."""
- key = (environment.block_start_string,
- environment.block_end_string,
- environment.variable_start_string,
- environment.variable_end_string,
- environment.comment_start_string,
- environment.comment_end_string,
- environment.line_statement_prefix,
- environment.line_comment_prefix,
- environment.trim_blocks,
- environment.lstrip_blocks,
- environment.newline_sequence,
- environment.keep_trailing_newline)
- lexer = _lexer_cache.get(key)
- if lexer is None:
- lexer = Lexer(environment)
- _lexer_cache[key] = lexer
- return lexer
-
-
-class Lexer(object):
- """Class that implements a lexer for a given environment. Automatically
- created by the environment class, usually you don't have to do that.
-
- Note that the lexer is not automatically bound to an environment.
- Multiple environments can share the same lexer.
- """
-
- def __init__(self, environment):
- # shortcuts
- c = lambda x: re.compile(x, re.M | re.S)
- e = re.escape
-
- # lexing rules for tags
- tag_rules = [
- (whitespace_re, TOKEN_WHITESPACE, None),
- (float_re, TOKEN_FLOAT, None),
- (integer_re, TOKEN_INTEGER, None),
- (name_re, TOKEN_NAME, None),
- (string_re, TOKEN_STRING, None),
- (operator_re, TOKEN_OPERATOR, None)
- ]
-
- # assemble the root lexing rule. because "|" is ungreedy
- # we have to sort by length so that the lexer continues working
- # as expected when we have parsing rules like <% for block and
- # <%= for variables. (if someone wants asp like syntax)
- # variables are just part of the rules if variable processing
- # is required.
- root_tag_rules = compile_rules(environment)
-
- # block suffix if trimming is enabled
- block_suffix_re = environment.trim_blocks and '\\n?' or ''
-
- # strip leading spaces if lstrip_blocks is enabled
- prefix_re = {}
- if environment.lstrip_blocks:
- # use '{%+' to manually disable lstrip_blocks behavior
- no_lstrip_re = e('+')
- # detect overlap between block and variable or comment strings
- block_diff = c(r'^%s(.*)' % e(environment.block_start_string))
- # make sure we don't mistake a block for a variable or a comment
- m = block_diff.match(environment.comment_start_string)
- no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''
- m = block_diff.match(environment.variable_start_string)
- no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''
-
- # detect overlap between comment and variable strings
- comment_diff = c(r'^%s(.*)' % e(environment.comment_start_string))
- m = comment_diff.match(environment.variable_start_string)
- no_variable_re = m and r'(?!%s)' % e(m.group(1)) or ''
-
- lstrip_re = r'^[ \t]*'
- block_prefix_re = r'%s%s(?!%s)|%s\+?' % (
- lstrip_re,
- e(environment.block_start_string),
- no_lstrip_re,
- e(environment.block_start_string),
- )
- comment_prefix_re = r'%s%s%s|%s\+?' % (
- lstrip_re,
- e(environment.comment_start_string),
- no_variable_re,
- e(environment.comment_start_string),
- )
- prefix_re['block'] = block_prefix_re
- prefix_re['comment'] = comment_prefix_re
- else:
- block_prefix_re = '%s' % e(environment.block_start_string)
-
- self.newline_sequence = environment.newline_sequence
- self.keep_trailing_newline = environment.keep_trailing_newline
-
- # global lexing rules
- self.rules = {
- 'root': [
- # directives
- (c('(.*?)(?:%s)' % '|'.join(
- [r'(?P(?:\s*%s\-|%s)\s*raw\s*(?:\-%s\s*|%s))' % (
- e(environment.block_start_string),
- block_prefix_re,
- e(environment.block_end_string),
- e(environment.block_end_string)
- )] + [
- r'(?P<%s_begin>\s*%s\-|%s)' % (n, r, prefix_re.get(n,r))
- for n, r in root_tag_rules
- ])), (TOKEN_DATA, '#bygroup'), '#bygroup'),
- # data
- (c('.+'), TOKEN_DATA, None)
- ],
- # comments
- TOKEN_COMMENT_BEGIN: [
- (c(r'(.*?)((?:\-%s\s*|%s)%s)' % (
- e(environment.comment_end_string),
- e(environment.comment_end_string),
- block_suffix_re
- )), (TOKEN_COMMENT, TOKEN_COMMENT_END), '#pop'),
- (c('(.)'), (Failure('Missing end of comment tag'),), None)
- ],
- # blocks
- TOKEN_BLOCK_BEGIN: [
- (c('(?:\-%s\s*|%s)%s' % (
- e(environment.block_end_string),
- e(environment.block_end_string),
- block_suffix_re
- )), TOKEN_BLOCK_END, '#pop'),
- ] + tag_rules,
- # variables
- TOKEN_VARIABLE_BEGIN: [
- (c('\-%s\s*|%s' % (
- e(environment.variable_end_string),
- e(environment.variable_end_string)
- )), TOKEN_VARIABLE_END, '#pop')
- ] + tag_rules,
- # raw block
- TOKEN_RAW_BEGIN: [
- (c('(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (
- e(environment.block_start_string),
- block_prefix_re,
- e(environment.block_end_string),
- e(environment.block_end_string),
- block_suffix_re
- )), (TOKEN_DATA, TOKEN_RAW_END), '#pop'),
- (c('(.)'), (Failure('Missing end of raw directive'),), None)
- ],
- # line statements
- TOKEN_LINESTATEMENT_BEGIN: [
- (c(r'\s*(\n|$)'), TOKEN_LINESTATEMENT_END, '#pop')
- ] + tag_rules,
- # line comments
- TOKEN_LINECOMMENT_BEGIN: [
- (c(r'(.*?)()(?=\n|$)'), (TOKEN_LINECOMMENT,
- TOKEN_LINECOMMENT_END), '#pop')
- ]
- }
-
- def _normalize_newlines(self, value):
- """Called for strings and template data to normalize it to unicode."""
- return newline_re.sub(self.newline_sequence, value)
-
- def tokenize(self, source, name=None, filename=None, state=None):
- """Calls tokeniter + tokenize and wraps it in a token stream.
- """
- stream = self.tokeniter(source, name, filename, state)
- return TokenStream(self.wrap(stream, name, filename), name, filename)
-
- def wrap(self, stream, name=None, filename=None):
- """This is called with the stream as returned by `tokenize` and wraps
- every token in a :class:`Token` and converts the value.
- """
- for lineno, token, value in stream:
- if token in ignored_tokens:
- continue
- elif token == 'linestatement_begin':
- token = 'block_begin'
- elif token == 'linestatement_end':
- token = 'block_end'
- # we are not interested in those tokens in the parser
- elif token in ('raw_begin', 'raw_end'):
- continue
- elif token == 'data':
- value = self._normalize_newlines(value)
- elif token == 'keyword':
- token = value
- elif token == 'name':
- value = str(value)
- elif token == 'string':
- # try to unescape string
- try:
- value = self._normalize_newlines(value[1:-1]) \
- .encode('ascii', 'backslashreplace') \
- .decode('unicode-escape')
- except Exception as e:
- msg = str(e).split(':')[-1].strip()
- raise TemplateSyntaxError(msg, lineno, name, filename)
- # if we can express it as bytestring (ascii only)
- # we do that for support of semi broken APIs
- # as datetime.datetime.strftime. On python 3 this
- # call becomes a noop thanks to 2to3
- try:
- value = str(value)
- except UnicodeError:
- pass
- elif token == 'integer':
- value = int(value)
- elif token == 'float':
- value = float(value)
- elif token == 'operator':
- token = operators[value]
- yield Token(lineno, token, value)
-
- def tokeniter(self, source, name, filename=None, state=None):
- """This method tokenizes the text and returns the tokens in a
- generator. Use this method if you just want to tokenize a template.
- """
- source = text_type(source)
- lines = source.splitlines()
- if self.keep_trailing_newline and source:
- for newline in ('\r\n', '\r', '\n'):
- if source.endswith(newline):
- lines.append('')
- break
- source = '\n'.join(lines)
- pos = 0
- lineno = 1
- stack = ['root']
- if state is not None and state != 'root':
- assert state in ('variable', 'block'), 'invalid state'
- stack.append(state + '_begin')
- else:
- state = 'root'
- statetokens = self.rules[stack[-1]]
- source_length = len(source)
-
- balancing_stack = []
-
- while 1:
- # tokenizer loop
- for regex, tokens, new_state in statetokens:
- m = regex.match(source, pos)
- # if no match we try again with the next rule
- if m is None:
- continue
-
- # we only match blocks and variables if braces / parentheses
- # are balanced. continue parsing with the lower rule which
- # is the operator rule. do this only if the end tags look
- # like operators
- if balancing_stack and \
- tokens in ('variable_end', 'block_end',
- 'linestatement_end'):
- continue
-
- # tuples support more options
- if isinstance(tokens, tuple):
- for idx, token in enumerate(tokens):
- # failure group
- if token.__class__ is Failure:
- raise token(lineno, filename)
- # bygroup is a bit more complex, in that case we
- # yield for the current token the first named
- # group that matched
- elif token == '#bygroup':
- for key, value in iteritems(m.groupdict()):
- if value is not None:
- yield lineno, key, value
- lineno += value.count('\n')
- break
- else:
- raise RuntimeError('%r wanted to resolve '
- 'the token dynamically'
- ' but no group matched'
- % regex)
- # normal group
- else:
- data = m.group(idx + 1)
- if data or token not in ignore_if_empty:
- yield lineno, token, data
- lineno += data.count('\n')
-
- # strings as token just are yielded as it.
- else:
- data = m.group()
- # update brace/parentheses balance
- if tokens == 'operator':
- if data == '{':
- balancing_stack.append('}')
- elif data == '(':
- balancing_stack.append(')')
- elif data == '[':
- balancing_stack.append(']')
- elif data in ('}', ')', ']'):
- if not balancing_stack:
- raise TemplateSyntaxError('unexpected \'%s\'' %
- data, lineno, name,
- filename)
- expected_op = balancing_stack.pop()
- if expected_op != data:
- raise TemplateSyntaxError('unexpected \'%s\', '
- 'expected \'%s\'' %
- (data, expected_op),
- lineno, name,
- filename)
- # yield items
- if data or tokens not in ignore_if_empty:
- yield lineno, tokens, data
- lineno += data.count('\n')
-
- # fetch new position into new variable so that we can check
- # if there is a internal parsing error which would result
- # in an infinite loop
- pos2 = m.end()
-
- # handle state changes
- if new_state is not None:
- # remove the uppermost state
- if new_state == '#pop':
- stack.pop()
- # resolve the new state by group checking
- elif new_state == '#bygroup':
- for key, value in iteritems(m.groupdict()):
- if value is not None:
- stack.append(key)
- break
- else:
- raise RuntimeError('%r wanted to resolve the '
- 'new state dynamically but'
- ' no group matched' %
- regex)
- # direct state name given
- else:
- stack.append(new_state)
- statetokens = self.rules[stack[-1]]
- # we are still at the same position and no stack change.
- # this means a loop without break condition, avoid that and
- # raise error
- elif pos2 == pos:
- raise RuntimeError('%r yielded empty string without '
- 'stack change' % regex)
- # publish new function and start again
- pos = pos2
- break
- # if loop terminated without break we haven't found a single match
- # either we are at the end of the file or we have a problem
- else:
- # end of text
- if pos >= source_length:
- return
- # something went wrong
- raise TemplateSyntaxError('unexpected char %r at %d' %
- (source[pos], pos), lineno,
- name, filename)
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/loaders.py b/Darwin/lib/python2.7/site-packages/jinja2/loaders.py
deleted file mode 100644
index cc9c683..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/loaders.py
+++ /dev/null
@@ -1,471 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.loaders
- ~~~~~~~~~~~~~~
-
- Jinja loader classes.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import os
-import sys
-import weakref
-from types import ModuleType
-from os import path
-from hashlib import sha1
-from jinja2.exceptions import TemplateNotFound
-from jinja2.utils import open_if_exists, internalcode
-from jinja2._compat import string_types, iteritems
-
-
-def split_template_path(template):
- """Split a path into segments and perform a sanity check. If it detects
- '..' in the path it will raise a `TemplateNotFound` error.
- """
- pieces = []
- for piece in template.split('/'):
- if path.sep in piece \
- or (path.altsep and path.altsep in piece) or \
- piece == path.pardir:
- raise TemplateNotFound(template)
- elif piece and piece != '.':
- pieces.append(piece)
- return pieces
-
-
-class BaseLoader(object):
- """Baseclass for all loaders. Subclass this and override `get_source` to
- implement a custom loading mechanism. The environment provides a
- `get_template` method that calls the loader's `load` method to get the
- :class:`Template` object.
-
- A very basic example for a loader that looks up templates on the file
- system could look like this::
-
- from jinja2 import BaseLoader, TemplateNotFound
- from os.path import join, exists, getmtime
-
- class MyLoader(BaseLoader):
-
- def __init__(self, path):
- self.path = path
-
- def get_source(self, environment, template):
- path = join(self.path, template)
- if not exists(path):
- raise TemplateNotFound(template)
- mtime = getmtime(path)
- with file(path) as f:
- source = f.read().decode('utf-8')
- return source, path, lambda: mtime == getmtime(path)
- """
-
- #: if set to `False` it indicates that the loader cannot provide access
- #: to the source of templates.
- #:
- #: .. versionadded:: 2.4
- has_source_access = True
-
- def get_source(self, environment, template):
- """Get the template source, filename and reload helper for a template.
- It's passed the environment and template name and has to return a
- tuple in the form ``(source, filename, uptodate)`` or raise a
- `TemplateNotFound` error if it can't locate the template.
-
- The source part of the returned tuple must be the source of the
- template as unicode string or a ASCII bytestring. The filename should
- be the name of the file on the filesystem if it was loaded from there,
- otherwise `None`. The filename is used by python for the tracebacks
- if no loader extension is used.
-
- The last item in the tuple is the `uptodate` function. If auto
- reloading is enabled it's always called to check if the template
- changed. No arguments are passed so the function must store the
- old state somewhere (for example in a closure). If it returns `False`
- the template will be reloaded.
- """
- if not self.has_source_access:
- raise RuntimeError('%s cannot provide access to the source' %
- self.__class__.__name__)
- raise TemplateNotFound(template)
-
- def list_templates(self):
- """Iterates over all templates. If the loader does not support that
- it should raise a :exc:`TypeError` which is the default behavior.
- """
- raise TypeError('this loader cannot iterate over all templates')
-
- @internalcode
- def load(self, environment, name, globals=None):
- """Loads a template. This method looks up the template in the cache
- or loads one by calling :meth:`get_source`. Subclasses should not
- override this method as loaders working on collections of other
- loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
- will not call this method but `get_source` directly.
- """
- code = None
- if globals is None:
- globals = {}
-
- # first we try to get the source for this template together
- # with the filename and the uptodate function.
- source, filename, uptodate = self.get_source(environment, name)
-
- # try to load the code from the bytecode cache if there is a
- # bytecode cache configured.
- bcc = environment.bytecode_cache
- if bcc is not None:
- bucket = bcc.get_bucket(environment, name, filename, source)
- code = bucket.code
-
- # if we don't have code so far (not cached, no longer up to
- # date) etc. we compile the template
- if code is None:
- code = environment.compile(source, name, filename)
-
- # if the bytecode cache is available and the bucket doesn't
- # have a code so far, we give the bucket the new code and put
- # it back to the bytecode cache.
- if bcc is not None and bucket.code is None:
- bucket.code = code
- bcc.set_bucket(bucket)
-
- return environment.template_class.from_code(environment, code,
- globals, uptodate)
-
-
-class FileSystemLoader(BaseLoader):
- """Loads templates from the file system. This loader can find templates
- in folders on the file system and is the preferred way to load them.
-
- The loader takes the path to the templates as string, or if multiple
- locations are wanted a list of them which is then looked up in the
- given order:
-
- >>> loader = FileSystemLoader('/path/to/templates')
- >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])
-
- Per default the template encoding is ``'utf-8'`` which can be changed
- by setting the `encoding` parameter to something else.
- """
-
- def __init__(self, searchpath, encoding='utf-8'):
- if isinstance(searchpath, string_types):
- searchpath = [searchpath]
- self.searchpath = list(searchpath)
- self.encoding = encoding
-
- def get_source(self, environment, template):
- pieces = split_template_path(template)
- for searchpath in self.searchpath:
- filename = path.join(searchpath, *pieces)
- f = open_if_exists(filename)
- if f is None:
- continue
- try:
- contents = f.read().decode(self.encoding)
- finally:
- f.close()
-
- mtime = path.getmtime(filename)
- def uptodate():
- try:
- return path.getmtime(filename) == mtime
- except OSError:
- return False
- return contents, filename, uptodate
- raise TemplateNotFound(template)
-
- def list_templates(self):
- found = set()
- for searchpath in self.searchpath:
- for dirpath, dirnames, filenames in os.walk(searchpath):
- for filename in filenames:
- template = os.path.join(dirpath, filename) \
- [len(searchpath):].strip(os.path.sep) \
- .replace(os.path.sep, '/')
- if template[:2] == './':
- template = template[2:]
- if template not in found:
- found.add(template)
- return sorted(found)
-
-
-class PackageLoader(BaseLoader):
- """Load templates from python eggs or packages. It is constructed with
- the name of the python package and the path to the templates in that
- package::
-
- loader = PackageLoader('mypackage', 'views')
-
- If the package path is not given, ``'templates'`` is assumed.
-
- Per default the template encoding is ``'utf-8'`` which can be changed
- by setting the `encoding` parameter to something else. Due to the nature
- of eggs it's only possible to reload templates if the package was loaded
- from the file system and not a zip file.
- """
-
- def __init__(self, package_name, package_path='templates',
- encoding='utf-8'):
- from pkg_resources import DefaultProvider, ResourceManager, \
- get_provider
- provider = get_provider(package_name)
- self.encoding = encoding
- self.manager = ResourceManager()
- self.filesystem_bound = isinstance(provider, DefaultProvider)
- self.provider = provider
- self.package_path = package_path
-
- def get_source(self, environment, template):
- pieces = split_template_path(template)
- p = '/'.join((self.package_path,) + tuple(pieces))
- if not self.provider.has_resource(p):
- raise TemplateNotFound(template)
-
- filename = uptodate = None
- if self.filesystem_bound:
- filename = self.provider.get_resource_filename(self.manager, p)
- mtime = path.getmtime(filename)
- def uptodate():
- try:
- return path.getmtime(filename) == mtime
- except OSError:
- return False
-
- source = self.provider.get_resource_string(self.manager, p)
- return source.decode(self.encoding), filename, uptodate
-
- def list_templates(self):
- path = self.package_path
- if path[:2] == './':
- path = path[2:]
- elif path == '.':
- path = ''
- offset = len(path)
- results = []
- def _walk(path):
- for filename in self.provider.resource_listdir(path):
- fullname = path + '/' + filename
- if self.provider.resource_isdir(fullname):
- _walk(fullname)
- else:
- results.append(fullname[offset:].lstrip('/'))
- _walk(path)
- results.sort()
- return results
-
-
-class DictLoader(BaseLoader):
- """Loads a template from a python dict. It's passed a dict of unicode
- strings bound to template names. This loader is useful for unittesting:
-
- >>> loader = DictLoader({'index.html': 'source here'})
-
- Because auto reloading is rarely useful this is disabled per default.
- """
-
- def __init__(self, mapping):
- self.mapping = mapping
-
- def get_source(self, environment, template):
- if template in self.mapping:
- source = self.mapping[template]
- return source, None, lambda: source == self.mapping.get(template)
- raise TemplateNotFound(template)
-
- def list_templates(self):
- return sorted(self.mapping)
-
-
-class FunctionLoader(BaseLoader):
- """A loader that is passed a function which does the loading. The
- function becomes the name of the template passed and has to return either
- an unicode string with the template source, a tuple in the form ``(source,
- filename, uptodatefunc)`` or `None` if the template does not exist.
-
- >>> def load_template(name):
- ... if name == 'index.html':
- ... return '...'
- ...
- >>> loader = FunctionLoader(load_template)
-
- The `uptodatefunc` is a function that is called if autoreload is enabled
- and has to return `True` if the template is still up to date. For more
- details have a look at :meth:`BaseLoader.get_source` which has the same
- return value.
- """
-
- def __init__(self, load_func):
- self.load_func = load_func
-
- def get_source(self, environment, template):
- rv = self.load_func(template)
- if rv is None:
- raise TemplateNotFound(template)
- elif isinstance(rv, string_types):
- return rv, None, None
- return rv
-
-
-class PrefixLoader(BaseLoader):
- """A loader that is passed a dict of loaders where each loader is bound
- to a prefix. The prefix is delimited from the template by a slash per
- default, which can be changed by setting the `delimiter` argument to
- something else::
-
- loader = PrefixLoader({
- 'app1': PackageLoader('mypackage.app1'),
- 'app2': PackageLoader('mypackage.app2')
- })
-
- By loading ``'app1/index.html'`` the file from the app1 package is loaded,
- by loading ``'app2/index.html'`` the file from the second.
- """
-
- def __init__(self, mapping, delimiter='/'):
- self.mapping = mapping
- self.delimiter = delimiter
-
- def get_loader(self, template):
- try:
- prefix, name = template.split(self.delimiter, 1)
- loader = self.mapping[prefix]
- except (ValueError, KeyError):
- raise TemplateNotFound(template)
- return loader, name
-
- def get_source(self, environment, template):
- loader, name = self.get_loader(template)
- try:
- return loader.get_source(environment, name)
- except TemplateNotFound:
- # re-raise the exception with the correct fileame here.
- # (the one that includes the prefix)
- raise TemplateNotFound(template)
-
- @internalcode
- def load(self, environment, name, globals=None):
- loader, local_name = self.get_loader(name)
- try:
- return loader.load(environment, local_name, globals)
- except TemplateNotFound:
- # re-raise the exception with the correct fileame here.
- # (the one that includes the prefix)
- raise TemplateNotFound(name)
-
- def list_templates(self):
- result = []
- for prefix, loader in iteritems(self.mapping):
- for template in loader.list_templates():
- result.append(prefix + self.delimiter + template)
- return result
-
-
-class ChoiceLoader(BaseLoader):
- """This loader works like the `PrefixLoader` just that no prefix is
- specified. If a template could not be found by one loader the next one
- is tried.
-
- >>> loader = ChoiceLoader([
- ... FileSystemLoader('/path/to/user/templates'),
- ... FileSystemLoader('/path/to/system/templates')
- ... ])
-
- This is useful if you want to allow users to override builtin templates
- from a different location.
- """
-
- def __init__(self, loaders):
- self.loaders = loaders
-
- def get_source(self, environment, template):
- for loader in self.loaders:
- try:
- return loader.get_source(environment, template)
- except TemplateNotFound:
- pass
- raise TemplateNotFound(template)
-
- @internalcode
- def load(self, environment, name, globals=None):
- for loader in self.loaders:
- try:
- return loader.load(environment, name, globals)
- except TemplateNotFound:
- pass
- raise TemplateNotFound(name)
-
- def list_templates(self):
- found = set()
- for loader in self.loaders:
- found.update(loader.list_templates())
- return sorted(found)
-
-
-class _TemplateModule(ModuleType):
- """Like a normal module but with support for weak references"""
-
-
-class ModuleLoader(BaseLoader):
- """This loader loads templates from precompiled templates.
-
- Example usage:
-
- >>> loader = ChoiceLoader([
- ... ModuleLoader('/path/to/compiled/templates'),
- ... FileSystemLoader('/path/to/templates')
- ... ])
-
- Templates can be precompiled with :meth:`Environment.compile_templates`.
- """
-
- has_source_access = False
-
- def __init__(self, path):
- package_name = '_jinja2_module_templates_%x' % id(self)
-
- # create a fake module that looks for the templates in the
- # path given.
- mod = _TemplateModule(package_name)
- if isinstance(path, string_types):
- path = [path]
- else:
- path = list(path)
- mod.__path__ = path
-
- sys.modules[package_name] = weakref.proxy(mod,
- lambda x: sys.modules.pop(package_name, None))
-
- # the only strong reference, the sys.modules entry is weak
- # so that the garbage collector can remove it once the
- # loader that created it goes out of business.
- self.module = mod
- self.package_name = package_name
-
- @staticmethod
- def get_template_key(name):
- return 'tmpl_' + sha1(name.encode('utf-8')).hexdigest()
-
- @staticmethod
- def get_module_filename(name):
- return ModuleLoader.get_template_key(name) + '.py'
-
- @internalcode
- def load(self, environment, name, globals=None):
- key = self.get_template_key(name)
- module = '%s.%s' % (self.package_name, key)
- mod = getattr(self.module, module, None)
- if mod is None:
- try:
- mod = __import__(module, None, None, ['root'])
- except ImportError:
- raise TemplateNotFound(name)
-
- # remove the entry from sys.modules, we only want the attribute
- # on the module object we have stored on the loader.
- sys.modules.pop(module, None)
-
- return environment.template_class.from_module_dict(
- environment, mod.__dict__, globals)
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/meta.py b/Darwin/lib/python2.7/site-packages/jinja2/meta.py
deleted file mode 100644
index 3110cff..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/meta.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.meta
- ~~~~~~~~~~~
-
- This module implements various functions that exposes information about
- templates that might be interesting for various kinds of applications.
-
- :copyright: (c) 2010 by the Jinja Team, see AUTHORS for more details.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2 import nodes
-from jinja2.compiler import CodeGenerator
-from jinja2._compat import string_types
-
-
-class TrackingCodeGenerator(CodeGenerator):
- """We abuse the code generator for introspection."""
-
- def __init__(self, environment):
- CodeGenerator.__init__(self, environment, '',
- '')
- self.undeclared_identifiers = set()
-
- def write(self, x):
- """Don't write."""
-
- def pull_locals(self, frame):
- """Remember all undeclared identifiers."""
- self.undeclared_identifiers.update(frame.identifiers.undeclared)
-
-
-def find_undeclared_variables(ast):
- """Returns a set of all variables in the AST that will be looked up from
- the context at runtime. Because at compile time it's not known which
- variables will be used depending on the path the execution takes at
- runtime, all variables are returned.
-
- >>> from jinja2 import Environment, meta
- >>> env = Environment()
- >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
- >>> meta.find_undeclared_variables(ast)
- set(['bar'])
-
- .. admonition:: Implementation
-
- Internally the code generator is used for finding undeclared variables.
- This is good to know because the code generator might raise a
- :exc:`TemplateAssertionError` during compilation and as a matter of
- fact this function can currently raise that exception as well.
- """
- codegen = TrackingCodeGenerator(ast.environment)
- codegen.visit(ast)
- return codegen.undeclared_identifiers
-
-
-def find_referenced_templates(ast):
- """Finds all the referenced templates from the AST. This will return an
- iterator over all the hardcoded template extensions, inclusions and
- imports. If dynamic inheritance or inclusion is used, `None` will be
- yielded.
-
- >>> from jinja2 import Environment, meta
- >>> env = Environment()
- >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
- >>> list(meta.find_referenced_templates(ast))
- ['layout.html', None]
-
- This function is useful for dependency tracking. For example if you want
- to rebuild parts of the website after a layout template has changed.
- """
- for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,
- nodes.Include)):
- if not isinstance(node.template, nodes.Const):
- # a tuple with some non consts in there
- if isinstance(node.template, (nodes.Tuple, nodes.List)):
- for template_name in node.template.items:
- # something const, only yield the strings and ignore
- # non-string consts that really just make no sense
- if isinstance(template_name, nodes.Const):
- if isinstance(template_name.value, string_types):
- yield template_name.value
- # something dynamic in there
- else:
- yield None
- # something dynamic we don't know about here
- else:
- yield None
- continue
- # constant is a basestring, direct template name
- if isinstance(node.template.value, string_types):
- yield node.template.value
- # a tuple or list (latter *should* not happen) made of consts,
- # yield the consts that are strings. We could warn here for
- # non string values
- elif isinstance(node, nodes.Include) and \
- isinstance(node.template.value, (tuple, list)):
- for template_name in node.template.value:
- if isinstance(template_name, string_types):
- yield template_name
- # something else we don't care about, we could warn here
- else:
- yield None
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/nodes.py b/Darwin/lib/python2.7/site-packages/jinja2/nodes.py
deleted file mode 100644
index c5697e6..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/nodes.py
+++ /dev/null
@@ -1,914 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.nodes
- ~~~~~~~~~~~~
-
- This module implements additional nodes derived from the ast base node.
-
- It also provides some node tree helper functions like `in_lineno` and
- `get_nodes` used by the parser and translator in order to normalize
- python and jinja nodes.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import operator
-
-from collections import deque
-from jinja2.utils import Markup
-from jinja2._compat import next, izip, with_metaclass, text_type, \
- method_type, function_type
-
-
-#: the types we support for context functions
-_context_function_types = (function_type, method_type)
-
-
-_binop_to_func = {
- '*': operator.mul,
- '/': operator.truediv,
- '//': operator.floordiv,
- '**': operator.pow,
- '%': operator.mod,
- '+': operator.add,
- '-': operator.sub
-}
-
-_uaop_to_func = {
- 'not': operator.not_,
- '+': operator.pos,
- '-': operator.neg
-}
-
-_cmpop_to_func = {
- 'eq': operator.eq,
- 'ne': operator.ne,
- 'gt': operator.gt,
- 'gteq': operator.ge,
- 'lt': operator.lt,
- 'lteq': operator.le,
- 'in': lambda a, b: a in b,
- 'notin': lambda a, b: a not in b
-}
-
-
-class Impossible(Exception):
- """Raised if the node could not perform a requested action."""
-
-
-class NodeType(type):
- """A metaclass for nodes that handles the field and attribute
- inheritance. fields and attributes from the parent class are
- automatically forwarded to the child."""
-
- def __new__(cls, name, bases, d):
- for attr in 'fields', 'attributes':
- storage = []
- storage.extend(getattr(bases[0], attr, ()))
- storage.extend(d.get(attr, ()))
- assert len(bases) == 1, 'multiple inheritance not allowed'
- assert len(storage) == len(set(storage)), 'layout conflict'
- d[attr] = tuple(storage)
- d.setdefault('abstract', False)
- return type.__new__(cls, name, bases, d)
-
-
-class EvalContext(object):
- """Holds evaluation time information. Custom attributes can be attached
- to it in extensions.
- """
-
- def __init__(self, environment, template_name=None):
- self.environment = environment
- if callable(environment.autoescape):
- self.autoescape = environment.autoescape(template_name)
- else:
- self.autoescape = environment.autoescape
- self.volatile = False
-
- def save(self):
- return self.__dict__.copy()
-
- def revert(self, old):
- self.__dict__.clear()
- self.__dict__.update(old)
-
-
-def get_eval_context(node, ctx):
- if ctx is None:
- if node.environment is None:
- raise RuntimeError('if no eval context is passed, the '
- 'node must have an attached '
- 'environment.')
- return EvalContext(node.environment)
- return ctx
-
-
-class Node(with_metaclass(NodeType, object)):
- """Baseclass for all Jinja2 nodes. There are a number of nodes available
- of different types. There are four major types:
-
- - :class:`Stmt`: statements
- - :class:`Expr`: expressions
- - :class:`Helper`: helper nodes
- - :class:`Template`: the outermost wrapper node
-
- All nodes have fields and attributes. Fields may be other nodes, lists,
- or arbitrary values. Fields are passed to the constructor as regular
- positional arguments, attributes as keyword arguments. Each node has
- two attributes: `lineno` (the line number of the node) and `environment`.
- The `environment` attribute is set at the end of the parsing process for
- all nodes automatically.
- """
- fields = ()
- attributes = ('lineno', 'environment')
- abstract = True
-
- def __init__(self, *fields, **attributes):
- if self.abstract:
- raise TypeError('abstract nodes are not instanciable')
- if fields:
- if len(fields) != len(self.fields):
- if not self.fields:
- raise TypeError('%r takes 0 arguments' %
- self.__class__.__name__)
- raise TypeError('%r takes 0 or %d argument%s' % (
- self.__class__.__name__,
- len(self.fields),
- len(self.fields) != 1 and 's' or ''
- ))
- for name, arg in izip(self.fields, fields):
- setattr(self, name, arg)
- for attr in self.attributes:
- setattr(self, attr, attributes.pop(attr, None))
- if attributes:
- raise TypeError('unknown attribute %r' %
- next(iter(attributes)))
-
- def iter_fields(self, exclude=None, only=None):
- """This method iterates over all fields that are defined and yields
- ``(key, value)`` tuples. Per default all fields are returned, but
- it's possible to limit that to some fields by providing the `only`
- parameter or to exclude some using the `exclude` parameter. Both
- should be sets or tuples of field names.
- """
- for name in self.fields:
- if (exclude is only is None) or \
- (exclude is not None and name not in exclude) or \
- (only is not None and name in only):
- try:
- yield name, getattr(self, name)
- except AttributeError:
- pass
-
- def iter_child_nodes(self, exclude=None, only=None):
- """Iterates over all direct child nodes of the node. This iterates
- over all fields and yields the values of they are nodes. If the value
- of a field is a list all the nodes in that list are returned.
- """
- for field, item in self.iter_fields(exclude, only):
- if isinstance(item, list):
- for n in item:
- if isinstance(n, Node):
- yield n
- elif isinstance(item, Node):
- yield item
-
- def find(self, node_type):
- """Find the first node of a given type. If no such node exists the
- return value is `None`.
- """
- for result in self.find_all(node_type):
- return result
-
- def find_all(self, node_type):
- """Find all the nodes of a given type. If the type is a tuple,
- the check is performed for any of the tuple items.
- """
- for child in self.iter_child_nodes():
- if isinstance(child, node_type):
- yield child
- for result in child.find_all(node_type):
- yield result
-
- def set_ctx(self, ctx):
- """Reset the context of a node and all child nodes. Per default the
- parser will all generate nodes that have a 'load' context as it's the
- most common one. This method is used in the parser to set assignment
- targets and other nodes to a store context.
- """
- todo = deque([self])
- while todo:
- node = todo.popleft()
- if 'ctx' in node.fields:
- node.ctx = ctx
- todo.extend(node.iter_child_nodes())
- return self
-
- def set_lineno(self, lineno, override=False):
- """Set the line numbers of the node and children."""
- todo = deque([self])
- while todo:
- node = todo.popleft()
- if 'lineno' in node.attributes:
- if node.lineno is None or override:
- node.lineno = lineno
- todo.extend(node.iter_child_nodes())
- return self
-
- def set_environment(self, environment):
- """Set the environment for all nodes."""
- todo = deque([self])
- while todo:
- node = todo.popleft()
- node.environment = environment
- todo.extend(node.iter_child_nodes())
- return self
-
- def __eq__(self, other):
- return type(self) is type(other) and \
- tuple(self.iter_fields()) == tuple(other.iter_fields())
-
- def __ne__(self, other):
- return not self.__eq__(other)
-
- # Restore Python 2 hashing behavior on Python 3
- __hash__ = object.__hash__
-
- def __repr__(self):
- return '%s(%s)' % (
- self.__class__.__name__,
- ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
- arg in self.fields)
- )
-
-
-class Stmt(Node):
- """Base node for all statements."""
- abstract = True
-
-
-class Helper(Node):
- """Nodes that exist in a specific context only."""
- abstract = True
-
-
-class Template(Node):
- """Node that represents a template. This must be the outermost node that
- is passed to the compiler.
- """
- fields = ('body',)
-
-
-class Output(Stmt):
- """A node that holds multiple expressions which are then printed out.
- This is used both for the `print` statement and the regular template data.
- """
- fields = ('nodes',)
-
-
-class Extends(Stmt):
- """Represents an extends statement."""
- fields = ('template',)
-
-
-class For(Stmt):
- """The for loop. `target` is the target for the iteration (usually a
- :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
- of nodes that are used as loop-body, and `else_` a list of nodes for the
- `else` block. If no else node exists it has to be an empty list.
-
- For filtered nodes an expression can be stored as `test`, otherwise `None`.
- """
- fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
-
-
-class If(Stmt):
- """If `test` is true, `body` is rendered, else `else_`."""
- fields = ('test', 'body', 'else_')
-
-
-class Macro(Stmt):
- """A macro definition. `name` is the name of the macro, `args` a list of
- arguments and `defaults` a list of defaults if there are any. `body` is
- a list of nodes for the macro body.
- """
- fields = ('name', 'args', 'defaults', 'body')
-
-
-class CallBlock(Stmt):
- """Like a macro without a name but a call instead. `call` is called with
- the unnamed macro as `caller` argument this node holds.
- """
- fields = ('call', 'args', 'defaults', 'body')
-
-
-class FilterBlock(Stmt):
- """Node for filter sections."""
- fields = ('body', 'filter')
-
-
-class Block(Stmt):
- """A node that represents a block."""
- fields = ('name', 'body', 'scoped')
-
-
-class Include(Stmt):
- """A node that represents the include tag."""
- fields = ('template', 'with_context', 'ignore_missing')
-
-
-class Import(Stmt):
- """A node that represents the import tag."""
- fields = ('template', 'target', 'with_context')
-
-
-class FromImport(Stmt):
- """A node that represents the from import tag. It's important to not
- pass unsafe names to the name attribute. The compiler translates the
- attribute lookups directly into getattr calls and does *not* use the
- subscript callback of the interface. As exported variables may not
- start with double underscores (which the parser asserts) this is not a
- problem for regular Jinja code, but if this node is used in an extension
- extra care must be taken.
-
- The list of names may contain tuples if aliases are wanted.
- """
- fields = ('template', 'names', 'with_context')
-
-
-class ExprStmt(Stmt):
- """A statement that evaluates an expression and discards the result."""
- fields = ('node',)
-
-
-class Assign(Stmt):
- """Assigns an expression to a target."""
- fields = ('target', 'node')
-
-
-class Expr(Node):
- """Baseclass for all expressions."""
- abstract = True
-
- def as_const(self, eval_ctx=None):
- """Return the value of the expression as constant or raise
- :exc:`Impossible` if this was not possible.
-
- An :class:`EvalContext` can be provided, if none is given
- a default context is created which requires the nodes to have
- an attached environment.
-
- .. versionchanged:: 2.4
- the `eval_ctx` parameter was added.
- """
- raise Impossible()
-
- def can_assign(self):
- """Check if it's possible to assign something to this node."""
- return False
-
-
-class BinExpr(Expr):
- """Baseclass for all binary expressions."""
- fields = ('left', 'right')
- operator = None
- abstract = True
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- # intercepted operators cannot be folded at compile time
- if self.environment.sandboxed and \
- self.operator in self.environment.intercepted_binops:
- raise Impossible()
- f = _binop_to_func[self.operator]
- try:
- return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
- except Exception:
- raise Impossible()
-
-
-class UnaryExpr(Expr):
- """Baseclass for all unary expressions."""
- fields = ('node',)
- operator = None
- abstract = True
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- # intercepted operators cannot be folded at compile time
- if self.environment.sandboxed and \
- self.operator in self.environment.intercepted_unops:
- raise Impossible()
- f = _uaop_to_func[self.operator]
- try:
- return f(self.node.as_const(eval_ctx))
- except Exception:
- raise Impossible()
-
-
-class Name(Expr):
- """Looks up a name or stores a value in a name.
- The `ctx` of the node can be one of the following values:
-
- - `store`: store a value in the name
- - `load`: load that name
- - `param`: like `store` but if the name was defined as function parameter.
- """
- fields = ('name', 'ctx')
-
- def can_assign(self):
- return self.name not in ('true', 'false', 'none',
- 'True', 'False', 'None')
-
-
-class Literal(Expr):
- """Baseclass for literals."""
- abstract = True
-
-
-class Const(Literal):
- """All constant values. The parser will return this node for simple
- constants such as ``42`` or ``"foo"`` but it can be used to store more
- complex values such as lists too. Only constants with a safe
- representation (objects where ``eval(repr(x)) == x`` is true).
- """
- fields = ('value',)
-
- def as_const(self, eval_ctx=None):
- return self.value
-
- @classmethod
- def from_untrusted(cls, value, lineno=None, environment=None):
- """Return a const object if the value is representable as
- constant value in the generated code, otherwise it will raise
- an `Impossible` exception.
- """
- from .compiler import has_safe_repr
- if not has_safe_repr(value):
- raise Impossible()
- return cls(value, lineno=lineno, environment=environment)
-
-
-class TemplateData(Literal):
- """A constant template string."""
- fields = ('data',)
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- if eval_ctx.volatile:
- raise Impossible()
- if eval_ctx.autoescape:
- return Markup(self.data)
- return self.data
-
-
-class Tuple(Literal):
- """For loop unpacking and some other things like multiple arguments
- for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
- is used for loading the names or storing.
- """
- fields = ('items', 'ctx')
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- return tuple(x.as_const(eval_ctx) for x in self.items)
-
- def can_assign(self):
- for item in self.items:
- if not item.can_assign():
- return False
- return True
-
-
-class List(Literal):
- """Any list literal such as ``[1, 2, 3]``"""
- fields = ('items',)
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- return [x.as_const(eval_ctx) for x in self.items]
-
-
-class Dict(Literal):
- """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
- :class:`Pair` nodes.
- """
- fields = ('items',)
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- return dict(x.as_const(eval_ctx) for x in self.items)
-
-
-class Pair(Helper):
- """A key, value pair for dicts."""
- fields = ('key', 'value')
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
-
-
-class Keyword(Helper):
- """A key, value pair for keyword arguments where key is a string."""
- fields = ('key', 'value')
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- return self.key, self.value.as_const(eval_ctx)
-
-
-class CondExpr(Expr):
- """A conditional expression (inline if expression). (``{{
- foo if bar else baz }}``)
- """
- fields = ('test', 'expr1', 'expr2')
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- if self.test.as_const(eval_ctx):
- return self.expr1.as_const(eval_ctx)
-
- # if we evaluate to an undefined object, we better do that at runtime
- if self.expr2 is None:
- raise Impossible()
-
- return self.expr2.as_const(eval_ctx)
-
-
-class Filter(Expr):
- """This node applies a filter on an expression. `name` is the name of
- the filter, the rest of the fields are the same as for :class:`Call`.
-
- If the `node` of a filter is `None` the contents of the last buffer are
- filtered. Buffers are created by macros and filter blocks.
- """
- fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- if eval_ctx.volatile or self.node is None:
- raise Impossible()
- # we have to be careful here because we call filter_ below.
- # if this variable would be called filter, 2to3 would wrap the
- # call in a list beause it is assuming we are talking about the
- # builtin filter function here which no longer returns a list in
- # python 3. because of that, do not rename filter_ to filter!
- filter_ = self.environment.filters.get(self.name)
- if filter_ is None or getattr(filter_, 'contextfilter', False):
- raise Impossible()
- obj = self.node.as_const(eval_ctx)
- args = [x.as_const(eval_ctx) for x in self.args]
- if getattr(filter_, 'evalcontextfilter', False):
- args.insert(0, eval_ctx)
- elif getattr(filter_, 'environmentfilter', False):
- args.insert(0, self.environment)
- kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
- if self.dyn_args is not None:
- try:
- args.extend(self.dyn_args.as_const(eval_ctx))
- except Exception:
- raise Impossible()
- if self.dyn_kwargs is not None:
- try:
- kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
- except Exception:
- raise Impossible()
- try:
- return filter_(obj, *args, **kwargs)
- except Exception:
- raise Impossible()
-
-
-class Test(Expr):
- """Applies a test on an expression. `name` is the name of the test, the
- rest of the fields are the same as for :class:`Call`.
- """
- fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
-
-
-class Call(Expr):
- """Calls an expression. `args` is a list of arguments, `kwargs` a list
- of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
- and `dyn_kwargs` has to be either `None` or a node that is used as
- node for dynamic positional (``*args``) or keyword (``**kwargs``)
- arguments.
- """
- fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- if eval_ctx.volatile:
- raise Impossible()
- obj = self.node.as_const(eval_ctx)
-
- # don't evaluate context functions
- args = [x.as_const(eval_ctx) for x in self.args]
- if isinstance(obj, _context_function_types):
- if getattr(obj, 'contextfunction', False):
- raise Impossible()
- elif getattr(obj, 'evalcontextfunction', False):
- args.insert(0, eval_ctx)
- elif getattr(obj, 'environmentfunction', False):
- args.insert(0, self.environment)
-
- kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
- if self.dyn_args is not None:
- try:
- args.extend(self.dyn_args.as_const(eval_ctx))
- except Exception:
- raise Impossible()
- if self.dyn_kwargs is not None:
- try:
- kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
- except Exception:
- raise Impossible()
- try:
- return obj(*args, **kwargs)
- except Exception:
- raise Impossible()
-
-
-class Getitem(Expr):
- """Get an attribute or item from an expression and prefer the item."""
- fields = ('node', 'arg', 'ctx')
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- if self.ctx != 'load':
- raise Impossible()
- try:
- return self.environment.getitem(self.node.as_const(eval_ctx),
- self.arg.as_const(eval_ctx))
- except Exception:
- raise Impossible()
-
- def can_assign(self):
- return False
-
-
-class Getattr(Expr):
- """Get an attribute or item from an expression that is a ascii-only
- bytestring and prefer the attribute.
- """
- fields = ('node', 'attr', 'ctx')
-
- def as_const(self, eval_ctx=None):
- if self.ctx != 'load':
- raise Impossible()
- try:
- eval_ctx = get_eval_context(self, eval_ctx)
- return self.environment.getattr(self.node.as_const(eval_ctx),
- self.attr)
- except Exception:
- raise Impossible()
-
- def can_assign(self):
- return False
-
-
-class Slice(Expr):
- """Represents a slice object. This must only be used as argument for
- :class:`Subscript`.
- """
- fields = ('start', 'stop', 'step')
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- def const(obj):
- if obj is None:
- return None
- return obj.as_const(eval_ctx)
- return slice(const(self.start), const(self.stop), const(self.step))
-
-
-class Concat(Expr):
- """Concatenates the list of expressions provided after converting them to
- unicode.
- """
- fields = ('nodes',)
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- return ''.join(text_type(x.as_const(eval_ctx)) for x in self.nodes)
-
-
-class Compare(Expr):
- """Compares an expression with some other expressions. `ops` must be a
- list of :class:`Operand`\s.
- """
- fields = ('expr', 'ops')
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- result = value = self.expr.as_const(eval_ctx)
- try:
- for op in self.ops:
- new_value = op.expr.as_const(eval_ctx)
- result = _cmpop_to_func[op.op](value, new_value)
- value = new_value
- except Exception:
- raise Impossible()
- return result
-
-
-class Operand(Helper):
- """Holds an operator and an expression."""
- fields = ('op', 'expr')
-
-if __debug__:
- Operand.__doc__ += '\nThe following operators are available: ' + \
- ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
- set(_uaop_to_func) | set(_cmpop_to_func)))
-
-
-class Mul(BinExpr):
- """Multiplies the left with the right node."""
- operator = '*'
-
-
-class Div(BinExpr):
- """Divides the left by the right node."""
- operator = '/'
-
-
-class FloorDiv(BinExpr):
- """Divides the left by the right node and truncates conver the
- result into an integer by truncating.
- """
- operator = '//'
-
-
-class Add(BinExpr):
- """Add the left to the right node."""
- operator = '+'
-
-
-class Sub(BinExpr):
- """Substract the right from the left node."""
- operator = '-'
-
-
-class Mod(BinExpr):
- """Left modulo right."""
- operator = '%'
-
-
-class Pow(BinExpr):
- """Left to the power of right."""
- operator = '**'
-
-
-class And(BinExpr):
- """Short circuited AND."""
- operator = 'and'
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
-
-
-class Or(BinExpr):
- """Short circuited OR."""
- operator = 'or'
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
-
-
-class Not(UnaryExpr):
- """Negate the expression."""
- operator = 'not'
-
-
-class Neg(UnaryExpr):
- """Make the expression negative."""
- operator = '-'
-
-
-class Pos(UnaryExpr):
- """Make the expression positive (noop for most expressions)"""
- operator = '+'
-
-
-# Helpers for extensions
-
-
-class EnvironmentAttribute(Expr):
- """Loads an attribute from the environment object. This is useful for
- extensions that want to call a callback stored on the environment.
- """
- fields = ('name',)
-
-
-class ExtensionAttribute(Expr):
- """Returns the attribute of an extension bound to the environment.
- The identifier is the identifier of the :class:`Extension`.
-
- This node is usually constructed by calling the
- :meth:`~jinja2.ext.Extension.attr` method on an extension.
- """
- fields = ('identifier', 'name')
-
-
-class ImportedName(Expr):
- """If created with an import name the import name is returned on node
- access. For example ``ImportedName('cgi.escape')`` returns the `escape`
- function from the cgi module on evaluation. Imports are optimized by the
- compiler so there is no need to assign them to local variables.
- """
- fields = ('importname',)
-
-
-class InternalName(Expr):
- """An internal name in the compiler. You cannot create these nodes
- yourself but the parser provides a
- :meth:`~jinja2.parser.Parser.free_identifier` method that creates
- a new identifier for you. This identifier is not available from the
- template and is not threated specially by the compiler.
- """
- fields = ('name',)
-
- def __init__(self):
- raise TypeError('Can\'t create internal names. Use the '
- '`free_identifier` method on a parser.')
-
-
-class MarkSafe(Expr):
- """Mark the wrapped expression as safe (wrap it as `Markup`)."""
- fields = ('expr',)
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- return Markup(self.expr.as_const(eval_ctx))
-
-
-class MarkSafeIfAutoescape(Expr):
- """Mark the wrapped expression as safe (wrap it as `Markup`) but
- only if autoescaping is active.
-
- .. versionadded:: 2.5
- """
- fields = ('expr',)
-
- def as_const(self, eval_ctx=None):
- eval_ctx = get_eval_context(self, eval_ctx)
- if eval_ctx.volatile:
- raise Impossible()
- expr = self.expr.as_const(eval_ctx)
- if eval_ctx.autoescape:
- return Markup(expr)
- return expr
-
-
-class ContextReference(Expr):
- """Returns the current template context. It can be used like a
- :class:`Name` node, with a ``'load'`` ctx and will return the
- current :class:`~jinja2.runtime.Context` object.
-
- Here an example that assigns the current template name to a
- variable named `foo`::
-
- Assign(Name('foo', ctx='store'),
- Getattr(ContextReference(), 'name'))
- """
-
-
-class Continue(Stmt):
- """Continue a loop."""
-
-
-class Break(Stmt):
- """Break a loop."""
-
-
-class Scope(Stmt):
- """An artificial scope."""
- fields = ('body',)
-
-
-class EvalContextModifier(Stmt):
- """Modifies the eval context. For each option that should be modified,
- a :class:`Keyword` has to be added to the :attr:`options` list.
-
- Example to change the `autoescape` setting::
-
- EvalContextModifier(options=[Keyword('autoescape', Const(True))])
- """
- fields = ('options',)
-
-
-class ScopedEvalContextModifier(EvalContextModifier):
- """Modifies the eval context and reverts it later. Works exactly like
- :class:`EvalContextModifier` but will only modify the
- :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
- """
- fields = ('body',)
-
-
-# make sure nobody creates custom nodes
-def _failing_new(*args, **kwargs):
- raise TypeError('can\'t create custom node types')
-NodeType.__new__ = staticmethod(_failing_new); del _failing_new
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/optimizer.py b/Darwin/lib/python2.7/site-packages/jinja2/optimizer.py
deleted file mode 100644
index 00eab11..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/optimizer.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.optimizer
- ~~~~~~~~~~~~~~~~
-
- The jinja optimizer is currently trying to constant fold a few expressions
- and modify the AST in place so that it should be easier to evaluate it.
-
- Because the AST does not contain all the scoping information and the
- compiler has to find that out, we cannot do all the optimizations we
- want. For example loop unrolling doesn't work because unrolled loops would
- have a different scoping.
-
- The solution would be a second syntax tree that has the scoping rules stored.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD.
-"""
-from jinja2 import nodes
-from jinja2.visitor import NodeTransformer
-
-
-def optimize(node, environment):
- """The context hint can be used to perform an static optimization
- based on the context given."""
- optimizer = Optimizer(environment)
- return optimizer.visit(node)
-
-
-class Optimizer(NodeTransformer):
-
- def __init__(self, environment):
- self.environment = environment
-
- def visit_If(self, node):
- """Eliminate dead code."""
- # do not optimize ifs that have a block inside so that it doesn't
- # break super().
- if node.find(nodes.Block) is not None:
- return self.generic_visit(node)
- try:
- val = self.visit(node.test).as_const()
- except nodes.Impossible:
- return self.generic_visit(node)
- if val:
- body = node.body
- else:
- body = node.else_
- result = []
- for node in body:
- result.extend(self.visit_list(node))
- return result
-
- def fold(self, node):
- """Do constant folding."""
- node = self.generic_visit(node)
- try:
- return nodes.Const.from_untrusted(node.as_const(),
- lineno=node.lineno,
- environment=self.environment)
- except nodes.Impossible:
- return node
-
- visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \
- visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \
- visit_Not = visit_Compare = visit_Getitem = visit_Getattr = visit_Call = \
- visit_Filter = visit_Test = visit_CondExpr = fold
- del fold
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/parser.py b/Darwin/lib/python2.7/site-packages/jinja2/parser.py
deleted file mode 100644
index f60cd01..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/parser.py
+++ /dev/null
@@ -1,895 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.parser
- ~~~~~~~~~~~~~
-
- Implements the template parser.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2 import nodes
-from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError
-from jinja2.lexer import describe_token, describe_token_expr
-from jinja2._compat import next, imap
-
-
-#: statements that callinto
-_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',
- 'macro', 'include', 'from', 'import',
- 'set'])
-_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])
-
-
-class Parser(object):
- """This is the central parsing class Jinja2 uses. It's passed to
- extensions and can be used to parse expressions or statements.
- """
-
- def __init__(self, environment, source, name=None, filename=None,
- state=None):
- self.environment = environment
- self.stream = environment._tokenize(source, name, filename, state)
- self.name = name
- self.filename = filename
- self.closed = False
- self.extensions = {}
- for extension in environment.iter_extensions():
- for tag in extension.tags:
- self.extensions[tag] = extension.parse
- self._last_identifier = 0
- self._tag_stack = []
- self._end_token_stack = []
-
- def fail(self, msg, lineno=None, exc=TemplateSyntaxError):
- """Convenience method that raises `exc` with the message, passed
- line number or last line number as well as the current name and
- filename.
- """
- if lineno is None:
- lineno = self.stream.current.lineno
- raise exc(msg, lineno, self.name, self.filename)
-
- def _fail_ut_eof(self, name, end_token_stack, lineno):
- expected = []
- for exprs in end_token_stack:
- expected.extend(imap(describe_token_expr, exprs))
- if end_token_stack:
- currently_looking = ' or '.join(
- "'%s'" % describe_token_expr(expr)
- for expr in end_token_stack[-1])
- else:
- currently_looking = None
-
- if name is None:
- message = ['Unexpected end of template.']
- else:
- message = ['Encountered unknown tag \'%s\'.' % name]
-
- if currently_looking:
- if name is not None and name in expected:
- message.append('You probably made a nesting mistake. Jinja '
- 'is expecting this tag, but currently looking '
- 'for %s.' % currently_looking)
- else:
- message.append('Jinja was looking for the following tags: '
- '%s.' % currently_looking)
-
- if self._tag_stack:
- message.append('The innermost block that needs to be '
- 'closed is \'%s\'.' % self._tag_stack[-1])
-
- self.fail(' '.join(message), lineno)
-
- def fail_unknown_tag(self, name, lineno=None):
- """Called if the parser encounters an unknown tag. Tries to fail
- with a human readable error message that could help to identify
- the problem.
- """
- return self._fail_ut_eof(name, self._end_token_stack, lineno)
-
- def fail_eof(self, end_tokens=None, lineno=None):
- """Like fail_unknown_tag but for end of template situations."""
- stack = list(self._end_token_stack)
- if end_tokens is not None:
- stack.append(end_tokens)
- return self._fail_ut_eof(None, stack, lineno)
-
- def is_tuple_end(self, extra_end_rules=None):
- """Are we at the end of a tuple?"""
- if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):
- return True
- elif extra_end_rules is not None:
- return self.stream.current.test_any(extra_end_rules)
- return False
-
- def free_identifier(self, lineno=None):
- """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""
- self._last_identifier += 1
- rv = object.__new__(nodes.InternalName)
- nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)
- return rv
-
- def parse_statement(self):
- """Parse a single statement."""
- token = self.stream.current
- if token.type != 'name':
- self.fail('tag name expected', token.lineno)
- self._tag_stack.append(token.value)
- pop_tag = True
- try:
- if token.value in _statement_keywords:
- return getattr(self, 'parse_' + self.stream.current.value)()
- if token.value == 'call':
- return self.parse_call_block()
- if token.value == 'filter':
- return self.parse_filter_block()
- ext = self.extensions.get(token.value)
- if ext is not None:
- return ext(self)
-
- # did not work out, remove the token we pushed by accident
- # from the stack so that the unknown tag fail function can
- # produce a proper error message.
- self._tag_stack.pop()
- pop_tag = False
- self.fail_unknown_tag(token.value, token.lineno)
- finally:
- if pop_tag:
- self._tag_stack.pop()
-
- def parse_statements(self, end_tokens, drop_needle=False):
- """Parse multiple statements into a list until one of the end tokens
- is reached. This is used to parse the body of statements as it also
- parses template data if appropriate. The parser checks first if the
- current token is a colon and skips it if there is one. Then it checks
- for the block end and parses until if one of the `end_tokens` is
- reached. Per default the active token in the stream at the end of
- the call is the matched end token. If this is not wanted `drop_needle`
- can be set to `True` and the end token is removed.
- """
- # the first token may be a colon for python compatibility
- self.stream.skip_if('colon')
-
- # in the future it would be possible to add whole code sections
- # by adding some sort of end of statement token and parsing those here.
- self.stream.expect('block_end')
- result = self.subparse(end_tokens)
-
- # we reached the end of the template too early, the subparser
- # does not check for this, so we do that now
- if self.stream.current.type == 'eof':
- self.fail_eof(end_tokens)
-
- if drop_needle:
- next(self.stream)
- return result
-
- def parse_set(self):
- """Parse an assign statement."""
- lineno = next(self.stream).lineno
- target = self.parse_assign_target()
- self.stream.expect('assign')
- expr = self.parse_tuple()
- return nodes.Assign(target, expr, lineno=lineno)
-
- def parse_for(self):
- """Parse a for loop."""
- lineno = self.stream.expect('name:for').lineno
- target = self.parse_assign_target(extra_end_rules=('name:in',))
- self.stream.expect('name:in')
- iter = self.parse_tuple(with_condexpr=False,
- extra_end_rules=('name:recursive',))
- test = None
- if self.stream.skip_if('name:if'):
- test = self.parse_expression()
- recursive = self.stream.skip_if('name:recursive')
- body = self.parse_statements(('name:endfor', 'name:else'))
- if next(self.stream).value == 'endfor':
- else_ = []
- else:
- else_ = self.parse_statements(('name:endfor',), drop_needle=True)
- return nodes.For(target, iter, body, else_, test,
- recursive, lineno=lineno)
-
- def parse_if(self):
- """Parse an if construct."""
- node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)
- while 1:
- node.test = self.parse_tuple(with_condexpr=False)
- node.body = self.parse_statements(('name:elif', 'name:else',
- 'name:endif'))
- token = next(self.stream)
- if token.test('name:elif'):
- new_node = nodes.If(lineno=self.stream.current.lineno)
- node.else_ = [new_node]
- node = new_node
- continue
- elif token.test('name:else'):
- node.else_ = self.parse_statements(('name:endif',),
- drop_needle=True)
- else:
- node.else_ = []
- break
- return result
-
- def parse_block(self):
- node = nodes.Block(lineno=next(self.stream).lineno)
- node.name = self.stream.expect('name').value
- node.scoped = self.stream.skip_if('name:scoped')
-
- # common problem people encounter when switching from django
- # to jinja. we do not support hyphens in block names, so let's
- # raise a nicer error message in that case.
- if self.stream.current.type == 'sub':
- self.fail('Block names in Jinja have to be valid Python '
- 'identifiers and may not contain hyphens, use an '
- 'underscore instead.')
-
- node.body = self.parse_statements(('name:endblock',), drop_needle=True)
- self.stream.skip_if('name:' + node.name)
- return node
-
- def parse_extends(self):
- node = nodes.Extends(lineno=next(self.stream).lineno)
- node.template = self.parse_expression()
- return node
-
- def parse_import_context(self, node, default):
- if self.stream.current.test_any('name:with', 'name:without') and \
- self.stream.look().test('name:context'):
- node.with_context = next(self.stream).value == 'with'
- self.stream.skip()
- else:
- node.with_context = default
- return node
-
- def parse_include(self):
- node = nodes.Include(lineno=next(self.stream).lineno)
- node.template = self.parse_expression()
- if self.stream.current.test('name:ignore') and \
- self.stream.look().test('name:missing'):
- node.ignore_missing = True
- self.stream.skip(2)
- else:
- node.ignore_missing = False
- return self.parse_import_context(node, True)
-
- def parse_import(self):
- node = nodes.Import(lineno=next(self.stream).lineno)
- node.template = self.parse_expression()
- self.stream.expect('name:as')
- node.target = self.parse_assign_target(name_only=True).name
- return self.parse_import_context(node, False)
-
- def parse_from(self):
- node = nodes.FromImport(lineno=next(self.stream).lineno)
- node.template = self.parse_expression()
- self.stream.expect('name:import')
- node.names = []
-
- def parse_context():
- if self.stream.current.value in ('with', 'without') and \
- self.stream.look().test('name:context'):
- node.with_context = next(self.stream).value == 'with'
- self.stream.skip()
- return True
- return False
-
- while 1:
- if node.names:
- self.stream.expect('comma')
- if self.stream.current.type == 'name':
- if parse_context():
- break
- target = self.parse_assign_target(name_only=True)
- if target.name.startswith('_'):
- self.fail('names starting with an underline can not '
- 'be imported', target.lineno,
- exc=TemplateAssertionError)
- if self.stream.skip_if('name:as'):
- alias = self.parse_assign_target(name_only=True)
- node.names.append((target.name, alias.name))
- else:
- node.names.append(target.name)
- if parse_context() or self.stream.current.type != 'comma':
- break
- else:
- break
- if not hasattr(node, 'with_context'):
- node.with_context = False
- self.stream.skip_if('comma')
- return node
-
- def parse_signature(self, node):
- node.args = args = []
- node.defaults = defaults = []
- self.stream.expect('lparen')
- while self.stream.current.type != 'rparen':
- if args:
- self.stream.expect('comma')
- arg = self.parse_assign_target(name_only=True)
- arg.set_ctx('param')
- if self.stream.skip_if('assign'):
- defaults.append(self.parse_expression())
- args.append(arg)
- self.stream.expect('rparen')
-
- def parse_call_block(self):
- node = nodes.CallBlock(lineno=next(self.stream).lineno)
- if self.stream.current.type == 'lparen':
- self.parse_signature(node)
- else:
- node.args = []
- node.defaults = []
-
- node.call = self.parse_expression()
- if not isinstance(node.call, nodes.Call):
- self.fail('expected call', node.lineno)
- node.body = self.parse_statements(('name:endcall',), drop_needle=True)
- return node
-
- def parse_filter_block(self):
- node = nodes.FilterBlock(lineno=next(self.stream).lineno)
- node.filter = self.parse_filter(None, start_inline=True)
- node.body = self.parse_statements(('name:endfilter',),
- drop_needle=True)
- return node
-
- def parse_macro(self):
- node = nodes.Macro(lineno=next(self.stream).lineno)
- node.name = self.parse_assign_target(name_only=True).name
- self.parse_signature(node)
- node.body = self.parse_statements(('name:endmacro',),
- drop_needle=True)
- return node
-
- def parse_print(self):
- node = nodes.Output(lineno=next(self.stream).lineno)
- node.nodes = []
- while self.stream.current.type != 'block_end':
- if node.nodes:
- self.stream.expect('comma')
- node.nodes.append(self.parse_expression())
- return node
-
- def parse_assign_target(self, with_tuple=True, name_only=False,
- extra_end_rules=None):
- """Parse an assignment target. As Jinja2 allows assignments to
- tuples, this function can parse all allowed assignment targets. Per
- default assignments to tuples are parsed, that can be disable however
- by setting `with_tuple` to `False`. If only assignments to names are
- wanted `name_only` can be set to `True`. The `extra_end_rules`
- parameter is forwarded to the tuple parsing function.
- """
- if name_only:
- token = self.stream.expect('name')
- target = nodes.Name(token.value, 'store', lineno=token.lineno)
- else:
- if with_tuple:
- target = self.parse_tuple(simplified=True,
- extra_end_rules=extra_end_rules)
- else:
- target = self.parse_primary()
- target.set_ctx('store')
- if not target.can_assign():
- self.fail('can\'t assign to %r' % target.__class__.
- __name__.lower(), target.lineno)
- return target
-
- def parse_expression(self, with_condexpr=True):
- """Parse an expression. Per default all expressions are parsed, if
- the optional `with_condexpr` parameter is set to `False` conditional
- expressions are not parsed.
- """
- if with_condexpr:
- return self.parse_condexpr()
- return self.parse_or()
-
- def parse_condexpr(self):
- lineno = self.stream.current.lineno
- expr1 = self.parse_or()
- while self.stream.skip_if('name:if'):
- expr2 = self.parse_or()
- if self.stream.skip_if('name:else'):
- expr3 = self.parse_condexpr()
- else:
- expr3 = None
- expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)
- lineno = self.stream.current.lineno
- return expr1
-
- def parse_or(self):
- lineno = self.stream.current.lineno
- left = self.parse_and()
- while self.stream.skip_if('name:or'):
- right = self.parse_and()
- left = nodes.Or(left, right, lineno=lineno)
- lineno = self.stream.current.lineno
- return left
-
- def parse_and(self):
- lineno = self.stream.current.lineno
- left = self.parse_not()
- while self.stream.skip_if('name:and'):
- right = self.parse_not()
- left = nodes.And(left, right, lineno=lineno)
- lineno = self.stream.current.lineno
- return left
-
- def parse_not(self):
- if self.stream.current.test('name:not'):
- lineno = next(self.stream).lineno
- return nodes.Not(self.parse_not(), lineno=lineno)
- return self.parse_compare()
-
- def parse_compare(self):
- lineno = self.stream.current.lineno
- expr = self.parse_add()
- ops = []
- while 1:
- token_type = self.stream.current.type
- if token_type in _compare_operators:
- next(self.stream)
- ops.append(nodes.Operand(token_type, self.parse_add()))
- elif self.stream.skip_if('name:in'):
- ops.append(nodes.Operand('in', self.parse_add()))
- elif self.stream.current.test('name:not') and \
- self.stream.look().test('name:in'):
- self.stream.skip(2)
- ops.append(nodes.Operand('notin', self.parse_add()))
- else:
- break
- lineno = self.stream.current.lineno
- if not ops:
- return expr
- return nodes.Compare(expr, ops, lineno=lineno)
-
- def parse_add(self):
- lineno = self.stream.current.lineno
- left = self.parse_sub()
- while self.stream.current.type == 'add':
- next(self.stream)
- right = self.parse_sub()
- left = nodes.Add(left, right, lineno=lineno)
- lineno = self.stream.current.lineno
- return left
-
- def parse_sub(self):
- lineno = self.stream.current.lineno
- left = self.parse_concat()
- while self.stream.current.type == 'sub':
- next(self.stream)
- right = self.parse_concat()
- left = nodes.Sub(left, right, lineno=lineno)
- lineno = self.stream.current.lineno
- return left
-
- def parse_concat(self):
- lineno = self.stream.current.lineno
- args = [self.parse_mul()]
- while self.stream.current.type == 'tilde':
- next(self.stream)
- args.append(self.parse_mul())
- if len(args) == 1:
- return args[0]
- return nodes.Concat(args, lineno=lineno)
-
- def parse_mul(self):
- lineno = self.stream.current.lineno
- left = self.parse_div()
- while self.stream.current.type == 'mul':
- next(self.stream)
- right = self.parse_div()
- left = nodes.Mul(left, right, lineno=lineno)
- lineno = self.stream.current.lineno
- return left
-
- def parse_div(self):
- lineno = self.stream.current.lineno
- left = self.parse_floordiv()
- while self.stream.current.type == 'div':
- next(self.stream)
- right = self.parse_floordiv()
- left = nodes.Div(left, right, lineno=lineno)
- lineno = self.stream.current.lineno
- return left
-
- def parse_floordiv(self):
- lineno = self.stream.current.lineno
- left = self.parse_mod()
- while self.stream.current.type == 'floordiv':
- next(self.stream)
- right = self.parse_mod()
- left = nodes.FloorDiv(left, right, lineno=lineno)
- lineno = self.stream.current.lineno
- return left
-
- def parse_mod(self):
- lineno = self.stream.current.lineno
- left = self.parse_pow()
- while self.stream.current.type == 'mod':
- next(self.stream)
- right = self.parse_pow()
- left = nodes.Mod(left, right, lineno=lineno)
- lineno = self.stream.current.lineno
- return left
-
- def parse_pow(self):
- lineno = self.stream.current.lineno
- left = self.parse_unary()
- while self.stream.current.type == 'pow':
- next(self.stream)
- right = self.parse_unary()
- left = nodes.Pow(left, right, lineno=lineno)
- lineno = self.stream.current.lineno
- return left
-
- def parse_unary(self, with_filter=True):
- token_type = self.stream.current.type
- lineno = self.stream.current.lineno
- if token_type == 'sub':
- next(self.stream)
- node = nodes.Neg(self.parse_unary(False), lineno=lineno)
- elif token_type == 'add':
- next(self.stream)
- node = nodes.Pos(self.parse_unary(False), lineno=lineno)
- else:
- node = self.parse_primary()
- node = self.parse_postfix(node)
- if with_filter:
- node = self.parse_filter_expr(node)
- return node
-
- def parse_primary(self):
- token = self.stream.current
- if token.type == 'name':
- if token.value in ('true', 'false', 'True', 'False'):
- node = nodes.Const(token.value in ('true', 'True'),
- lineno=token.lineno)
- elif token.value in ('none', 'None'):
- node = nodes.Const(None, lineno=token.lineno)
- else:
- node = nodes.Name(token.value, 'load', lineno=token.lineno)
- next(self.stream)
- elif token.type == 'string':
- next(self.stream)
- buf = [token.value]
- lineno = token.lineno
- while self.stream.current.type == 'string':
- buf.append(self.stream.current.value)
- next(self.stream)
- node = nodes.Const(''.join(buf), lineno=lineno)
- elif token.type in ('integer', 'float'):
- next(self.stream)
- node = nodes.Const(token.value, lineno=token.lineno)
- elif token.type == 'lparen':
- next(self.stream)
- node = self.parse_tuple(explicit_parentheses=True)
- self.stream.expect('rparen')
- elif token.type == 'lbracket':
- node = self.parse_list()
- elif token.type == 'lbrace':
- node = self.parse_dict()
- else:
- self.fail("unexpected '%s'" % describe_token(token), token.lineno)
- return node
-
- def parse_tuple(self, simplified=False, with_condexpr=True,
- extra_end_rules=None, explicit_parentheses=False):
- """Works like `parse_expression` but if multiple expressions are
- delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.
- This method could also return a regular expression instead of a tuple
- if no commas where found.
-
- The default parsing mode is a full tuple. If `simplified` is `True`
- only names and literals are parsed. The `no_condexpr` parameter is
- forwarded to :meth:`parse_expression`.
-
- Because tuples do not require delimiters and may end in a bogus comma
- an extra hint is needed that marks the end of a tuple. For example
- for loops support tuples between `for` and `in`. In that case the
- `extra_end_rules` is set to ``['name:in']``.
-
- `explicit_parentheses` is true if the parsing was triggered by an
- expression in parentheses. This is used to figure out if an empty
- tuple is a valid expression or not.
- """
- lineno = self.stream.current.lineno
- if simplified:
- parse = self.parse_primary
- elif with_condexpr:
- parse = self.parse_expression
- else:
- parse = lambda: self.parse_expression(with_condexpr=False)
- args = []
- is_tuple = False
- while 1:
- if args:
- self.stream.expect('comma')
- if self.is_tuple_end(extra_end_rules):
- break
- args.append(parse())
- if self.stream.current.type == 'comma':
- is_tuple = True
- else:
- break
- lineno = self.stream.current.lineno
-
- if not is_tuple:
- if args:
- return args[0]
-
- # if we don't have explicit parentheses, an empty tuple is
- # not a valid expression. This would mean nothing (literally
- # nothing) in the spot of an expression would be an empty
- # tuple.
- if not explicit_parentheses:
- self.fail('Expected an expression, got \'%s\'' %
- describe_token(self.stream.current))
-
- return nodes.Tuple(args, 'load', lineno=lineno)
-
- def parse_list(self):
- token = self.stream.expect('lbracket')
- items = []
- while self.stream.current.type != 'rbracket':
- if items:
- self.stream.expect('comma')
- if self.stream.current.type == 'rbracket':
- break
- items.append(self.parse_expression())
- self.stream.expect('rbracket')
- return nodes.List(items, lineno=token.lineno)
-
- def parse_dict(self):
- token = self.stream.expect('lbrace')
- items = []
- while self.stream.current.type != 'rbrace':
- if items:
- self.stream.expect('comma')
- if self.stream.current.type == 'rbrace':
- break
- key = self.parse_expression()
- self.stream.expect('colon')
- value = self.parse_expression()
- items.append(nodes.Pair(key, value, lineno=key.lineno))
- self.stream.expect('rbrace')
- return nodes.Dict(items, lineno=token.lineno)
-
- def parse_postfix(self, node):
- while 1:
- token_type = self.stream.current.type
- if token_type == 'dot' or token_type == 'lbracket':
- node = self.parse_subscript(node)
- # calls are valid both after postfix expressions (getattr
- # and getitem) as well as filters and tests
- elif token_type == 'lparen':
- node = self.parse_call(node)
- else:
- break
- return node
-
- def parse_filter_expr(self, node):
- while 1:
- token_type = self.stream.current.type
- if token_type == 'pipe':
- node = self.parse_filter(node)
- elif token_type == 'name' and self.stream.current.value == 'is':
- node = self.parse_test(node)
- # calls are valid both after postfix expressions (getattr
- # and getitem) as well as filters and tests
- elif token_type == 'lparen':
- node = self.parse_call(node)
- else:
- break
- return node
-
- def parse_subscript(self, node):
- token = next(self.stream)
- if token.type == 'dot':
- attr_token = self.stream.current
- next(self.stream)
- if attr_token.type == 'name':
- return nodes.Getattr(node, attr_token.value, 'load',
- lineno=token.lineno)
- elif attr_token.type != 'integer':
- self.fail('expected name or number', attr_token.lineno)
- arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)
- return nodes.Getitem(node, arg, 'load', lineno=token.lineno)
- if token.type == 'lbracket':
- args = []
- while self.stream.current.type != 'rbracket':
- if args:
- self.stream.expect('comma')
- args.append(self.parse_subscribed())
- self.stream.expect('rbracket')
- if len(args) == 1:
- arg = args[0]
- else:
- arg = nodes.Tuple(args, 'load', lineno=token.lineno)
- return nodes.Getitem(node, arg, 'load', lineno=token.lineno)
- self.fail('expected subscript expression', self.lineno)
-
- def parse_subscribed(self):
- lineno = self.stream.current.lineno
-
- if self.stream.current.type == 'colon':
- next(self.stream)
- args = [None]
- else:
- node = self.parse_expression()
- if self.stream.current.type != 'colon':
- return node
- next(self.stream)
- args = [node]
-
- if self.stream.current.type == 'colon':
- args.append(None)
- elif self.stream.current.type not in ('rbracket', 'comma'):
- args.append(self.parse_expression())
- else:
- args.append(None)
-
- if self.stream.current.type == 'colon':
- next(self.stream)
- if self.stream.current.type not in ('rbracket', 'comma'):
- args.append(self.parse_expression())
- else:
- args.append(None)
- else:
- args.append(None)
-
- return nodes.Slice(lineno=lineno, *args)
-
- def parse_call(self, node):
- token = self.stream.expect('lparen')
- args = []
- kwargs = []
- dyn_args = dyn_kwargs = None
- require_comma = False
-
- def ensure(expr):
- if not expr:
- self.fail('invalid syntax for function call expression',
- token.lineno)
-
- while self.stream.current.type != 'rparen':
- if require_comma:
- self.stream.expect('comma')
- # support for trailing comma
- if self.stream.current.type == 'rparen':
- break
- if self.stream.current.type == 'mul':
- ensure(dyn_args is None and dyn_kwargs is None)
- next(self.stream)
- dyn_args = self.parse_expression()
- elif self.stream.current.type == 'pow':
- ensure(dyn_kwargs is None)
- next(self.stream)
- dyn_kwargs = self.parse_expression()
- else:
- ensure(dyn_args is None and dyn_kwargs is None)
- if self.stream.current.type == 'name' and \
- self.stream.look().type == 'assign':
- key = self.stream.current.value
- self.stream.skip(2)
- value = self.parse_expression()
- kwargs.append(nodes.Keyword(key, value,
- lineno=value.lineno))
- else:
- ensure(not kwargs)
- args.append(self.parse_expression())
-
- require_comma = True
- self.stream.expect('rparen')
-
- if node is None:
- return args, kwargs, dyn_args, dyn_kwargs
- return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs,
- lineno=token.lineno)
-
- def parse_filter(self, node, start_inline=False):
- while self.stream.current.type == 'pipe' or start_inline:
- if not start_inline:
- next(self.stream)
- token = self.stream.expect('name')
- name = token.value
- while self.stream.current.type == 'dot':
- next(self.stream)
- name += '.' + self.stream.expect('name').value
- if self.stream.current.type == 'lparen':
- args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)
- else:
- args = []
- kwargs = []
- dyn_args = dyn_kwargs = None
- node = nodes.Filter(node, name, args, kwargs, dyn_args,
- dyn_kwargs, lineno=token.lineno)
- start_inline = False
- return node
-
- def parse_test(self, node):
- token = next(self.stream)
- if self.stream.current.test('name:not'):
- next(self.stream)
- negated = True
- else:
- negated = False
- name = self.stream.expect('name').value
- while self.stream.current.type == 'dot':
- next(self.stream)
- name += '.' + self.stream.expect('name').value
- dyn_args = dyn_kwargs = None
- kwargs = []
- if self.stream.current.type == 'lparen':
- args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)
- elif self.stream.current.type in ('name', 'string', 'integer',
- 'float', 'lparen', 'lbracket',
- 'lbrace') and not \
- self.stream.current.test_any('name:else', 'name:or',
- 'name:and'):
- if self.stream.current.test('name:is'):
- self.fail('You cannot chain multiple tests with is')
- args = [self.parse_expression()]
- else:
- args = []
- node = nodes.Test(node, name, args, kwargs, dyn_args,
- dyn_kwargs, lineno=token.lineno)
- if negated:
- node = nodes.Not(node, lineno=token.lineno)
- return node
-
- def subparse(self, end_tokens=None):
- body = []
- data_buffer = []
- add_data = data_buffer.append
-
- if end_tokens is not None:
- self._end_token_stack.append(end_tokens)
-
- def flush_data():
- if data_buffer:
- lineno = data_buffer[0].lineno
- body.append(nodes.Output(data_buffer[:], lineno=lineno))
- del data_buffer[:]
-
- try:
- while self.stream:
- token = self.stream.current
- if token.type == 'data':
- if token.value:
- add_data(nodes.TemplateData(token.value,
- lineno=token.lineno))
- next(self.stream)
- elif token.type == 'variable_begin':
- next(self.stream)
- add_data(self.parse_tuple(with_condexpr=True))
- self.stream.expect('variable_end')
- elif token.type == 'block_begin':
- flush_data()
- next(self.stream)
- if end_tokens is not None and \
- self.stream.current.test_any(*end_tokens):
- return body
- rv = self.parse_statement()
- if isinstance(rv, list):
- body.extend(rv)
- else:
- body.append(rv)
- self.stream.expect('block_end')
- else:
- raise AssertionError('internal parsing error')
-
- flush_data()
- finally:
- if end_tokens is not None:
- self._end_token_stack.pop()
-
- return body
-
- def parse(self):
- """Parse the whole template into a `Template` node."""
- result = nodes.Template(self.subparse(), lineno=1)
- result.set_environment(self.environment)
- return result
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/runtime.py b/Darwin/lib/python2.7/site-packages/jinja2/runtime.py
deleted file mode 100644
index 7791c64..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/runtime.py
+++ /dev/null
@@ -1,581 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.runtime
- ~~~~~~~~~~~~~~
-
- Runtime helpers.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD.
-"""
-from itertools import chain
-from jinja2.nodes import EvalContext, _context_function_types
-from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \
- internalcode, object_type_repr
-from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \
- TemplateNotFound
-from jinja2._compat import next, imap, text_type, iteritems, \
- implements_iterator, implements_to_string, string_types, PY2
-
-
-# these variables are exported to the template runtime
-__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
- 'TemplateRuntimeError', 'missing', 'concat', 'escape',
- 'markup_join', 'unicode_join', 'to_string', 'identity',
- 'TemplateNotFound']
-
-#: the name of the function that is used to convert something into
-#: a string. We can just use the text type here.
-to_string = text_type
-
-#: the identity function. Useful for certain things in the environment
-identity = lambda x: x
-
-_last_iteration = object()
-
-
-def markup_join(seq):
- """Concatenation that escapes if necessary and converts to unicode."""
- buf = []
- iterator = imap(soft_unicode, seq)
- for arg in iterator:
- buf.append(arg)
- if hasattr(arg, '__html__'):
- return Markup(u'').join(chain(buf, iterator))
- return concat(buf)
-
-
-def unicode_join(seq):
- """Simple args to unicode conversion and concatenation."""
- return concat(imap(text_type, seq))
-
-
-def new_context(environment, template_name, blocks, vars=None,
- shared=None, globals=None, locals=None):
- """Internal helper to for context creation."""
- if vars is None:
- vars = {}
- if shared:
- parent = vars
- else:
- parent = dict(globals or (), **vars)
- if locals:
- # if the parent is shared a copy should be created because
- # we don't want to modify the dict passed
- if shared:
- parent = dict(parent)
- for key, value in iteritems(locals):
- if key[:2] == 'l_' and value is not missing:
- parent[key[2:]] = value
- return Context(environment, parent, template_name, blocks)
-
-
-class TemplateReference(object):
- """The `self` in templates."""
-
- def __init__(self, context):
- self.__context = context
-
- def __getitem__(self, name):
- blocks = self.__context.blocks[name]
- return BlockReference(name, self.__context, blocks, 0)
-
- def __repr__(self):
- return '<%s %r>' % (
- self.__class__.__name__,
- self.__context.name
- )
-
-
-class Context(object):
- """The template context holds the variables of a template. It stores the
- values passed to the template and also the names the template exports.
- Creating instances is neither supported nor useful as it's created
- automatically at various stages of the template evaluation and should not
- be created by hand.
-
- The context is immutable. Modifications on :attr:`parent` **must not**
- happen and modifications on :attr:`vars` are allowed from generated
- template code only. Template filters and global functions marked as
- :func:`contextfunction`\s get the active context passed as first argument
- and are allowed to access the context read-only.
-
- The template context supports read only dict operations (`get`,
- `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
- `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
- method that doesn't fail with a `KeyError` but returns an
- :class:`Undefined` object for missing variables.
- """
- __slots__ = ('parent', 'vars', 'environment', 'eval_ctx', 'exported_vars',
- 'name', 'blocks', '__weakref__')
-
- def __init__(self, environment, parent, name, blocks):
- self.parent = parent
- self.vars = {}
- self.environment = environment
- self.eval_ctx = EvalContext(self.environment, name)
- self.exported_vars = set()
- self.name = name
-
- # create the initial mapping of blocks. Whenever template inheritance
- # takes place the runtime will update this mapping with the new blocks
- # from the template.
- self.blocks = dict((k, [v]) for k, v in iteritems(blocks))
-
- def super(self, name, current):
- """Render a parent block."""
- try:
- blocks = self.blocks[name]
- index = blocks.index(current) + 1
- blocks[index]
- except LookupError:
- return self.environment.undefined('there is no parent block '
- 'called %r.' % name,
- name='super')
- return BlockReference(name, self, blocks, index)
-
- def get(self, key, default=None):
- """Returns an item from the template context, if it doesn't exist
- `default` is returned.
- """
- try:
- return self[key]
- except KeyError:
- return default
-
- def resolve(self, key):
- """Looks up a variable like `__getitem__` or `get` but returns an
- :class:`Undefined` object with the name of the name looked up.
- """
- if key in self.vars:
- return self.vars[key]
- if key in self.parent:
- return self.parent[key]
- return self.environment.undefined(name=key)
-
- def get_exported(self):
- """Get a new dict with the exported variables."""
- return dict((k, self.vars[k]) for k in self.exported_vars)
-
- def get_all(self):
- """Return a copy of the complete context as dict including the
- exported variables.
- """
- return dict(self.parent, **self.vars)
-
- @internalcode
- def call(__self, __obj, *args, **kwargs):
- """Call the callable with the arguments and keyword arguments
- provided but inject the active context or environment as first
- argument if the callable is a :func:`contextfunction` or
- :func:`environmentfunction`.
- """
- if __debug__:
- __traceback_hide__ = True
-
- # Allow callable classes to take a context
- fn = __obj.__call__
- for fn_type in ('contextfunction',
- 'evalcontextfunction',
- 'environmentfunction'):
- if hasattr(fn, fn_type):
- __obj = fn
- break
-
- if isinstance(__obj, _context_function_types):
- if getattr(__obj, 'contextfunction', 0):
- args = (__self,) + args
- elif getattr(__obj, 'evalcontextfunction', 0):
- args = (__self.eval_ctx,) + args
- elif getattr(__obj, 'environmentfunction', 0):
- args = (__self.environment,) + args
- try:
- return __obj(*args, **kwargs)
- except StopIteration:
- return __self.environment.undefined('value was undefined because '
- 'a callable raised a '
- 'StopIteration exception')
-
- def derived(self, locals=None):
- """Internal helper function to create a derived context."""
- context = new_context(self.environment, self.name, {},
- self.parent, True, None, locals)
- context.vars.update(self.vars)
- context.eval_ctx = self.eval_ctx
- context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))
- return context
-
- def _all(meth):
- proxy = lambda self: getattr(self.get_all(), meth)()
- proxy.__doc__ = getattr(dict, meth).__doc__
- proxy.__name__ = meth
- return proxy
-
- keys = _all('keys')
- values = _all('values')
- items = _all('items')
-
- # not available on python 3
- if PY2:
- iterkeys = _all('iterkeys')
- itervalues = _all('itervalues')
- iteritems = _all('iteritems')
- del _all
-
- def __contains__(self, name):
- return name in self.vars or name in self.parent
-
- def __getitem__(self, key):
- """Lookup a variable or raise `KeyError` if the variable is
- undefined.
- """
- item = self.resolve(key)
- if isinstance(item, Undefined):
- raise KeyError(key)
- return item
-
- def __repr__(self):
- return '<%s %s of %r>' % (
- self.__class__.__name__,
- repr(self.get_all()),
- self.name
- )
-
-
-# register the context as mapping if possible
-try:
- from collections import Mapping
- Mapping.register(Context)
-except ImportError:
- pass
-
-
-class BlockReference(object):
- """One block on a template reference."""
-
- def __init__(self, name, context, stack, depth):
- self.name = name
- self._context = context
- self._stack = stack
- self._depth = depth
-
- @property
- def super(self):
- """Super the block."""
- if self._depth + 1 >= len(self._stack):
- return self._context.environment. \
- undefined('there is no parent block called %r.' %
- self.name, name='super')
- return BlockReference(self.name, self._context, self._stack,
- self._depth + 1)
-
- @internalcode
- def __call__(self):
- rv = concat(self._stack[self._depth](self._context))
- if self._context.eval_ctx.autoescape:
- rv = Markup(rv)
- return rv
-
-
-class LoopContext(object):
- """A loop context for dynamic iteration."""
-
- def __init__(self, iterable, recurse=None, depth0=0):
- self._iterator = iter(iterable)
- self._recurse = recurse
- self._after = self._safe_next()
- self.index0 = -1
- self.depth0 = depth0
-
- # try to get the length of the iterable early. This must be done
- # here because there are some broken iterators around where there
- # __len__ is the number of iterations left (i'm looking at your
- # listreverseiterator!).
- try:
- self._length = len(iterable)
- except (TypeError, AttributeError):
- self._length = None
-
- def cycle(self, *args):
- """Cycles among the arguments with the current loop index."""
- if not args:
- raise TypeError('no items for cycling given')
- return args[self.index0 % len(args)]
-
- first = property(lambda x: x.index0 == 0)
- last = property(lambda x: x._after is _last_iteration)
- index = property(lambda x: x.index0 + 1)
- revindex = property(lambda x: x.length - x.index0)
- revindex0 = property(lambda x: x.length - x.index)
- depth = property(lambda x: x.depth0 + 1)
-
- def __len__(self):
- return self.length
-
- def __iter__(self):
- return LoopContextIterator(self)
-
- def _safe_next(self):
- try:
- return next(self._iterator)
- except StopIteration:
- return _last_iteration
-
- @internalcode
- def loop(self, iterable):
- if self._recurse is None:
- raise TypeError('Tried to call non recursive loop. Maybe you '
- "forgot the 'recursive' modifier.")
- return self._recurse(iterable, self._recurse, self.depth0 + 1)
-
- # a nifty trick to enhance the error message if someone tried to call
- # the the loop without or with too many arguments.
- __call__ = loop
- del loop
-
- @property
- def length(self):
- if self._length is None:
- # if was not possible to get the length of the iterator when
- # the loop context was created (ie: iterating over a generator)
- # we have to convert the iterable into a sequence and use the
- # length of that.
- iterable = tuple(self._iterator)
- self._iterator = iter(iterable)
- self._length = len(iterable) + self.index0 + 1
- return self._length
-
- def __repr__(self):
- return '<%s %r/%r>' % (
- self.__class__.__name__,
- self.index,
- self.length
- )
-
-
-@implements_iterator
-class LoopContextIterator(object):
- """The iterator for a loop context."""
- __slots__ = ('context',)
-
- def __init__(self, context):
- self.context = context
-
- def __iter__(self):
- return self
-
- def __next__(self):
- ctx = self.context
- ctx.index0 += 1
- if ctx._after is _last_iteration:
- raise StopIteration()
- next_elem = ctx._after
- ctx._after = ctx._safe_next()
- return next_elem, ctx
-
-
-class Macro(object):
- """Wraps a macro function."""
-
- def __init__(self, environment, func, name, arguments, defaults,
- catch_kwargs, catch_varargs, caller):
- self._environment = environment
- self._func = func
- self._argument_count = len(arguments)
- self.name = name
- self.arguments = arguments
- self.defaults = defaults
- self.catch_kwargs = catch_kwargs
- self.catch_varargs = catch_varargs
- self.caller = caller
-
- @internalcode
- def __call__(self, *args, **kwargs):
- # try to consume the positional arguments
- arguments = list(args[:self._argument_count])
- off = len(arguments)
-
- # if the number of arguments consumed is not the number of
- # arguments expected we start filling in keyword arguments
- # and defaults.
- if off != self._argument_count:
- for idx, name in enumerate(self.arguments[len(arguments):]):
- try:
- value = kwargs.pop(name)
- except KeyError:
- try:
- value = self.defaults[idx - self._argument_count + off]
- except IndexError:
- value = self._environment.undefined(
- 'parameter %r was not provided' % name, name=name)
- arguments.append(value)
-
- # it's important that the order of these arguments does not change
- # if not also changed in the compiler's `function_scoping` method.
- # the order is caller, keyword arguments, positional arguments!
- if self.caller:
- caller = kwargs.pop('caller', None)
- if caller is None:
- caller = self._environment.undefined('No caller defined',
- name='caller')
- arguments.append(caller)
- if self.catch_kwargs:
- arguments.append(kwargs)
- elif kwargs:
- raise TypeError('macro %r takes no keyword argument %r' %
- (self.name, next(iter(kwargs))))
- if self.catch_varargs:
- arguments.append(args[self._argument_count:])
- elif len(args) > self._argument_count:
- raise TypeError('macro %r takes not more than %d argument(s)' %
- (self.name, len(self.arguments)))
- return self._func(*arguments)
-
- def __repr__(self):
- return '<%s %s>' % (
- self.__class__.__name__,
- self.name is None and 'anonymous' or repr(self.name)
- )
-
-
-@implements_to_string
-class Undefined(object):
- """The default undefined type. This undefined type can be printed and
- iterated over, but every other access will raise an :exc:`UndefinedError`:
-
- >>> foo = Undefined(name='foo')
- >>> str(foo)
- ''
- >>> not foo
- True
- >>> foo + 42
- Traceback (most recent call last):
- ...
- UndefinedError: 'foo' is undefined
- """
- __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
- '_undefined_exception')
-
- def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):
- self._undefined_hint = hint
- self._undefined_obj = obj
- self._undefined_name = name
- self._undefined_exception = exc
-
- @internalcode
- def _fail_with_undefined_error(self, *args, **kwargs):
- """Regular callback function for undefined objects that raises an
- `UndefinedError` on call.
- """
- if self._undefined_hint is None:
- if self._undefined_obj is missing:
- hint = '%r is undefined' % self._undefined_name
- elif not isinstance(self._undefined_name, string_types):
- hint = '%s has no element %r' % (
- object_type_repr(self._undefined_obj),
- self._undefined_name
- )
- else:
- hint = '%r has no attribute %r' % (
- object_type_repr(self._undefined_obj),
- self._undefined_name
- )
- else:
- hint = self._undefined_hint
- raise self._undefined_exception(hint)
-
- @internalcode
- def __getattr__(self, name):
- if name[:2] == '__':
- raise AttributeError(name)
- return self._fail_with_undefined_error()
-
- __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
- __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
- __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
- __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
- __float__ = __complex__ = __pow__ = __rpow__ = \
- _fail_with_undefined_error
-
- def __eq__(self, other):
- return type(self) is type(other)
-
- def __ne__(self, other):
- return not self.__eq__(other)
-
- def __hash__(self):
- return id(type(self))
-
- def __str__(self):
- return u''
-
- def __len__(self):
- return 0
-
- def __iter__(self):
- if 0:
- yield None
-
- def __nonzero__(self):
- return False
-
- def __repr__(self):
- return 'Undefined'
-
-
-@implements_to_string
-class DebugUndefined(Undefined):
- """An undefined that returns the debug info when printed.
-
- >>> foo = DebugUndefined(name='foo')
- >>> str(foo)
- '{{ foo }}'
- >>> not foo
- True
- >>> foo + 42
- Traceback (most recent call last):
- ...
- UndefinedError: 'foo' is undefined
- """
- __slots__ = ()
-
- def __str__(self):
- if self._undefined_hint is None:
- if self._undefined_obj is missing:
- return u'{{ %s }}' % self._undefined_name
- return '{{ no such element: %s[%r] }}' % (
- object_type_repr(self._undefined_obj),
- self._undefined_name
- )
- return u'{{ undefined value printed: %s }}' % self._undefined_hint
-
-
-@implements_to_string
-class StrictUndefined(Undefined):
- """An undefined that barks on print and iteration as well as boolean
- tests and all kinds of comparisons. In other words: you can do nothing
- with it except checking if it's defined using the `defined` test.
-
- >>> foo = StrictUndefined(name='foo')
- >>> str(foo)
- Traceback (most recent call last):
- ...
- UndefinedError: 'foo' is undefined
- >>> not foo
- Traceback (most recent call last):
- ...
- UndefinedError: 'foo' is undefined
- >>> foo + 42
- Traceback (most recent call last):
- ...
- UndefinedError: 'foo' is undefined
- """
- __slots__ = ()
- __iter__ = __str__ = __len__ = __nonzero__ = __eq__ = \
- __ne__ = __bool__ = __hash__ = \
- Undefined._fail_with_undefined_error
-
-
-# remove remaining slots attributes, after the metaclass did the magic they
-# are unneeded and irritating as they contain wrong data for the subclasses.
-del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/sandbox.py b/Darwin/lib/python2.7/site-packages/jinja2/sandbox.py
deleted file mode 100644
index da479c1..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/sandbox.py
+++ /dev/null
@@ -1,368 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.sandbox
- ~~~~~~~~~~~~~~
-
- Adds a sandbox layer to Jinja as it was the default behavior in the old
- Jinja 1 releases. This sandbox is slightly different from Jinja 1 as the
- default behavior is easier to use.
-
- The behavior can be changed by subclassing the environment.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD.
-"""
-import operator
-from jinja2.environment import Environment
-from jinja2.exceptions import SecurityError
-from jinja2._compat import string_types, function_type, method_type, \
- traceback_type, code_type, frame_type, generator_type, PY2
-
-
-#: maximum number of items a range may produce
-MAX_RANGE = 100000
-
-#: attributes of function objects that are considered unsafe.
-UNSAFE_FUNCTION_ATTRIBUTES = set(['func_closure', 'func_code', 'func_dict',
- 'func_defaults', 'func_globals'])
-
-#: unsafe method attributes. function attributes are unsafe for methods too
-UNSAFE_METHOD_ATTRIBUTES = set(['im_class', 'im_func', 'im_self'])
-
-#: unsafe generator attirbutes.
-UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code'])
-
-# On versions > python 2 the special attributes on functions are gone,
-# but they remain on methods and generators for whatever reason.
-if not PY2:
- UNSAFE_FUNCTION_ATTRIBUTES = set()
-
-import warnings
-
-# make sure we don't warn in python 2.6 about stuff we don't care about
-warnings.filterwarnings('ignore', 'the sets module', DeprecationWarning,
- module='jinja2.sandbox')
-
-from collections import deque
-
-_mutable_set_types = (set,)
-_mutable_mapping_types = (dict,)
-_mutable_sequence_types = (list,)
-
-
-# on python 2.x we can register the user collection types
-try:
- from UserDict import UserDict, DictMixin
- from UserList import UserList
- _mutable_mapping_types += (UserDict, DictMixin)
- _mutable_set_types += (UserList,)
-except ImportError:
- pass
-
-# if sets is still available, register the mutable set from there as well
-try:
- from sets import Set
- _mutable_set_types += (Set,)
-except ImportError:
- pass
-
-#: register Python 2.6 abstract base classes
-try:
- from collections import MutableSet, MutableMapping, MutableSequence
- _mutable_set_types += (MutableSet,)
- _mutable_mapping_types += (MutableMapping,)
- _mutable_sequence_types += (MutableSequence,)
-except ImportError:
- pass
-
-_mutable_spec = (
- (_mutable_set_types, frozenset([
- 'add', 'clear', 'difference_update', 'discard', 'pop', 'remove',
- 'symmetric_difference_update', 'update'
- ])),
- (_mutable_mapping_types, frozenset([
- 'clear', 'pop', 'popitem', 'setdefault', 'update'
- ])),
- (_mutable_sequence_types, frozenset([
- 'append', 'reverse', 'insert', 'sort', 'extend', 'remove'
- ])),
- (deque, frozenset([
- 'append', 'appendleft', 'clear', 'extend', 'extendleft', 'pop',
- 'popleft', 'remove', 'rotate'
- ]))
-)
-
-
-def safe_range(*args):
- """A range that can't generate ranges with a length of more than
- MAX_RANGE items.
- """
- rng = range(*args)
- if len(rng) > MAX_RANGE:
- raise OverflowError('range too big, maximum size for range is %d' %
- MAX_RANGE)
- return rng
-
-
-def unsafe(f):
- """Marks a function or method as unsafe.
-
- ::
-
- @unsafe
- def delete(self):
- pass
- """
- f.unsafe_callable = True
- return f
-
-
-def is_internal_attribute(obj, attr):
- """Test if the attribute given is an internal python attribute. For
- example this function returns `True` for the `func_code` attribute of
- python objects. This is useful if the environment method
- :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.
-
- >>> from jinja2.sandbox import is_internal_attribute
- >>> is_internal_attribute(lambda: None, "func_code")
- True
- >>> is_internal_attribute((lambda x:x).func_code, 'co_code')
- True
- >>> is_internal_attribute(str, "upper")
- False
- """
- if isinstance(obj, function_type):
- if attr in UNSAFE_FUNCTION_ATTRIBUTES:
- return True
- elif isinstance(obj, method_type):
- if attr in UNSAFE_FUNCTION_ATTRIBUTES or \
- attr in UNSAFE_METHOD_ATTRIBUTES:
- return True
- elif isinstance(obj, type):
- if attr == 'mro':
- return True
- elif isinstance(obj, (code_type, traceback_type, frame_type)):
- return True
- elif isinstance(obj, generator_type):
- if attr in UNSAFE_GENERATOR_ATTRIBUTES:
- return True
- return attr.startswith('__')
-
-
-def modifies_known_mutable(obj, attr):
- """This function checks if an attribute on a builtin mutable object
- (list, dict, set or deque) would modify it if called. It also supports
- the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and
- with Python 2.6 onwards the abstract base classes `MutableSet`,
- `MutableMapping`, and `MutableSequence`.
-
- >>> modifies_known_mutable({}, "clear")
- True
- >>> modifies_known_mutable({}, "keys")
- False
- >>> modifies_known_mutable([], "append")
- True
- >>> modifies_known_mutable([], "index")
- False
-
- If called with an unsupported object (such as unicode) `False` is
- returned.
-
- >>> modifies_known_mutable("foo", "upper")
- False
- """
- for typespec, unsafe in _mutable_spec:
- if isinstance(obj, typespec):
- return attr in unsafe
- return False
-
-
-class SandboxedEnvironment(Environment):
- """The sandboxed environment. It works like the regular environment but
- tells the compiler to generate sandboxed code. Additionally subclasses of
- this environment may override the methods that tell the runtime what
- attributes or functions are safe to access.
-
- If the template tries to access insecure code a :exc:`SecurityError` is
- raised. However also other exceptions may occour during the rendering so
- the caller has to ensure that all exceptions are catched.
- """
- sandboxed = True
-
- #: default callback table for the binary operators. A copy of this is
- #: available on each instance of a sandboxed environment as
- #: :attr:`binop_table`
- default_binop_table = {
- '+': operator.add,
- '-': operator.sub,
- '*': operator.mul,
- '/': operator.truediv,
- '//': operator.floordiv,
- '**': operator.pow,
- '%': operator.mod
- }
-
- #: default callback table for the unary operators. A copy of this is
- #: available on each instance of a sandboxed environment as
- #: :attr:`unop_table`
- default_unop_table = {
- '+': operator.pos,
- '-': operator.neg
- }
-
- #: a set of binary operators that should be intercepted. Each operator
- #: that is added to this set (empty by default) is delegated to the
- #: :meth:`call_binop` method that will perform the operator. The default
- #: operator callback is specified by :attr:`binop_table`.
- #:
- #: The following binary operators are interceptable:
- #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``
- #:
- #: The default operation form the operator table corresponds to the
- #: builtin function. Intercepted calls are always slower than the native
- #: operator call, so make sure only to intercept the ones you are
- #: interested in.
- #:
- #: .. versionadded:: 2.6
- intercepted_binops = frozenset()
-
- #: a set of unary operators that should be intercepted. Each operator
- #: that is added to this set (empty by default) is delegated to the
- #: :meth:`call_unop` method that will perform the operator. The default
- #: operator callback is specified by :attr:`unop_table`.
- #:
- #: The following unary operators are interceptable: ``+``, ``-``
- #:
- #: The default operation form the operator table corresponds to the
- #: builtin function. Intercepted calls are always slower than the native
- #: operator call, so make sure only to intercept the ones you are
- #: interested in.
- #:
- #: .. versionadded:: 2.6
- intercepted_unops = frozenset()
-
- def intercept_unop(self, operator):
- """Called during template compilation with the name of a unary
- operator to check if it should be intercepted at runtime. If this
- method returns `True`, :meth:`call_unop` is excuted for this unary
- operator. The default implementation of :meth:`call_unop` will use
- the :attr:`unop_table` dictionary to perform the operator with the
- same logic as the builtin one.
-
- The following unary operators are interceptable: ``+`` and ``-``
-
- Intercepted calls are always slower than the native operator call,
- so make sure only to intercept the ones you are interested in.
-
- .. versionadded:: 2.6
- """
- return False
-
-
- def __init__(self, *args, **kwargs):
- Environment.__init__(self, *args, **kwargs)
- self.globals['range'] = safe_range
- self.binop_table = self.default_binop_table.copy()
- self.unop_table = self.default_unop_table.copy()
-
- def is_safe_attribute(self, obj, attr, value):
- """The sandboxed environment will call this method to check if the
- attribute of an object is safe to access. Per default all attributes
- starting with an underscore are considered private as well as the
- special attributes of internal python objects as returned by the
- :func:`is_internal_attribute` function.
- """
- return not (attr.startswith('_') or is_internal_attribute(obj, attr))
-
- def is_safe_callable(self, obj):
- """Check if an object is safely callable. Per default a function is
- considered safe unless the `unsafe_callable` attribute exists and is
- True. Override this method to alter the behavior, but this won't
- affect the `unsafe` decorator from this module.
- """
- return not (getattr(obj, 'unsafe_callable', False) or
- getattr(obj, 'alters_data', False))
-
- def call_binop(self, context, operator, left, right):
- """For intercepted binary operator calls (:meth:`intercepted_binops`)
- this function is executed instead of the builtin operator. This can
- be used to fine tune the behavior of certain operators.
-
- .. versionadded:: 2.6
- """
- return self.binop_table[operator](left, right)
-
- def call_unop(self, context, operator, arg):
- """For intercepted unary operator calls (:meth:`intercepted_unops`)
- this function is executed instead of the builtin operator. This can
- be used to fine tune the behavior of certain operators.
-
- .. versionadded:: 2.6
- """
- return self.unop_table[operator](arg)
-
- def getitem(self, obj, argument):
- """Subscribe an object from sandboxed code."""
- try:
- return obj[argument]
- except (TypeError, LookupError):
- if isinstance(argument, string_types):
- try:
- attr = str(argument)
- except Exception:
- pass
- else:
- try:
- value = getattr(obj, attr)
- except AttributeError:
- pass
- else:
- if self.is_safe_attribute(obj, argument, value):
- return value
- return self.unsafe_undefined(obj, argument)
- return self.undefined(obj=obj, name=argument)
-
- def getattr(self, obj, attribute):
- """Subscribe an object from sandboxed code and prefer the
- attribute. The attribute passed *must* be a bytestring.
- """
- try:
- value = getattr(obj, attribute)
- except AttributeError:
- try:
- return obj[attribute]
- except (TypeError, LookupError):
- pass
- else:
- if self.is_safe_attribute(obj, attribute, value):
- return value
- return self.unsafe_undefined(obj, attribute)
- return self.undefined(obj=obj, name=attribute)
-
- def unsafe_undefined(self, obj, attribute):
- """Return an undefined object for unsafe attributes."""
- return self.undefined('access to attribute %r of %r '
- 'object is unsafe.' % (
- attribute,
- obj.__class__.__name__
- ), name=attribute, obj=obj, exc=SecurityError)
-
- def call(__self, __context, __obj, *args, **kwargs):
- """Call an object from sandboxed code."""
- # the double prefixes are to avoid double keyword argument
- # errors when proxying the call.
- if not __self.is_safe_callable(__obj):
- raise SecurityError('%r is not safely callable' % (__obj,))
- return __context.call(__obj, *args, **kwargs)
-
-
-class ImmutableSandboxedEnvironment(SandboxedEnvironment):
- """Works exactly like the regular `SandboxedEnvironment` but does not
- permit modifications on the builtin mutable objects `list`, `set`, and
- `dict` by using the :func:`modifies_known_mutable` function.
- """
-
- def is_safe_attribute(self, obj, attr, value):
- if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):
- return False
- return not modifies_known_mutable(obj, attr)
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/tests.py b/Darwin/lib/python2.7/site-packages/jinja2/tests.py
deleted file mode 100644
index 48a3e06..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/tests.py
+++ /dev/null
@@ -1,149 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.tests
- ~~~~~~~~~~~~
-
- Jinja test functions. Used with the "is" operator.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import re
-from jinja2.runtime import Undefined
-from jinja2._compat import text_type, string_types, mapping_types
-
-
-number_re = re.compile(r'^-?\d+(\.\d+)?$')
-regex_type = type(number_re)
-
-
-test_callable = callable
-
-
-def test_odd(value):
- """Return true if the variable is odd."""
- return value % 2 == 1
-
-
-def test_even(value):
- """Return true if the variable is even."""
- return value % 2 == 0
-
-
-def test_divisibleby(value, num):
- """Check if a variable is divisible by a number."""
- return value % num == 0
-
-
-def test_defined(value):
- """Return true if the variable is defined:
-
- .. sourcecode:: jinja
-
- {% if variable is defined %}
- value of variable: {{ variable }}
- {% else %}
- variable is not defined
- {% endif %}
-
- See the :func:`default` filter for a simple way to set undefined
- variables.
- """
- return not isinstance(value, Undefined)
-
-
-def test_undefined(value):
- """Like :func:`defined` but the other way round."""
- return isinstance(value, Undefined)
-
-
-def test_none(value):
- """Return true if the variable is none."""
- return value is None
-
-
-def test_lower(value):
- """Return true if the variable is lowercased."""
- return text_type(value).islower()
-
-
-def test_upper(value):
- """Return true if the variable is uppercased."""
- return text_type(value).isupper()
-
-
-def test_string(value):
- """Return true if the object is a string."""
- return isinstance(value, string_types)
-
-
-def test_mapping(value):
- """Return true if the object is a mapping (dict etc.).
-
- .. versionadded:: 2.6
- """
- return isinstance(value, mapping_types)
-
-
-def test_number(value):
- """Return true if the variable is a number."""
- return isinstance(value, (int, float, complex))
-
-
-def test_sequence(value):
- """Return true if the variable is a sequence. Sequences are variables
- that are iterable.
- """
- try:
- len(value)
- value.__getitem__
- except:
- return False
- return True
-
-
-def test_sameas(value, other):
- """Check if an object points to the same memory address than another
- object:
-
- .. sourcecode:: jinja
-
- {% if foo.attribute is sameas false %}
- the foo attribute really is the `False` singleton
- {% endif %}
- """
- return value is other
-
-
-def test_iterable(value):
- """Check if it's possible to iterate over an object."""
- try:
- iter(value)
- except TypeError:
- return False
- return True
-
-
-def test_escaped(value):
- """Check if the value is escaped."""
- return hasattr(value, '__html__')
-
-
-TESTS = {
- 'odd': test_odd,
- 'even': test_even,
- 'divisibleby': test_divisibleby,
- 'defined': test_defined,
- 'undefined': test_undefined,
- 'none': test_none,
- 'lower': test_lower,
- 'upper': test_upper,
- 'string': test_string,
- 'mapping': test_mapping,
- 'number': test_number,
- 'sequence': test_sequence,
- 'iterable': test_iterable,
- 'callable': test_callable,
- 'sameas': test_sameas,
- 'escaped': test_escaped
-}
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/__init__.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/__init__.py
deleted file mode 100644
index 635c83e..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/__init__.py
+++ /dev/null
@@ -1,156 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite
- ~~~~~~~~~~~~~~~~
-
- All the unittests of Jinja2. These tests can be executed by
- either running run-tests.py using multiple Python versions at
- the same time.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import os
-import re
-import sys
-import unittest
-from traceback import format_exception
-from jinja2 import loaders
-from jinja2._compat import PY2
-
-
-here = os.path.dirname(os.path.abspath(__file__))
-
-dict_loader = loaders.DictLoader({
- 'justdict.html': 'FOO'
-})
-package_loader = loaders.PackageLoader('jinja2.testsuite.res', 'templates')
-filesystem_loader = loaders.FileSystemLoader(here + '/res/templates')
-function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get)
-choice_loader = loaders.ChoiceLoader([dict_loader, package_loader])
-prefix_loader = loaders.PrefixLoader({
- 'a': filesystem_loader,
- 'b': dict_loader
-})
-
-
-class JinjaTestCase(unittest.TestCase):
-
- ### use only these methods for testing. If you need standard
- ### unittest method, wrap them!
-
- def setup(self):
- pass
-
- def teardown(self):
- pass
-
- def setUp(self):
- self.setup()
-
- def tearDown(self):
- self.teardown()
-
- def assert_equal(self, a, b):
- return self.assertEqual(a, b)
-
- def assert_raises(self, *args, **kwargs):
- return self.assertRaises(*args, **kwargs)
-
- def assert_traceback_matches(self, callback, expected_tb):
- try:
- callback()
- except Exception as e:
- tb = format_exception(*sys.exc_info())
- if re.search(expected_tb.strip(), ''.join(tb)) is None:
- raise self.fail('Traceback did not match:\n\n%s\nexpected:\n%s'
- % (''.join(tb), expected_tb))
- else:
- self.fail('Expected exception')
-
-
-def find_all_tests(suite):
- """Yields all the tests and their names from a given suite."""
- suites = [suite]
- while suites:
- s = suites.pop()
- try:
- suites.extend(s)
- except TypeError:
- yield s, '%s.%s.%s' % (
- s.__class__.__module__,
- s.__class__.__name__,
- s._testMethodName
- )
-
-
-class BetterLoader(unittest.TestLoader):
- """A nicer loader that solves two problems. First of all we are setting
- up tests from different sources and we're doing this programmatically
- which breaks the default loading logic so this is required anyways.
- Secondly this loader has a nicer interpolation for test names than the
- default one so you can just do ``run-tests.py ViewTestCase`` and it
- will work.
- """
-
- def getRootSuite(self):
- return suite()
-
- def loadTestsFromName(self, name, module=None):
- root = self.getRootSuite()
- if name == 'suite':
- return root
-
- all_tests = []
- for testcase, testname in find_all_tests(root):
- if testname == name or \
- testname.endswith('.' + name) or \
- ('.' + name + '.') in testname or \
- testname.startswith(name + '.'):
- all_tests.append(testcase)
-
- if not all_tests:
- raise LookupError('could not find test case for "%s"' % name)
-
- if len(all_tests) == 1:
- return all_tests[0]
- rv = unittest.TestSuite()
- for test in all_tests:
- rv.addTest(test)
- return rv
-
-
-def suite():
- from jinja2.testsuite import ext, filters, tests, core_tags, \
- loader, inheritance, imports, lexnparse, security, api, \
- regression, debug, utils, bytecode_cache, doctests
- suite = unittest.TestSuite()
- suite.addTest(ext.suite())
- suite.addTest(filters.suite())
- suite.addTest(tests.suite())
- suite.addTest(core_tags.suite())
- suite.addTest(loader.suite())
- suite.addTest(inheritance.suite())
- suite.addTest(imports.suite())
- suite.addTest(lexnparse.suite())
- suite.addTest(security.suite())
- suite.addTest(api.suite())
- suite.addTest(regression.suite())
- suite.addTest(debug.suite())
- suite.addTest(utils.suite())
- suite.addTest(bytecode_cache.suite())
-
- # doctests will not run on python 3 currently. Too many issues
- # with that, do not test that on that platform.
- if PY2:
- suite.addTest(doctests.suite())
-
- return suite
-
-
-def main():
- """Runs the testsuite as command line application."""
- try:
- unittest.main(testLoader=BetterLoader(), defaultTest='suite')
- except Exception as e:
- print('Error: %s' % e)
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/api.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/api.py
deleted file mode 100644
index 1b68bf8..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/api.py
+++ /dev/null
@@ -1,261 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.api
- ~~~~~~~~~~~~~~~~~~~~
-
- Tests the public API and related stuff.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-import os
-import tempfile
-import shutil
-
-from jinja2.testsuite import JinjaTestCase
-from jinja2._compat import next
-
-from jinja2 import Environment, Undefined, DebugUndefined, \
- StrictUndefined, UndefinedError, meta, \
- is_undefined, Template, DictLoader
-from jinja2.utils import Cycler
-
-env = Environment()
-
-
-class ExtendedAPITestCase(JinjaTestCase):
-
- def test_item_and_attribute(self):
- from jinja2.sandbox import SandboxedEnvironment
-
- for env in Environment(), SandboxedEnvironment():
- # the |list is necessary for python3
- tmpl = env.from_string('{{ foo.items()|list }}')
- assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"
- tmpl = env.from_string('{{ foo|attr("items")()|list }}')
- assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"
- tmpl = env.from_string('{{ foo["items"] }}')
- assert tmpl.render(foo={'items': 42}) == '42'
-
- def test_finalizer(self):
- def finalize_none_empty(value):
- if value is None:
- value = u''
- return value
- env = Environment(finalize=finalize_none_empty)
- tmpl = env.from_string('{% for item in seq %}|{{ item }}{% endfor %}')
- assert tmpl.render(seq=(None, 1, "foo")) == '||1|foo'
- tmpl = env.from_string('<{{ none }}>')
- assert tmpl.render() == '<>'
-
- def test_cycler(self):
- items = 1, 2, 3
- c = Cycler(*items)
- for item in items + items:
- assert c.current == item
- assert next(c) == item
- next(c)
- assert c.current == 2
- c.reset()
- assert c.current == 1
-
- def test_expressions(self):
- expr = env.compile_expression("foo")
- assert expr() is None
- assert expr(foo=42) == 42
- expr2 = env.compile_expression("foo", undefined_to_none=False)
- assert is_undefined(expr2())
-
- expr = env.compile_expression("42 + foo")
- assert expr(foo=42) == 84
-
- def test_template_passthrough(self):
- t = Template('Content')
- assert env.get_template(t) is t
- assert env.select_template([t]) is t
- assert env.get_or_select_template([t]) is t
- assert env.get_or_select_template(t) is t
-
- def test_autoescape_autoselect(self):
- def select_autoescape(name):
- if name is None or '.' not in name:
- return False
- return name.endswith('.html')
- env = Environment(autoescape=select_autoescape,
- loader=DictLoader({
- 'test.txt': '{{ foo }}',
- 'test.html': '{{ foo }}'
- }))
- t = env.get_template('test.txt')
- assert t.render(foo='') == ''
- t = env.get_template('test.html')
- assert t.render(foo='') == '<foo>'
- t = env.from_string('{{ foo }}')
- assert t.render(foo='') == ''
-
-
-class MetaTestCase(JinjaTestCase):
-
- def test_find_undeclared_variables(self):
- ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
- x = meta.find_undeclared_variables(ast)
- assert x == set(['bar'])
-
- ast = env.parse('{% set foo = 42 %}{{ bar + foo }}'
- '{% macro meh(x) %}{{ x }}{% endmacro %}'
- '{% for item in seq %}{{ muh(item) + meh(seq) }}{% endfor %}')
- x = meta.find_undeclared_variables(ast)
- assert x == set(['bar', 'seq', 'muh'])
-
- def test_find_refererenced_templates(self):
- ast = env.parse('{% extends "layout.html" %}{% include helper %}')
- i = meta.find_referenced_templates(ast)
- assert next(i) == 'layout.html'
- assert next(i) is None
- assert list(i) == []
-
- ast = env.parse('{% extends "layout.html" %}'
- '{% from "test.html" import a, b as c %}'
- '{% import "meh.html" as meh %}'
- '{% include "muh.html" %}')
- i = meta.find_referenced_templates(ast)
- assert list(i) == ['layout.html', 'test.html', 'meh.html', 'muh.html']
-
- def test_find_included_templates(self):
- ast = env.parse('{% include ["foo.html", "bar.html"] %}')
- i = meta.find_referenced_templates(ast)
- assert list(i) == ['foo.html', 'bar.html']
-
- ast = env.parse('{% include ("foo.html", "bar.html") %}')
- i = meta.find_referenced_templates(ast)
- assert list(i) == ['foo.html', 'bar.html']
-
- ast = env.parse('{% include ["foo.html", "bar.html", foo] %}')
- i = meta.find_referenced_templates(ast)
- assert list(i) == ['foo.html', 'bar.html', None]
-
- ast = env.parse('{% include ("foo.html", "bar.html", foo) %}')
- i = meta.find_referenced_templates(ast)
- assert list(i) == ['foo.html', 'bar.html', None]
-
-
-class StreamingTestCase(JinjaTestCase):
-
- def test_basic_streaming(self):
- tmpl = env.from_string("{% for item in seq %}- {{ loop.index "
- "}} - {{ item }}
{%- endfor %}
")
- stream = tmpl.stream(seq=list(range(4)))
- self.assert_equal(next(stream), '')
- self.assert_equal(next(stream), '- 1 - 0
')
- self.assert_equal(next(stream), '- 2 - 1
')
- self.assert_equal(next(stream), '- 3 - 2
')
- self.assert_equal(next(stream), '- 4 - 3
')
- self.assert_equal(next(stream), '
')
-
- def test_buffered_streaming(self):
- tmpl = env.from_string("{% for item in seq %}- {{ loop.index "
- "}} - {{ item }}
{%- endfor %}
")
- stream = tmpl.stream(seq=list(range(4)))
- stream.enable_buffering(size=3)
- self.assert_equal(next(stream), u'- 1 - 0
- 2 - 1
')
- self.assert_equal(next(stream), u'- 3 - 2
- 4 - 3
')
-
- def test_streaming_behavior(self):
- tmpl = env.from_string("")
- stream = tmpl.stream()
- assert not stream.buffered
- stream.enable_buffering(20)
- assert stream.buffered
- stream.disable_buffering()
- assert not stream.buffered
-
- def test_dump_stream(self):
- tmp = tempfile.mkdtemp()
- try:
- tmpl = env.from_string(u"\u2713")
- stream = tmpl.stream()
- stream.dump(os.path.join(tmp, 'dump.txt'), 'utf-8')
- with open(os.path.join(tmp, 'dump.txt'), 'rb') as f:
- self.assertEqual(f.read(), b'\xe2\x9c\x93')
- finally:
- shutil.rmtree(tmp)
-
-
-class UndefinedTestCase(JinjaTestCase):
-
- def test_stopiteration_is_undefined(self):
- def test():
- raise StopIteration()
- t = Template('A{{ test() }}B')
- assert t.render(test=test) == 'AB'
- t = Template('A{{ test().missingattribute }}B')
- self.assert_raises(UndefinedError, t.render, test=test)
-
- def test_undefined_and_special_attributes(self):
- try:
- Undefined('Foo').__dict__
- except AttributeError:
- pass
- else:
- assert False, "Expected actual attribute error"
-
- def test_default_undefined(self):
- env = Environment(undefined=Undefined)
- self.assert_equal(env.from_string('{{ missing }}').render(), u'')
- self.assert_raises(UndefinedError,
- env.from_string('{{ missing.attribute }}').render)
- self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]')
- self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True')
- self.assert_equal(env.from_string('{{ foo.missing }}').render(foo=42), '')
- self.assert_equal(env.from_string('{{ not missing }}').render(), 'True')
-
- def test_debug_undefined(self):
- env = Environment(undefined=DebugUndefined)
- self.assert_equal(env.from_string('{{ missing }}').render(), '{{ missing }}')
- self.assert_raises(UndefinedError,
- env.from_string('{{ missing.attribute }}').render)
- self.assert_equal(env.from_string('{{ missing|list }}').render(), '[]')
- self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True')
- self.assert_equal(env.from_string('{{ foo.missing }}').render(foo=42),
- u"{{ no such element: int object['missing'] }}")
- self.assert_equal(env.from_string('{{ not missing }}').render(), 'True')
-
- def test_strict_undefined(self):
- env = Environment(undefined=StrictUndefined)
- self.assert_raises(UndefinedError, env.from_string('{{ missing }}').render)
- self.assert_raises(UndefinedError, env.from_string('{{ missing.attribute }}').render)
- self.assert_raises(UndefinedError, env.from_string('{{ missing|list }}').render)
- self.assert_equal(env.from_string('{{ missing is not defined }}').render(), 'True')
- self.assert_raises(UndefinedError, env.from_string('{{ foo.missing }}').render, foo=42)
- self.assert_raises(UndefinedError, env.from_string('{{ not missing }}').render)
- self.assert_equal(env.from_string('{{ missing|default("default", true) }}').render(), 'default')
-
- def test_indexing_gives_undefined(self):
- t = Template("{{ var[42].foo }}")
- self.assert_raises(UndefinedError, t.render, var=0)
-
- def test_none_gives_proper_error(self):
- try:
- Environment().getattr(None, 'split')()
- except UndefinedError as e:
- assert e.message == "'None' has no attribute 'split'"
- else:
- assert False, 'expected exception'
-
- def test_object_repr(self):
- try:
- Undefined(obj=42, name='upper')()
- except UndefinedError as e:
- assert e.message == "'int object' has no attribute 'upper'"
- else:
- assert False, 'expected exception'
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(ExtendedAPITestCase))
- suite.addTest(unittest.makeSuite(MetaTestCase))
- suite.addTest(unittest.makeSuite(StreamingTestCase))
- suite.addTest(unittest.makeSuite(UndefinedTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/bytecode_cache.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/bytecode_cache.py
deleted file mode 100644
index 9f5c635..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/bytecode_cache.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.bytecode_cache
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Test bytecode caching
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-
-from jinja2.testsuite import JinjaTestCase, package_loader
-
-from jinja2 import Environment
-from jinja2.bccache import FileSystemBytecodeCache
-from jinja2.exceptions import TemplateNotFound
-
-bytecode_cache = FileSystemBytecodeCache()
-env = Environment(
- loader=package_loader,
- bytecode_cache=bytecode_cache,
-)
-
-
-class ByteCodeCacheTestCase(JinjaTestCase):
-
- def test_simple(self):
- tmpl = env.get_template('test.html')
- assert tmpl.render().strip() == 'BAR'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(ByteCodeCacheTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/core_tags.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/core_tags.py
deleted file mode 100644
index f1a20fd..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/core_tags.py
+++ /dev/null
@@ -1,305 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.core_tags
- ~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Test the core tags like for and if.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Environment, TemplateSyntaxError, UndefinedError, \
- DictLoader
-
-env = Environment()
-
-
-class ForLoopTestCase(JinjaTestCase):
-
- def test_simple(self):
- tmpl = env.from_string('{% for item in seq %}{{ item }}{% endfor %}')
- assert tmpl.render(seq=list(range(10))) == '0123456789'
-
- def test_else(self):
- tmpl = env.from_string('{% for item in seq %}XXX{% else %}...{% endfor %}')
- assert tmpl.render() == '...'
-
- def test_empty_blocks(self):
- tmpl = env.from_string('<{% for item in seq %}{% else %}{% endfor %}>')
- assert tmpl.render() == '<>'
-
- def test_context_vars(self):
- tmpl = env.from_string('''{% for item in seq -%}
- {{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{
- loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{
- loop.length }}###{% endfor %}''')
- one, two, _ = tmpl.render(seq=[0, 1]).split('###')
- (one_index, one_index0, one_revindex, one_revindex0, one_first,
- one_last, one_length) = one.split('|')
- (two_index, two_index0, two_revindex, two_revindex0, two_first,
- two_last, two_length) = two.split('|')
-
- assert int(one_index) == 1 and int(two_index) == 2
- assert int(one_index0) == 0 and int(two_index0) == 1
- assert int(one_revindex) == 2 and int(two_revindex) == 1
- assert int(one_revindex0) == 1 and int(two_revindex0) == 0
- assert one_first == 'True' and two_first == 'False'
- assert one_last == 'False' and two_last == 'True'
- assert one_length == two_length == '2'
-
- def test_cycling(self):
- tmpl = env.from_string('''{% for item in seq %}{{
- loop.cycle('<1>', '<2>') }}{% endfor %}{%
- for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')
- output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))
- assert output == '<1><2>' * 4
-
- def test_scope(self):
- tmpl = env.from_string('{% for item in seq %}{% endfor %}{{ item }}')
- output = tmpl.render(seq=list(range(10)))
- assert not output
-
- def test_varlen(self):
- def inner():
- for item in range(5):
- yield item
- tmpl = env.from_string('{% for item in iter %}{{ item }}{% endfor %}')
- output = tmpl.render(iter=inner())
- assert output == '01234'
-
- def test_noniter(self):
- tmpl = env.from_string('{% for item in none %}...{% endfor %}')
- self.assert_raises(TypeError, tmpl.render)
-
- def test_recursive(self):
- tmpl = env.from_string('''{% for item in seq recursive -%}
- [{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]
- {%- endfor %}''')
- assert tmpl.render(seq=[
- dict(a=1, b=[dict(a=1), dict(a=2)]),
- dict(a=2, b=[dict(a=1), dict(a=2)]),
- dict(a=3, b=[dict(a='a')])
- ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'
-
- def test_recursive_depth0(self):
- tmpl = env.from_string('''{% for item in seq recursive -%}
- [{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]
- {%- endfor %}''')
- self.assertEqual(tmpl.render(seq=[
- dict(a=1, b=[dict(a=1), dict(a=2)]),
- dict(a=2, b=[dict(a=1), dict(a=2)]),
- dict(a=3, b=[dict(a='a')])
- ]), '[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]')
-
- def test_recursive_depth(self):
- tmpl = env.from_string('''{% for item in seq recursive -%}
- [{{ loop.depth }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]
- {%- endfor %}''')
- self.assertEqual(tmpl.render(seq=[
- dict(a=1, b=[dict(a=1), dict(a=2)]),
- dict(a=2, b=[dict(a=1), dict(a=2)]),
- dict(a=3, b=[dict(a='a')])
- ]), '[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]')
-
- def test_looploop(self):
- tmpl = env.from_string('''{% for row in table %}
- {%- set rowloop = loop -%}
- {% for cell in row -%}
- [{{ rowloop.index }}|{{ loop.index }}]
- {%- endfor %}
- {%- endfor %}''')
- assert tmpl.render(table=['ab', 'cd']) == '[1|1][1|2][2|1][2|2]'
-
- def test_reversed_bug(self):
- tmpl = env.from_string('{% for i in items %}{{ i }}'
- '{% if not loop.last %}'
- ',{% endif %}{% endfor %}')
- assert tmpl.render(items=reversed([3, 2, 1])) == '1,2,3'
-
- def test_loop_errors(self):
- tmpl = env.from_string('''{% for item in [1] if loop.index
- == 0 %}...{% endfor %}''')
- self.assert_raises(UndefinedError, tmpl.render)
- tmpl = env.from_string('''{% for item in [] %}...{% else
- %}{{ loop }}{% endfor %}''')
- assert tmpl.render() == ''
-
- def test_loop_filter(self):
- tmpl = env.from_string('{% for item in range(10) if item '
- 'is even %}[{{ item }}]{% endfor %}')
- assert tmpl.render() == '[0][2][4][6][8]'
- tmpl = env.from_string('''
- {%- for item in range(10) if item is even %}[{{
- loop.index }}:{{ item }}]{% endfor %}''')
- assert tmpl.render() == '[1:0][2:2][3:4][4:6][5:8]'
-
- def test_loop_unassignable(self):
- self.assert_raises(TemplateSyntaxError, env.from_string,
- '{% for loop in seq %}...{% endfor %}')
-
- def test_scoped_special_var(self):
- t = env.from_string('{% for s in seq %}[{{ loop.first }}{% for c in s %}'
- '|{{ loop.first }}{% endfor %}]{% endfor %}')
- assert t.render(seq=('ab', 'cd')) == '[True|True|False][False|True|False]'
-
- def test_scoped_loop_var(self):
- t = env.from_string('{% for x in seq %}{{ loop.first }}'
- '{% for y in seq %}{% endfor %}{% endfor %}')
- assert t.render(seq='ab') == 'TrueFalse'
- t = env.from_string('{% for x in seq %}{% for y in seq %}'
- '{{ loop.first }}{% endfor %}{% endfor %}')
- assert t.render(seq='ab') == 'TrueFalseTrueFalse'
-
- def test_recursive_empty_loop_iter(self):
- t = env.from_string('''
- {%- for item in foo recursive -%}{%- endfor -%}
- ''')
- assert t.render(dict(foo=[])) == ''
-
- def test_call_in_loop(self):
- t = env.from_string('''
- {%- macro do_something() -%}
- [{{ caller() }}]
- {%- endmacro %}
-
- {%- for i in [1, 2, 3] %}
- {%- call do_something() -%}
- {{ i }}
- {%- endcall %}
- {%- endfor -%}
- ''')
- assert t.render() == '[1][2][3]'
-
- def test_scoping_bug(self):
- t = env.from_string('''
- {%- for item in foo %}...{{ item }}...{% endfor %}
- {%- macro item(a) %}...{{ a }}...{% endmacro %}
- {{- item(2) -}}
- ''')
- assert t.render(foo=(1,)) == '...1......2...'
-
- def test_unpacking(self):
- tmpl = env.from_string('{% for a, b, c in [[1, 2, 3]] %}'
- '{{ a }}|{{ b }}|{{ c }}{% endfor %}')
- assert tmpl.render() == '1|2|3'
-
-
-class IfConditionTestCase(JinjaTestCase):
-
- def test_simple(self):
- tmpl = env.from_string('''{% if true %}...{% endif %}''')
- assert tmpl.render() == '...'
-
- def test_elif(self):
- tmpl = env.from_string('''{% if false %}XXX{% elif true
- %}...{% else %}XXX{% endif %}''')
- assert tmpl.render() == '...'
-
- def test_else(self):
- tmpl = env.from_string('{% if false %}XXX{% else %}...{% endif %}')
- assert tmpl.render() == '...'
-
- def test_empty(self):
- tmpl = env.from_string('[{% if true %}{% else %}{% endif %}]')
- assert tmpl.render() == '[]'
-
- def test_complete(self):
- tmpl = env.from_string('{% if a %}A{% elif b %}B{% elif c == d %}'
- 'C{% else %}D{% endif %}')
- assert tmpl.render(a=0, b=False, c=42, d=42.0) == 'C'
-
- def test_no_scope(self):
- tmpl = env.from_string('{% if a %}{% set foo = 1 %}{% endif %}{{ foo }}')
- assert tmpl.render(a=True) == '1'
- tmpl = env.from_string('{% if true %}{% set foo = 1 %}{% endif %}{{ foo }}')
- assert tmpl.render() == '1'
-
-
-class MacrosTestCase(JinjaTestCase):
- env = Environment(trim_blocks=True)
-
- def test_simple(self):
- tmpl = self.env.from_string('''\
-{% macro say_hello(name) %}Hello {{ name }}!{% endmacro %}
-{{ say_hello('Peter') }}''')
- assert tmpl.render() == 'Hello Peter!'
-
- def test_scoping(self):
- tmpl = self.env.from_string('''\
-{% macro level1(data1) %}
-{% macro level2(data2) %}{{ data1 }}|{{ data2 }}{% endmacro %}
-{{ level2('bar') }}{% endmacro %}
-{{ level1('foo') }}''')
- assert tmpl.render() == 'foo|bar'
-
- def test_arguments(self):
- tmpl = self.env.from_string('''\
-{% macro m(a, b, c='c', d='d') %}{{ a }}|{{ b }}|{{ c }}|{{ d }}{% endmacro %}
-{{ m() }}|{{ m('a') }}|{{ m('a', 'b') }}|{{ m(1, 2, 3) }}''')
- assert tmpl.render() == '||c|d|a||c|d|a|b|c|d|1|2|3|d'
-
- def test_varargs(self):
- tmpl = self.env.from_string('''\
-{% macro test() %}{{ varargs|join('|') }}{% endmacro %}\
-{{ test(1, 2, 3) }}''')
- assert tmpl.render() == '1|2|3'
-
- def test_simple_call(self):
- tmpl = self.env.from_string('''\
-{% macro test() %}[[{{ caller() }}]]{% endmacro %}\
-{% call test() %}data{% endcall %}''')
- assert tmpl.render() == '[[data]]'
-
- def test_complex_call(self):
- tmpl = self.env.from_string('''\
-{% macro test() %}[[{{ caller('data') }}]]{% endmacro %}\
-{% call(data) test() %}{{ data }}{% endcall %}''')
- assert tmpl.render() == '[[data]]'
-
- def test_caller_undefined(self):
- tmpl = self.env.from_string('''\
-{% set caller = 42 %}\
-{% macro test() %}{{ caller is not defined }}{% endmacro %}\
-{{ test() }}''')
- assert tmpl.render() == 'True'
-
- def test_include(self):
- self.env = Environment(loader=DictLoader({'include':
- '{% macro test(foo) %}[{{ foo }}]{% endmacro %}'}))
- tmpl = self.env.from_string('{% from "include" import test %}{{ test("foo") }}')
- assert tmpl.render() == '[foo]'
-
- def test_macro_api(self):
- tmpl = self.env.from_string('{% macro foo(a, b) %}{% endmacro %}'
- '{% macro bar() %}{{ varargs }}{{ kwargs }}{% endmacro %}'
- '{% macro baz() %}{{ caller() }}{% endmacro %}')
- assert tmpl.module.foo.arguments == ('a', 'b')
- assert tmpl.module.foo.defaults == ()
- assert tmpl.module.foo.name == 'foo'
- assert not tmpl.module.foo.caller
- assert not tmpl.module.foo.catch_kwargs
- assert not tmpl.module.foo.catch_varargs
- assert tmpl.module.bar.arguments == ()
- assert tmpl.module.bar.defaults == ()
- assert not tmpl.module.bar.caller
- assert tmpl.module.bar.catch_kwargs
- assert tmpl.module.bar.catch_varargs
- assert tmpl.module.baz.caller
-
- def test_callself(self):
- tmpl = self.env.from_string('{% macro foo(x) %}{{ x }}{% if x > 1 %}|'
- '{{ foo(x - 1) }}{% endif %}{% endmacro %}'
- '{{ foo(5) }}')
- assert tmpl.render() == '5|4|3|2|1'
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(ForLoopTestCase))
- suite.addTest(unittest.makeSuite(IfConditionTestCase))
- suite.addTest(unittest.makeSuite(MacrosTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/debug.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/debug.py
deleted file mode 100644
index 2588a83..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/debug.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.debug
- ~~~~~~~~~~~~~~~~~~~~~~
-
- Tests the debug system.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-
-from jinja2.testsuite import JinjaTestCase, filesystem_loader
-
-from jinja2 import Environment, TemplateSyntaxError
-
-env = Environment(loader=filesystem_loader)
-
-
-class DebugTestCase(JinjaTestCase):
-
- def test_runtime_error(self):
- def test():
- tmpl.render(fail=lambda: 1 / 0)
- tmpl = env.get_template('broken.html')
- self.assert_traceback_matches(test, r'''
- File ".*?broken.html", line 2, in (top-level template code|)
- \{\{ fail\(\) \}\}
- File ".*?debug.pyc?", line \d+, in
- tmpl\.render\(fail=lambda: 1 / 0\)
-ZeroDivisionError: (int(eger)? )?division (or modulo )?by zero
-''')
-
- def test_syntax_error(self):
- # XXX: the .*? is necessary for python3 which does not hide
- # some of the stack frames we don't want to show. Not sure
- # what's up with that, but that is not that critical. Should
- # be fixed though.
- self.assert_traceback_matches(lambda: env.get_template('syntaxerror.html'), r'''(?sm)
- File ".*?syntaxerror.html", line 4, in (template|)
- \{% endif %\}.*?
-(jinja2\.exceptions\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
- ''')
-
- def test_regular_syntax_error(self):
- def test():
- raise TemplateSyntaxError('wtf', 42)
- self.assert_traceback_matches(test, r'''
- File ".*debug.pyc?", line \d+, in test
- raise TemplateSyntaxError\('wtf', 42\)
-(jinja2\.exceptions\.)?TemplateSyntaxError: wtf
- line 42''')
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(DebugTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/doctests.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/doctests.py
deleted file mode 100644
index 616d3b6..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/doctests.py
+++ /dev/null
@@ -1,29 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.doctests
- ~~~~~~~~~~~~~~~~~~~~~~~~~
-
- The doctests. Collects all tests we want to test from
- the Jinja modules.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-import doctest
-
-
-def suite():
- from jinja2 import utils, sandbox, runtime, meta, loaders, \
- ext, environment, bccache, nodes
- suite = unittest.TestSuite()
- suite.addTest(doctest.DocTestSuite(utils))
- suite.addTest(doctest.DocTestSuite(sandbox))
- suite.addTest(doctest.DocTestSuite(runtime))
- suite.addTest(doctest.DocTestSuite(meta))
- suite.addTest(doctest.DocTestSuite(loaders))
- suite.addTest(doctest.DocTestSuite(ext))
- suite.addTest(doctest.DocTestSuite(environment))
- suite.addTest(doctest.DocTestSuite(bccache))
- suite.addTest(doctest.DocTestSuite(nodes))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/ext.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/ext.py
deleted file mode 100644
index 0f93be9..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/ext.py
+++ /dev/null
@@ -1,459 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.ext
- ~~~~~~~~~~~~~~~~~~~~
-
- Tests for the extensions.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import re
-import unittest
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Environment, DictLoader, contextfunction, nodes
-from jinja2.exceptions import TemplateAssertionError
-from jinja2.ext import Extension
-from jinja2.lexer import Token, count_newlines
-from jinja2._compat import next, BytesIO, itervalues, text_type
-
-importable_object = 23
-
-_gettext_re = re.compile(r'_\((.*?)\)(?s)')
-
-
-i18n_templates = {
- 'master.html': '{{ page_title|default(_("missing")) }}'
- '{% block body %}{% endblock %}',
- 'child.html': '{% extends "master.html" %}{% block body %}'
- '{% trans %}watch out{% endtrans %}{% endblock %}',
- 'plural.html': '{% trans user_count %}One user online{% pluralize %}'
- '{{ user_count }} users online{% endtrans %}',
- 'plural2.html': '{% trans user_count=get_user_count() %}{{ user_count }}s'
- '{% pluralize %}{{ user_count }}p{% endtrans %}',
- 'stringformat.html': '{{ _("User: %(num)s")|format(num=user_count) }}'
-}
-
-newstyle_i18n_templates = {
- 'master.html': '{{ page_title|default(_("missing")) }}'
- '{% block body %}{% endblock %}',
- 'child.html': '{% extends "master.html" %}{% block body %}'
- '{% trans %}watch out{% endtrans %}{% endblock %}',
- 'plural.html': '{% trans user_count %}One user online{% pluralize %}'
- '{{ user_count }} users online{% endtrans %}',
- 'stringformat.html': '{{ _("User: %(num)s", num=user_count) }}',
- 'ngettext.html': '{{ ngettext("%(num)s apple", "%(num)s apples", apples) }}',
- 'ngettext_long.html': '{% trans num=apples %}{{ num }} apple{% pluralize %}'
- '{{ num }} apples{% endtrans %}',
- 'transvars1.html': '{% trans %}User: {{ num }}{% endtrans %}',
- 'transvars2.html': '{% trans num=count %}User: {{ num }}{% endtrans %}',
- 'transvars3.html': '{% trans count=num %}User: {{ count }}{% endtrans %}',
- 'novars.html': '{% trans %}%(hello)s{% endtrans %}',
- 'vars.html': '{% trans %}{{ foo }}%(foo)s{% endtrans %}',
- 'explicitvars.html': '{% trans foo="42" %}%(foo)s{% endtrans %}'
-}
-
-
-languages = {
- 'de': {
- 'missing': u'fehlend',
- 'watch out': u'pass auf',
- 'One user online': u'Ein Benutzer online',
- '%(user_count)s users online': u'%(user_count)s Benutzer online',
- 'User: %(num)s': u'Benutzer: %(num)s',
- 'User: %(count)s': u'Benutzer: %(count)s',
- '%(num)s apple': u'%(num)s Apfel',
- '%(num)s apples': u'%(num)s Äpfel'
- }
-}
-
-
-@contextfunction
-def gettext(context, string):
- language = context.get('LANGUAGE', 'en')
- return languages.get(language, {}).get(string, string)
-
-
-@contextfunction
-def ngettext(context, s, p, n):
- language = context.get('LANGUAGE', 'en')
- if n != 1:
- return languages.get(language, {}).get(p, p)
- return languages.get(language, {}).get(s, s)
-
-
-i18n_env = Environment(
- loader=DictLoader(i18n_templates),
- extensions=['jinja2.ext.i18n']
-)
-i18n_env.globals.update({
- '_': gettext,
- 'gettext': gettext,
- 'ngettext': ngettext
-})
-
-newstyle_i18n_env = Environment(
- loader=DictLoader(newstyle_i18n_templates),
- extensions=['jinja2.ext.i18n']
-)
-newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)
-
-class TestExtension(Extension):
- tags = set(['test'])
- ext_attr = 42
-
- def parse(self, parser):
- return nodes.Output([self.call_method('_dump', [
- nodes.EnvironmentAttribute('sandboxed'),
- self.attr('ext_attr'),
- nodes.ImportedName(__name__ + '.importable_object'),
- nodes.ContextReference()
- ])]).set_lineno(next(parser.stream).lineno)
-
- def _dump(self, sandboxed, ext_attr, imported_object, context):
- return '%s|%s|%s|%s' % (
- sandboxed,
- ext_attr,
- imported_object,
- context.blocks
- )
-
-
-class PreprocessorExtension(Extension):
-
- def preprocess(self, source, name, filename=None):
- return source.replace('[[TEST]]', '({{ foo }})')
-
-
-class StreamFilterExtension(Extension):
-
- def filter_stream(self, stream):
- for token in stream:
- if token.type == 'data':
- for t in self.interpolate(token):
- yield t
- else:
- yield token
-
- def interpolate(self, token):
- pos = 0
- end = len(token.value)
- lineno = token.lineno
- while 1:
- match = _gettext_re.search(token.value, pos)
- if match is None:
- break
- value = token.value[pos:match.start()]
- if value:
- yield Token(lineno, 'data', value)
- lineno += count_newlines(token.value)
- yield Token(lineno, 'variable_begin', None)
- yield Token(lineno, 'name', 'gettext')
- yield Token(lineno, 'lparen', None)
- yield Token(lineno, 'string', match.group(1))
- yield Token(lineno, 'rparen', None)
- yield Token(lineno, 'variable_end', None)
- pos = match.end()
- if pos < end:
- yield Token(lineno, 'data', token.value[pos:])
-
-
-class ExtensionsTestCase(JinjaTestCase):
-
- def test_extend_late(self):
- env = Environment()
- env.add_extension('jinja2.ext.autoescape')
- t = env.from_string('{% autoescape true %}{{ "" }}{% endautoescape %}')
- assert t.render() == '<test>'
-
- def test_loop_controls(self):
- env = Environment(extensions=['jinja2.ext.loopcontrols'])
-
- tmpl = env.from_string('''
- {%- for item in [1, 2, 3, 4] %}
- {%- if item % 2 == 0 %}{% continue %}{% endif -%}
- {{ item }}
- {%- endfor %}''')
- assert tmpl.render() == '13'
-
- tmpl = env.from_string('''
- {%- for item in [1, 2, 3, 4] %}
- {%- if item > 2 %}{% break %}{% endif -%}
- {{ item }}
- {%- endfor %}''')
- assert tmpl.render() == '12'
-
- def test_do(self):
- env = Environment(extensions=['jinja2.ext.do'])
- tmpl = env.from_string('''
- {%- set items = [] %}
- {%- for char in "foo" %}
- {%- do items.append(loop.index0 ~ char) %}
- {%- endfor %}{{ items|join(', ') }}''')
- assert tmpl.render() == '0f, 1o, 2o'
-
- def test_with(self):
- env = Environment(extensions=['jinja2.ext.with_'])
- tmpl = env.from_string('''\
- {% with a=42, b=23 -%}
- {{ a }} = {{ b }}
- {% endwith -%}
- {{ a }} = {{ b }}\
- ''')
- assert [x.strip() for x in tmpl.render(a=1, b=2).splitlines()] \
- == ['42 = 23', '1 = 2']
-
- def test_extension_nodes(self):
- env = Environment(extensions=[TestExtension])
- tmpl = env.from_string('{% test %}')
- assert tmpl.render() == 'False|42|23|{}'
-
- def test_identifier(self):
- assert TestExtension.identifier == __name__ + '.TestExtension'
-
- def test_rebinding(self):
- original = Environment(extensions=[TestExtension])
- overlay = original.overlay()
- for env in original, overlay:
- for ext in itervalues(env.extensions):
- assert ext.environment is env
-
- def test_preprocessor_extension(self):
- env = Environment(extensions=[PreprocessorExtension])
- tmpl = env.from_string('{[[TEST]]}')
- assert tmpl.render(foo=42) == '{(42)}'
-
- def test_streamfilter_extension(self):
- env = Environment(extensions=[StreamFilterExtension])
- env.globals['gettext'] = lambda x: x.upper()
- tmpl = env.from_string('Foo _(bar) Baz')
- out = tmpl.render()
- assert out == 'Foo BAR Baz'
-
- def test_extension_ordering(self):
- class T1(Extension):
- priority = 1
- class T2(Extension):
- priority = 2
- env = Environment(extensions=[T1, T2])
- ext = list(env.iter_extensions())
- assert ext[0].__class__ is T1
- assert ext[1].__class__ is T2
-
-
-class InternationalizationTestCase(JinjaTestCase):
-
- def test_trans(self):
- tmpl = i18n_env.get_template('child.html')
- assert tmpl.render(LANGUAGE='de') == 'fehlendpass auf'
-
- def test_trans_plural(self):
- tmpl = i18n_env.get_template('plural.html')
- assert tmpl.render(LANGUAGE='de', user_count=1) == 'Ein Benutzer online'
- assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'
-
- def test_trans_plural_with_functions(self):
- tmpl = i18n_env.get_template('plural2.html')
- def get_user_count():
- get_user_count.called += 1
- return 1
- get_user_count.called = 0
- assert tmpl.render(LANGUAGE='de', get_user_count=get_user_count) == '1s'
- assert get_user_count.called == 1
-
- def test_complex_plural(self):
- tmpl = i18n_env.from_string('{% trans foo=42, count=2 %}{{ count }} item{% '
- 'pluralize count %}{{ count }} items{% endtrans %}')
- assert tmpl.render() == '2 items'
- self.assert_raises(TemplateAssertionError, i18n_env.from_string,
- '{% trans foo %}...{% pluralize bar %}...{% endtrans %}')
-
- def test_trans_stringformatting(self):
- tmpl = i18n_env.get_template('stringformat.html')
- assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'
-
- def test_extract(self):
- from jinja2.ext import babel_extract
- source = BytesIO('''
- {{ gettext('Hello World') }}
- {% trans %}Hello World{% endtrans %}
- {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}
- '''.encode('ascii')) # make python 3 happy
- assert list(babel_extract(source, ('gettext', 'ngettext', '_'), [], {})) == [
- (2, 'gettext', u'Hello World', []),
- (3, 'gettext', u'Hello World', []),
- (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])
- ]
-
- def test_comment_extract(self):
- from jinja2.ext import babel_extract
- source = BytesIO('''
- {# trans first #}
- {{ gettext('Hello World') }}
- {% trans %}Hello World{% endtrans %}{# trans second #}
- {#: third #}
- {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}
- '''.encode('utf-8')) # make python 3 happy
- assert list(babel_extract(source, ('gettext', 'ngettext', '_'), ['trans', ':'], {})) == [
- (3, 'gettext', u'Hello World', ['first']),
- (4, 'gettext', u'Hello World', ['second']),
- (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), ['third'])
- ]
-
-
-class NewstyleInternationalizationTestCase(JinjaTestCase):
-
- def test_trans(self):
- tmpl = newstyle_i18n_env.get_template('child.html')
- assert tmpl.render(LANGUAGE='de') == 'fehlendpass auf'
-
- def test_trans_plural(self):
- tmpl = newstyle_i18n_env.get_template('plural.html')
- assert tmpl.render(LANGUAGE='de', user_count=1) == 'Ein Benutzer online'
- assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'
-
- def test_complex_plural(self):
- tmpl = newstyle_i18n_env.from_string('{% trans foo=42, count=2 %}{{ count }} item{% '
- 'pluralize count %}{{ count }} items{% endtrans %}')
- assert tmpl.render() == '2 items'
- self.assert_raises(TemplateAssertionError, i18n_env.from_string,
- '{% trans foo %}...{% pluralize bar %}...{% endtrans %}')
-
- def test_trans_stringformatting(self):
- tmpl = newstyle_i18n_env.get_template('stringformat.html')
- assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'
-
- def test_newstyle_plural(self):
- tmpl = newstyle_i18n_env.get_template('ngettext.html')
- assert tmpl.render(LANGUAGE='de', apples=1) == '1 Apfel'
- assert tmpl.render(LANGUAGE='de', apples=5) == u'5 Äpfel'
-
- def test_autoescape_support(self):
- env = Environment(extensions=['jinja2.ext.autoescape',
- 'jinja2.ext.i18n'])
- env.install_gettext_callables(lambda x: u'Wert: %(name)s',
- lambda s, p, n: s, newstyle=True)
- t = env.from_string('{% autoescape ae %}{{ gettext("foo", name='
- '"") }}{% endautoescape %}')
- assert t.render(ae=True) == 'Wert: <test>'
- assert t.render(ae=False) == 'Wert: '
-
- def test_num_used_twice(self):
- tmpl = newstyle_i18n_env.get_template('ngettext_long.html')
- assert tmpl.render(apples=5, LANGUAGE='de') == u'5 Äpfel'
-
- def test_num_called_num(self):
- source = newstyle_i18n_env.compile('''
- {% trans num=3 %}{{ num }} apple{% pluralize
- %}{{ num }} apples{% endtrans %}
- ''', raw=True)
- # quite hacky, but the only way to properly test that. The idea is
- # that the generated code does not pass num twice (although that
- # would work) for better performance. This only works on the
- # newstyle gettext of course
- assert re.search(r"l_ngettext, u?'\%\(num\)s apple', u?'\%\(num\)s "
- r"apples', 3", source) is not None
-
- def test_trans_vars(self):
- t1 = newstyle_i18n_env.get_template('transvars1.html')
- t2 = newstyle_i18n_env.get_template('transvars2.html')
- t3 = newstyle_i18n_env.get_template('transvars3.html')
- assert t1.render(num=1, LANGUAGE='de') == 'Benutzer: 1'
- assert t2.render(count=23, LANGUAGE='de') == 'Benutzer: 23'
- assert t3.render(num=42, LANGUAGE='de') == 'Benutzer: 42'
-
- def test_novars_vars_escaping(self):
- t = newstyle_i18n_env.get_template('novars.html')
- assert t.render() == '%(hello)s'
- t = newstyle_i18n_env.get_template('vars.html')
- assert t.render(foo='42') == '42%(foo)s'
- t = newstyle_i18n_env.get_template('explicitvars.html')
- assert t.render() == '%(foo)s'
-
-
-class AutoEscapeTestCase(JinjaTestCase):
-
- def test_scoped_setting(self):
- env = Environment(extensions=['jinja2.ext.autoescape'],
- autoescape=True)
- tmpl = env.from_string('''
- {{ "" }}
- {% autoescape false %}
- {{ "" }}
- {% endautoescape %}
- {{ "" }}
- ''')
- assert tmpl.render().split() == \
- [u'<HelloWorld>', u'', u'<HelloWorld>']
-
- env = Environment(extensions=['jinja2.ext.autoescape'],
- autoescape=False)
- tmpl = env.from_string('''
- {{ "" }}
- {% autoescape true %}
- {{ "" }}
- {% endautoescape %}
- {{ "" }}
- ''')
- assert tmpl.render().split() == \
- [u'', u'<HelloWorld>', u'']
-
- def test_nonvolatile(self):
- env = Environment(extensions=['jinja2.ext.autoescape'],
- autoescape=True)
- tmpl = env.from_string('{{ {"foo": ""}|xmlattr|escape }}')
- assert tmpl.render() == ' foo="<test>"'
- tmpl = env.from_string('{% autoescape false %}{{ {"foo": ""}'
- '|xmlattr|escape }}{% endautoescape %}')
- assert tmpl.render() == ' foo="<test>"'
-
- def test_volatile(self):
- env = Environment(extensions=['jinja2.ext.autoescape'],
- autoescape=True)
- tmpl = env.from_string('{% autoescape foo %}{{ {"foo": ""}'
- '|xmlattr|escape }}{% endautoescape %}')
- assert tmpl.render(foo=False) == ' foo="<test>"'
- assert tmpl.render(foo=True) == ' foo="<test>"'
-
- def test_scoping(self):
- env = Environment(extensions=['jinja2.ext.autoescape'])
- tmpl = env.from_string('{% autoescape true %}{% set x = "" %}{{ x }}'
- '{% endautoescape %}{{ x }}{{ "" }}')
- assert tmpl.render(x=1) == '<x>1'
-
- def test_volatile_scoping(self):
- env = Environment(extensions=['jinja2.ext.autoescape'])
- tmplsource = '''
- {% autoescape val %}
- {% macro foo(x) %}
- [{{ x }}]
- {% endmacro %}
- {{ foo().__class__.__name__ }}
- {% endautoescape %}
- {{ '' }}
- '''
- tmpl = env.from_string(tmplsource)
- assert tmpl.render(val=True).split()[0] == 'Markup'
- assert tmpl.render(val=False).split()[0] == text_type.__name__
-
- # looking at the source we should see there in raw
- # (and then escaped as well)
- env = Environment(extensions=['jinja2.ext.autoescape'])
- pysource = env.compile(tmplsource, raw=True)
- assert '\\n' in pysource
-
- env = Environment(extensions=['jinja2.ext.autoescape'],
- autoescape=True)
- pysource = env.compile(tmplsource, raw=True)
- assert '<testing>\\n' in pysource
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(ExtensionsTestCase))
- suite.addTest(unittest.makeSuite(InternationalizationTestCase))
- suite.addTest(unittest.makeSuite(NewstyleInternationalizationTestCase))
- suite.addTest(unittest.makeSuite(AutoEscapeTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/filters.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/filters.py
deleted file mode 100644
index 282dd2d..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/filters.py
+++ /dev/null
@@ -1,515 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.filters
- ~~~~~~~~~~~~~~~~~~~~~~~~
-
- Tests for the jinja filters.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Markup, Environment
-from jinja2._compat import text_type, implements_to_string
-
-env = Environment()
-
-
-class FilterTestCase(JinjaTestCase):
-
- def test_filter_calling(self):
- rv = env.call_filter('sum', [1, 2, 3])
- self.assert_equal(rv, 6)
-
- def test_capitalize(self):
- tmpl = env.from_string('{{ "foo bar"|capitalize }}')
- assert tmpl.render() == 'Foo bar'
-
- def test_center(self):
- tmpl = env.from_string('{{ "foo"|center(9) }}')
- assert tmpl.render() == ' foo '
-
- def test_default(self):
- tmpl = env.from_string(
- "{{ missing|default('no') }}|{{ false|default('no') }}|"
- "{{ false|default('no', true) }}|{{ given|default('no') }}"
- )
- assert tmpl.render(given='yes') == 'no|False|no|yes'
-
- def test_dictsort(self):
- tmpl = env.from_string(
- '{{ foo|dictsort }}|'
- '{{ foo|dictsort(true) }}|'
- '{{ foo|dictsort(false, "value") }}'
- )
- out = tmpl.render(foo={"aa": 0, "b": 1, "c": 2, "AB": 3})
- assert out == ("[('aa', 0), ('AB', 3), ('b', 1), ('c', 2)]|"
- "[('AB', 3), ('aa', 0), ('b', 1), ('c', 2)]|"
- "[('aa', 0), ('b', 1), ('c', 2), ('AB', 3)]")
-
- def test_batch(self):
- tmpl = env.from_string("{{ foo|batch(3)|list }}|"
- "{{ foo|batch(3, 'X')|list }}")
- out = tmpl.render(foo=list(range(10)))
- assert out == ("[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]|"
- "[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 'X', 'X']]")
-
- def test_slice(self):
- tmpl = env.from_string('{{ foo|slice(3)|list }}|'
- '{{ foo|slice(3, "X")|list }}')
- out = tmpl.render(foo=list(range(10)))
- assert out == ("[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"
- "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]")
-
- def test_escape(self):
- tmpl = env.from_string('''{{ '<">&'|escape }}''')
- out = tmpl.render()
- assert out == '<">&'
-
- def test_striptags(self):
- tmpl = env.from_string('''{{ foo|striptags }}''')
- out = tmpl.render(foo=' just a small \n '
- 'example link
\nto a webpage
'
- '')
- assert out == 'just a small example link to a webpage'
-
- def test_filesizeformat(self):
- tmpl = env.from_string(
- '{{ 100|filesizeformat }}|'
- '{{ 1000|filesizeformat }}|'
- '{{ 1000000|filesizeformat }}|'
- '{{ 1000000000|filesizeformat }}|'
- '{{ 1000000000000|filesizeformat }}|'
- '{{ 100|filesizeformat(true) }}|'
- '{{ 1000|filesizeformat(true) }}|'
- '{{ 1000000|filesizeformat(true) }}|'
- '{{ 1000000000|filesizeformat(true) }}|'
- '{{ 1000000000000|filesizeformat(true) }}'
- )
- out = tmpl.render()
- self.assert_equal(out, (
- '100 Bytes|1.0 kB|1.0 MB|1.0 GB|1.0 TB|100 Bytes|'
- '1000 Bytes|976.6 KiB|953.7 MiB|931.3 GiB'
- ))
-
- def test_filesizeformat_issue59(self):
- tmpl = env.from_string(
- '{{ 300|filesizeformat }}|'
- '{{ 3000|filesizeformat }}|'
- '{{ 3000000|filesizeformat }}|'
- '{{ 3000000000|filesizeformat }}|'
- '{{ 3000000000000|filesizeformat }}|'
- '{{ 300|filesizeformat(true) }}|'
- '{{ 3000|filesizeformat(true) }}|'
- '{{ 3000000|filesizeformat(true) }}'
- )
- out = tmpl.render()
- self.assert_equal(out, (
- '300 Bytes|3.0 kB|3.0 MB|3.0 GB|3.0 TB|300 Bytes|'
- '2.9 KiB|2.9 MiB'
- ))
-
-
- def test_first(self):
- tmpl = env.from_string('{{ foo|first }}')
- out = tmpl.render(foo=list(range(10)))
- assert out == '0'
-
- def test_float(self):
- tmpl = env.from_string('{{ "42"|float }}|'
- '{{ "ajsghasjgd"|float }}|'
- '{{ "32.32"|float }}')
- out = tmpl.render()
- assert out == '42.0|0.0|32.32'
-
- def test_format(self):
- tmpl = env.from_string('''{{ "%s|%s"|format("a", "b") }}''')
- out = tmpl.render()
- assert out == 'a|b'
-
- def test_indent(self):
- tmpl = env.from_string('{{ foo|indent(2) }}|{{ foo|indent(2, true) }}')
- text = '\n'.join([' '.join(['foo', 'bar'] * 2)] * 2)
- out = tmpl.render(foo=text)
- assert out == ('foo bar foo bar\n foo bar foo bar| '
- 'foo bar foo bar\n foo bar foo bar')
-
- def test_int(self):
- tmpl = env.from_string('{{ "42"|int }}|{{ "ajsghasjgd"|int }}|'
- '{{ "32.32"|int }}')
- out = tmpl.render()
- assert out == '42|0|32'
-
- def test_join(self):
- tmpl = env.from_string('{{ [1, 2, 3]|join("|") }}')
- out = tmpl.render()
- assert out == '1|2|3'
-
- env2 = Environment(autoescape=True)
- tmpl = env2.from_string('{{ ["", "foo"|safe]|join }}')
- assert tmpl.render() == '<foo>foo'
-
- def test_join_attribute(self):
- class User(object):
- def __init__(self, username):
- self.username = username
- tmpl = env.from_string('''{{ users|join(', ', 'username') }}''')
- assert tmpl.render(users=map(User, ['foo', 'bar'])) == 'foo, bar'
-
- def test_last(self):
- tmpl = env.from_string('''{{ foo|last }}''')
- out = tmpl.render(foo=list(range(10)))
- assert out == '9'
-
- def test_length(self):
- tmpl = env.from_string('''{{ "hello world"|length }}''')
- out = tmpl.render()
- assert out == '11'
-
- def test_lower(self):
- tmpl = env.from_string('''{{ "FOO"|lower }}''')
- out = tmpl.render()
- assert out == 'foo'
-
- def test_pprint(self):
- from pprint import pformat
- tmpl = env.from_string('''{{ data|pprint }}''')
- data = list(range(1000))
- assert tmpl.render(data=data) == pformat(data)
-
- def test_random(self):
- tmpl = env.from_string('''{{ seq|random }}''')
- seq = list(range(100))
- for _ in range(10):
- assert int(tmpl.render(seq=seq)) in seq
-
- def test_reverse(self):
- tmpl = env.from_string('{{ "foobar"|reverse|join }}|'
- '{{ [1, 2, 3]|reverse|list }}')
- assert tmpl.render() == 'raboof|[3, 2, 1]'
-
- def test_string(self):
- x = [1, 2, 3, 4, 5]
- tmpl = env.from_string('''{{ obj|string }}''')
- assert tmpl.render(obj=x) == text_type(x)
-
- def test_title(self):
- tmpl = env.from_string('''{{ "foo bar"|title }}''')
- assert tmpl.render() == "Foo Bar"
- tmpl = env.from_string('''{{ "foo's bar"|title }}''')
- assert tmpl.render() == "Foo's Bar"
- tmpl = env.from_string('''{{ "foo bar"|title }}''')
- assert tmpl.render() == "Foo Bar"
- tmpl = env.from_string('''{{ "f bar f"|title }}''')
- assert tmpl.render() == "F Bar F"
- tmpl = env.from_string('''{{ "foo-bar"|title }}''')
- assert tmpl.render() == "Foo-Bar"
- tmpl = env.from_string('''{{ "foo\tbar"|title }}''')
- assert tmpl.render() == "Foo\tBar"
- tmpl = env.from_string('''{{ "FOO\tBAR"|title }}''')
- assert tmpl.render() == "Foo\tBar"
-
- def test_truncate(self):
- tmpl = env.from_string(
- '{{ data|truncate(15, true, ">>>") }}|'
- '{{ data|truncate(15, false, ">>>") }}|'
- '{{ smalldata|truncate(15) }}'
- )
- out = tmpl.render(data='foobar baz bar' * 1000,
- smalldata='foobar baz bar')
- assert out == 'foobar baz barf>>>|foobar baz >>>|foobar baz bar'
-
- def test_upper(self):
- tmpl = env.from_string('{{ "foo"|upper }}')
- assert tmpl.render() == 'FOO'
-
- def test_urlize(self):
- tmpl = env.from_string('{{ "foo http://www.example.com/ bar"|urlize }}')
- assert tmpl.render() == 'foo '\
- 'http://www.example.com/ bar'
-
- def test_wordcount(self):
- tmpl = env.from_string('{{ "foo bar baz"|wordcount }}')
- assert tmpl.render() == '3'
-
- def test_block(self):
- tmpl = env.from_string('{% filter lower|escape %}{% endfilter %}')
- assert tmpl.render() == '<hehe>'
-
- def test_chaining(self):
- tmpl = env.from_string('''{{ ['', '']|first|upper|escape }}''')
- assert tmpl.render() == '<FOO>'
-
- def test_sum(self):
- tmpl = env.from_string('''{{ [1, 2, 3, 4, 5, 6]|sum }}''')
- assert tmpl.render() == '21'
-
- def test_sum_attributes(self):
- tmpl = env.from_string('''{{ values|sum('value') }}''')
- assert tmpl.render(values=[
- {'value': 23},
- {'value': 1},
- {'value': 18},
- ]) == '42'
-
- def test_sum_attributes_nested(self):
- tmpl = env.from_string('''{{ values|sum('real.value') }}''')
- assert tmpl.render(values=[
- {'real': {'value': 23}},
- {'real': {'value': 1}},
- {'real': {'value': 18}},
- ]) == '42'
-
- def test_sum_attributes_tuple(self):
- tmpl = env.from_string('''{{ values.items()|sum('1') }}''')
- assert tmpl.render(values={
- 'foo': 23,
- 'bar': 1,
- 'baz': 18,
- }) == '42'
-
- def test_abs(self):
- tmpl = env.from_string('''{{ -1|abs }}|{{ 1|abs }}''')
- assert tmpl.render() == '1|1', tmpl.render()
-
- def test_round_positive(self):
- tmpl = env.from_string('{{ 2.7|round }}|{{ 2.1|round }}|'
- "{{ 2.1234|round(3, 'floor') }}|"
- "{{ 2.1|round(0, 'ceil') }}")
- assert tmpl.render() == '3.0|2.0|2.123|3.0', tmpl.render()
-
- def test_round_negative(self):
- tmpl = env.from_string('{{ 21.3|round(-1)}}|'
- "{{ 21.3|round(-1, 'ceil')}}|"
- "{{ 21.3|round(-1, 'floor')}}")
- assert tmpl.render() == '20.0|30.0|20.0',tmpl.render()
-
- def test_xmlattr(self):
- tmpl = env.from_string("{{ {'foo': 42, 'bar': 23, 'fish': none, "
- "'spam': missing, 'blub:blub': '>'}|xmlattr }}")
- out = tmpl.render().split()
- assert len(out) == 3
- assert 'foo="42"' in out
- assert 'bar="23"' in out
- assert 'blub:blub="<?>"' in out
-
- def test_sort1(self):
- tmpl = env.from_string('{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}')
- assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'
-
- def test_sort2(self):
- tmpl = env.from_string('{{ "".join(["c", "A", "b", "D"]|sort) }}')
- assert tmpl.render() == 'AbcD'
-
- def test_sort3(self):
- tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')
- assert tmpl.render() == "['Bar', 'blah', 'foo']"
-
- def test_sort4(self):
- @implements_to_string
- class Magic(object):
- def __init__(self, value):
- self.value = value
- def __str__(self):
- return text_type(self.value)
- tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')
- assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'
-
- def test_groupby(self):
- tmpl = env.from_string('''
- {%- for grouper, list in [{'foo': 1, 'bar': 2},
- {'foo': 2, 'bar': 3},
- {'foo': 1, 'bar': 1},
- {'foo': 3, 'bar': 4}]|groupby('foo') -%}
- {{ grouper }}{% for x in list %}: {{ x.foo }}, {{ x.bar }}{% endfor %}|
- {%- endfor %}''')
- assert tmpl.render().split('|') == [
- "1: 1, 2: 1, 1",
- "2: 2, 3",
- "3: 3, 4",
- ""
- ]
-
- def test_groupby_tuple_index(self):
- tmpl = env.from_string('''
- {%- for grouper, list in [('a', 1), ('a', 2), ('b', 1)]|groupby(0) -%}
- {{ grouper }}{% for x in list %}:{{ x.1 }}{% endfor %}|
- {%- endfor %}''')
- assert tmpl.render() == 'a:1:2|b:1|'
-
- def test_groupby_multidot(self):
- class Date(object):
- def __init__(self, day, month, year):
- self.day = day
- self.month = month
- self.year = year
- class Article(object):
- def __init__(self, title, *date):
- self.date = Date(*date)
- self.title = title
- articles = [
- Article('aha', 1, 1, 1970),
- Article('interesting', 2, 1, 1970),
- Article('really?', 3, 1, 1970),
- Article('totally not', 1, 1, 1971)
- ]
- tmpl = env.from_string('''
- {%- for year, list in articles|groupby('date.year') -%}
- {{ year }}{% for x in list %}[{{ x.title }}]{% endfor %}|
- {%- endfor %}''')
- assert tmpl.render(articles=articles).split('|') == [
- '1970[aha][interesting][really?]',
- '1971[totally not]',
- ''
- ]
-
- def test_filtertag(self):
- tmpl = env.from_string("{% filter upper|replace('FOO', 'foo') %}"
- "foobar{% endfilter %}")
- assert tmpl.render() == 'fooBAR'
-
- def test_replace(self):
- env = Environment()
- tmpl = env.from_string('{{ string|replace("o", 42) }}')
- assert tmpl.render(string='') == ''
- env = Environment(autoescape=True)
- tmpl = env.from_string('{{ string|replace("o", 42) }}')
- assert tmpl.render(string='') == '<f4242>'
- tmpl = env.from_string('{{ string|replace("<", 42) }}')
- assert tmpl.render(string='') == '42foo>'
- tmpl = env.from_string('{{ string|replace("o", ">x<") }}')
- assert tmpl.render(string=Markup('foo')) == 'f>x<>x<'
-
- def test_forceescape(self):
- tmpl = env.from_string('{{ x|forceescape }}')
- assert tmpl.render(x=Markup('')) == u'<div />'
-
- def test_safe(self):
- env = Environment(autoescape=True)
- tmpl = env.from_string('{{ "foo
"|safe }}')
- assert tmpl.render() == 'foo
'
- tmpl = env.from_string('{{ "foo
" }}')
- assert tmpl.render() == '<div>foo</div>'
-
- def test_urlencode(self):
- env = Environment(autoescape=True)
- tmpl = env.from_string('{{ "Hello, world!"|urlencode }}')
- assert tmpl.render() == 'Hello%2C%20world%21'
- tmpl = env.from_string('{{ o|urlencode }}')
- assert tmpl.render(o=u"Hello, world\u203d") == "Hello%2C%20world%E2%80%BD"
- assert tmpl.render(o=(("f", 1),)) == "f=1"
- assert tmpl.render(o=(('f', 1), ("z", 2))) == "f=1&z=2"
- assert tmpl.render(o=((u"\u203d", 1),)) == "%E2%80%BD=1"
- assert tmpl.render(o={u"\u203d": 1}) == "%E2%80%BD=1"
- assert tmpl.render(o={0: 1}) == "0=1"
-
- def test_simple_map(self):
- env = Environment()
- tmpl = env.from_string('{{ ["1", "2", "3"]|map("int")|sum }}')
- self.assertEqual(tmpl.render(), '6')
-
- def test_attribute_map(self):
- class User(object):
- def __init__(self, name):
- self.name = name
- env = Environment()
- users = [
- User('john'),
- User('jane'),
- User('mike'),
- ]
- tmpl = env.from_string('{{ users|map(attribute="name")|join("|") }}')
- self.assertEqual(tmpl.render(users=users), 'john|jane|mike')
-
- def test_empty_map(self):
- env = Environment()
- tmpl = env.from_string('{{ none|map("upper")|list }}')
- self.assertEqual(tmpl.render(), '[]')
-
- def test_simple_select(self):
- env = Environment()
- tmpl = env.from_string('{{ [1, 2, 3, 4, 5]|select("odd")|join("|") }}')
- self.assertEqual(tmpl.render(), '1|3|5')
-
- def test_bool_select(self):
- env = Environment()
- tmpl = env.from_string('{{ [none, false, 0, 1, 2, 3, 4, 5]|select|join("|") }}')
- self.assertEqual(tmpl.render(), '1|2|3|4|5')
-
- def test_simple_reject(self):
- env = Environment()
- tmpl = env.from_string('{{ [1, 2, 3, 4, 5]|reject("odd")|join("|") }}')
- self.assertEqual(tmpl.render(), '2|4')
-
- def test_bool_reject(self):
- env = Environment()
- tmpl = env.from_string('{{ [none, false, 0, 1, 2, 3, 4, 5]|reject|join("|") }}')
- self.assertEqual(tmpl.render(), 'None|False|0')
-
- def test_simple_select_attr(self):
- class User(object):
- def __init__(self, name, is_active):
- self.name = name
- self.is_active = is_active
- env = Environment()
- users = [
- User('john', True),
- User('jane', True),
- User('mike', False),
- ]
- tmpl = env.from_string('{{ users|selectattr("is_active")|'
- 'map(attribute="name")|join("|") }}')
- self.assertEqual(tmpl.render(users=users), 'john|jane')
-
- def test_simple_reject_attr(self):
- class User(object):
- def __init__(self, name, is_active):
- self.name = name
- self.is_active = is_active
- env = Environment()
- users = [
- User('john', True),
- User('jane', True),
- User('mike', False),
- ]
- tmpl = env.from_string('{{ users|rejectattr("is_active")|'
- 'map(attribute="name")|join("|") }}')
- self.assertEqual(tmpl.render(users=users), 'mike')
-
- def test_func_select_attr(self):
- class User(object):
- def __init__(self, id, name):
- self.id = id
- self.name = name
- env = Environment()
- users = [
- User(1, 'john'),
- User(2, 'jane'),
- User(3, 'mike'),
- ]
- tmpl = env.from_string('{{ users|selectattr("id", "odd")|'
- 'map(attribute="name")|join("|") }}')
- self.assertEqual(tmpl.render(users=users), 'john|mike')
-
- def test_func_reject_attr(self):
- class User(object):
- def __init__(self, id, name):
- self.id = id
- self.name = name
- env = Environment()
- users = [
- User(1, 'john'),
- User(2, 'jane'),
- User(3, 'mike'),
- ]
- tmpl = env.from_string('{{ users|rejectattr("id", "odd")|'
- 'map(attribute="name")|join("|") }}')
- self.assertEqual(tmpl.render(users=users), 'jane')
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(FilterTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/imports.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/imports.py
deleted file mode 100644
index 3db9008..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/imports.py
+++ /dev/null
@@ -1,141 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.imports
- ~~~~~~~~~~~~~~~~~~~~~~~~
-
- Tests the import features (with includes).
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Environment, DictLoader
-from jinja2.exceptions import TemplateNotFound, TemplatesNotFound
-
-
-test_env = Environment(loader=DictLoader(dict(
- module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',
- header='[{{ foo }}|{{ 23 }}]',
- o_printer='({{ o }})'
-)))
-test_env.globals['bar'] = 23
-
-
-class ImportsTestCase(JinjaTestCase):
-
- def test_context_imports(self):
- t = test_env.from_string('{% import "module" as m %}{{ m.test() }}')
- assert t.render(foo=42) == '[|23]'
- t = test_env.from_string('{% import "module" as m without context %}{{ m.test() }}')
- assert t.render(foo=42) == '[|23]'
- t = test_env.from_string('{% import "module" as m with context %}{{ m.test() }}')
- assert t.render(foo=42) == '[42|23]'
- t = test_env.from_string('{% from "module" import test %}{{ test() }}')
- assert t.render(foo=42) == '[|23]'
- t = test_env.from_string('{% from "module" import test without context %}{{ test() }}')
- assert t.render(foo=42) == '[|23]'
- t = test_env.from_string('{% from "module" import test with context %}{{ test() }}')
- assert t.render(foo=42) == '[42|23]'
-
- def test_trailing_comma(self):
- test_env.from_string('{% from "foo" import bar, baz with context %}')
- test_env.from_string('{% from "foo" import bar, baz, with context %}')
- test_env.from_string('{% from "foo" import bar, with context %}')
- test_env.from_string('{% from "foo" import bar, with, context %}')
- test_env.from_string('{% from "foo" import bar, with with context %}')
-
- def test_exports(self):
- m = test_env.from_string('''
- {% macro toplevel() %}...{% endmacro %}
- {% macro __private() %}...{% endmacro %}
- {% set variable = 42 %}
- {% for item in [1] %}
- {% macro notthere() %}{% endmacro %}
- {% endfor %}
- ''').module
- assert m.toplevel() == '...'
- assert not hasattr(m, '__missing')
- assert m.variable == 42
- assert not hasattr(m, 'notthere')
-
-
-class IncludesTestCase(JinjaTestCase):
-
- def test_context_include(self):
- t = test_env.from_string('{% include "header" %}')
- assert t.render(foo=42) == '[42|23]'
- t = test_env.from_string('{% include "header" with context %}')
- assert t.render(foo=42) == '[42|23]'
- t = test_env.from_string('{% include "header" without context %}')
- assert t.render(foo=42) == '[|23]'
-
- def test_choice_includes(self):
- t = test_env.from_string('{% include ["missing", "header"] %}')
- assert t.render(foo=42) == '[42|23]'
-
- t = test_env.from_string('{% include ["missing", "missing2"] ignore missing %}')
- assert t.render(foo=42) == ''
-
- t = test_env.from_string('{% include ["missing", "missing2"] %}')
- self.assert_raises(TemplateNotFound, t.render)
- try:
- t.render()
- except TemplatesNotFound as e:
- assert e.templates == ['missing', 'missing2']
- assert e.name == 'missing2'
- else:
- assert False, 'thou shalt raise'
-
- def test_includes(t, **ctx):
- ctx['foo'] = 42
- assert t.render(ctx) == '[42|23]'
-
- t = test_env.from_string('{% include ["missing", "header"] %}')
- test_includes(t)
- t = test_env.from_string('{% include x %}')
- test_includes(t, x=['missing', 'header'])
- t = test_env.from_string('{% include [x, "header"] %}')
- test_includes(t, x='missing')
- t = test_env.from_string('{% include x %}')
- test_includes(t, x='header')
- t = test_env.from_string('{% include x %}')
- test_includes(t, x='header')
- t = test_env.from_string('{% include [x] %}')
- test_includes(t, x='header')
-
- def test_include_ignoring_missing(self):
- t = test_env.from_string('{% include "missing" %}')
- self.assert_raises(TemplateNotFound, t.render)
- for extra in '', 'with context', 'without context':
- t = test_env.from_string('{% include "missing" ignore missing ' +
- extra + ' %}')
- assert t.render() == ''
-
- def test_context_include_with_overrides(self):
- env = Environment(loader=DictLoader(dict(
- main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",
- item="{{ item }}"
- )))
- assert env.get_template("main").render() == "123"
-
- def test_unoptimized_scopes(self):
- t = test_env.from_string("""
- {% macro outer(o) %}
- {% macro inner() %}
- {% include "o_printer" %}
- {% endmacro %}
- {{ inner() }}
- {% endmacro %}
- {{ outer("FOO") }}
- """)
- assert t.render().strip() == '(FOO)'
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(ImportsTestCase))
- suite.addTest(unittest.makeSuite(IncludesTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/inheritance.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/inheritance.py
deleted file mode 100644
index e0f51cd..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/inheritance.py
+++ /dev/null
@@ -1,250 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.inheritance
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Tests the template inheritance feature.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Environment, DictLoader, TemplateError
-
-
-LAYOUTTEMPLATE = '''\
-|{% block block1 %}block 1 from layout{% endblock %}
-|{% block block2 %}block 2 from layout{% endblock %}
-|{% block block3 %}
-{% block block4 %}nested block 4 from layout{% endblock %}
-{% endblock %}|'''
-
-LEVEL1TEMPLATE = '''\
-{% extends "layout" %}
-{% block block1 %}block 1 from level1{% endblock %}'''
-
-LEVEL2TEMPLATE = '''\
-{% extends "level1" %}
-{% block block2 %}{% block block5 %}nested block 5 from level2{%
-endblock %}{% endblock %}'''
-
-LEVEL3TEMPLATE = '''\
-{% extends "level2" %}
-{% block block5 %}block 5 from level3{% endblock %}
-{% block block4 %}block 4 from level3{% endblock %}
-'''
-
-LEVEL4TEMPLATE = '''\
-{% extends "level3" %}
-{% block block3 %}block 3 from level4{% endblock %}
-'''
-
-WORKINGTEMPLATE = '''\
-{% extends "layout" %}
-{% block block1 %}
- {% if false %}
- {% block block2 %}
- this should workd
- {% endblock %}
- {% endif %}
-{% endblock %}
-'''
-
-DOUBLEEXTENDS = '''\
-{% extends "layout" %}
-{% extends "layout" %}
-{% block block1 %}
- {% if false %}
- {% block block2 %}
- this should workd
- {% endblock %}
- {% endif %}
-{% endblock %}
-'''
-
-
-env = Environment(loader=DictLoader({
- 'layout': LAYOUTTEMPLATE,
- 'level1': LEVEL1TEMPLATE,
- 'level2': LEVEL2TEMPLATE,
- 'level3': LEVEL3TEMPLATE,
- 'level4': LEVEL4TEMPLATE,
- 'working': WORKINGTEMPLATE,
- 'doublee': DOUBLEEXTENDS,
-}), trim_blocks=True)
-
-
-class InheritanceTestCase(JinjaTestCase):
-
- def test_layout(self):
- tmpl = env.get_template('layout')
- assert tmpl.render() == ('|block 1 from layout|block 2 from '
- 'layout|nested block 4 from layout|')
-
- def test_level1(self):
- tmpl = env.get_template('level1')
- assert tmpl.render() == ('|block 1 from level1|block 2 from '
- 'layout|nested block 4 from layout|')
-
- def test_level2(self):
- tmpl = env.get_template('level2')
- assert tmpl.render() == ('|block 1 from level1|nested block 5 from '
- 'level2|nested block 4 from layout|')
-
- def test_level3(self):
- tmpl = env.get_template('level3')
- assert tmpl.render() == ('|block 1 from level1|block 5 from level3|'
- 'block 4 from level3|')
-
- def test_level4(sel):
- tmpl = env.get_template('level4')
- assert tmpl.render() == ('|block 1 from level1|block 5 from '
- 'level3|block 3 from level4|')
-
- def test_super(self):
- env = Environment(loader=DictLoader({
- 'a': '{% block intro %}INTRO{% endblock %}|'
- 'BEFORE|{% block data %}INNER{% endblock %}|AFTER',
- 'b': '{% extends "a" %}{% block data %}({{ '
- 'super() }}){% endblock %}',
- 'c': '{% extends "b" %}{% block intro %}--{{ '
- 'super() }}--{% endblock %}\n{% block data '
- '%}[{{ super() }}]{% endblock %}'
- }))
- tmpl = env.get_template('c')
- assert tmpl.render() == '--INTRO--|BEFORE|[(INNER)]|AFTER'
-
- def test_working(self):
- tmpl = env.get_template('working')
-
- def test_reuse_blocks(self):
- tmpl = env.from_string('{{ self.foo() }}|{% block foo %}42'
- '{% endblock %}|{{ self.foo() }}')
- assert tmpl.render() == '42|42|42'
-
- def test_preserve_blocks(self):
- env = Environment(loader=DictLoader({
- 'a': '{% if false %}{% block x %}A{% endblock %}{% endif %}{{ self.x() }}',
- 'b': '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}'
- }))
- tmpl = env.get_template('b')
- assert tmpl.render() == 'BA'
-
- def test_dynamic_inheritance(self):
- env = Environment(loader=DictLoader({
- 'master1': 'MASTER1{% block x %}{% endblock %}',
- 'master2': 'MASTER2{% block x %}{% endblock %}',
- 'child': '{% extends master %}{% block x %}CHILD{% endblock %}'
- }))
- tmpl = env.get_template('child')
- for m in range(1, 3):
- assert tmpl.render(master='master%d' % m) == 'MASTER%dCHILD' % m
-
- def test_multi_inheritance(self):
- env = Environment(loader=DictLoader({
- 'master1': 'MASTER1{% block x %}{% endblock %}',
- 'master2': 'MASTER2{% block x %}{% endblock %}',
- 'child': '''{% if master %}{% extends master %}{% else %}{% extends
- 'master1' %}{% endif %}{% block x %}CHILD{% endblock %}'''
- }))
- tmpl = env.get_template('child')
- assert tmpl.render(master='master2') == 'MASTER2CHILD'
- assert tmpl.render(master='master1') == 'MASTER1CHILD'
- assert tmpl.render() == 'MASTER1CHILD'
-
- def test_scoped_block(self):
- env = Environment(loader=DictLoader({
- 'master.html': '{% for item in seq %}[{% block item scoped %}'
- '{% endblock %}]{% endfor %}'
- }))
- t = env.from_string('{% extends "master.html" %}{% block item %}'
- '{{ item }}{% endblock %}')
- assert t.render(seq=list(range(5))) == '[0][1][2][3][4]'
-
- def test_super_in_scoped_block(self):
- env = Environment(loader=DictLoader({
- 'master.html': '{% for item in seq %}[{% block item scoped %}'
- '{{ item }}{% endblock %}]{% endfor %}'
- }))
- t = env.from_string('{% extends "master.html" %}{% block item %}'
- '{{ super() }}|{{ item * 2 }}{% endblock %}')
- assert t.render(seq=list(range(5))) == '[0|0][1|2][2|4][3|6][4|8]'
-
- def test_scoped_block_after_inheritance(self):
- env = Environment(loader=DictLoader({
- 'layout.html': '''
- {% block useless %}{% endblock %}
- ''',
- 'index.html': '''
- {%- extends 'layout.html' %}
- {% from 'helpers.html' import foo with context %}
- {% block useless %}
- {% for x in [1, 2, 3] %}
- {% block testing scoped %}
- {{ foo(x) }}
- {% endblock %}
- {% endfor %}
- {% endblock %}
- ''',
- 'helpers.html': '''
- {% macro foo(x) %}{{ the_foo + x }}{% endmacro %}
- '''
- }))
- rv = env.get_template('index.html').render(the_foo=42).split()
- assert rv == ['43', '44', '45']
-
-
-class BugFixTestCase(JinjaTestCase):
-
- def test_fixed_macro_scoping_bug(self):
- assert Environment(loader=DictLoader({
- 'test.html': '''\
- {% extends 'details.html' %}
-
- {% macro my_macro() %}
- my_macro
- {% endmacro %}
-
- {% block inner_box %}
- {{ my_macro() }}
- {% endblock %}
- ''',
- 'details.html': '''\
- {% extends 'standard.html' %}
-
- {% macro my_macro() %}
- my_macro
- {% endmacro %}
-
- {% block content %}
- {% block outer_box %}
- outer_box
- {% block inner_box %}
- inner_box
- {% endblock %}
- {% endblock %}
- {% endblock %}
- ''',
- 'standard.html': '''
- {% block content %} {% endblock %}
- '''
- })).get_template("test.html").render().split() == [u'outer_box', u'my_macro']
-
- def test_double_extends(self):
- """Ensures that a template with more than 1 {% extends ... %} usage
- raises a ``TemplateError``.
- """
- try:
- tmpl = env.get_template('doublee')
- except Exception as e:
- assert isinstance(e, TemplateError)
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(InheritanceTestCase))
- suite.addTest(unittest.makeSuite(BugFixTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/lexnparse.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/lexnparse.py
deleted file mode 100644
index bd1c94c..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/lexnparse.py
+++ /dev/null
@@ -1,593 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.lexnparse
- ~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- All the unittests regarding lexing, parsing and syntax.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Environment, Template, TemplateSyntaxError, \
- UndefinedError, nodes
-from jinja2._compat import next, iteritems, text_type, PY2
-from jinja2.lexer import Token, TokenStream, TOKEN_EOF, \
- TOKEN_BLOCK_BEGIN, TOKEN_BLOCK_END
-
-env = Environment()
-
-
-# how does a string look like in jinja syntax?
-if PY2:
- def jinja_string_repr(string):
- return repr(string)[1:]
-else:
- jinja_string_repr = repr
-
-
-class TokenStreamTestCase(JinjaTestCase):
- test_tokens = [Token(1, TOKEN_BLOCK_BEGIN, ''),
- Token(2, TOKEN_BLOCK_END, ''),
- ]
-
- def test_simple(self):
- ts = TokenStream(self.test_tokens, "foo", "bar")
- assert ts.current.type is TOKEN_BLOCK_BEGIN
- assert bool(ts)
- assert not bool(ts.eos)
- next(ts)
- assert ts.current.type is TOKEN_BLOCK_END
- assert bool(ts)
- assert not bool(ts.eos)
- next(ts)
- assert ts.current.type is TOKEN_EOF
- assert not bool(ts)
- assert bool(ts.eos)
-
- def test_iter(self):
- token_types = [t.type for t in TokenStream(self.test_tokens, "foo", "bar")]
- assert token_types == ['block_begin', 'block_end', ]
-
-
-class LexerTestCase(JinjaTestCase):
-
- def test_raw1(self):
- tmpl = env.from_string('{% raw %}foo{% endraw %}|'
- '{%raw%}{{ bar }}|{% baz %}{% endraw %}')
- assert tmpl.render() == 'foo|{{ bar }}|{% baz %}'
-
- def test_raw2(self):
- tmpl = env.from_string('1 {%- raw -%} 2 {%- endraw -%} 3')
- assert tmpl.render() == '123'
-
- def test_balancing(self):
- env = Environment('{%', '%}', '${', '}')
- tmpl = env.from_string('''{% for item in seq
- %}${{'foo': item}|upper}{% endfor %}''')
- assert tmpl.render(seq=list(range(3))) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"
-
- def test_comments(self):
- env = Environment('', '{', '}')
- tmpl = env.from_string('''\
-''')
- assert tmpl.render(seq=list(range(3))) == ("")
-
- def test_string_escapes(self):
- for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n':
- tmpl = env.from_string('{{ %s }}' % jinja_string_repr(char))
- assert tmpl.render() == char
- assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u'\u2668'
-
- def test_bytefallback(self):
- from pprint import pformat
- tmpl = env.from_string(u'''{{ 'foo'|pprint }}|{{ 'bär'|pprint }}''')
- assert tmpl.render() == pformat('foo') + '|' + pformat(u'bär')
-
- def test_operators(self):
- from jinja2.lexer import operators
- for test, expect in iteritems(operators):
- if test in '([{}])':
- continue
- stream = env.lexer.tokenize('{{ %s }}' % test)
- next(stream)
- assert stream.current.type == expect
-
- def test_normalizing(self):
- for seq in '\r', '\r\n', '\n':
- env = Environment(newline_sequence=seq)
- tmpl = env.from_string('1\n2\r\n3\n4\n')
- result = tmpl.render()
- assert result.replace(seq, 'X') == '1X2X3X4'
-
- def test_trailing_newline(self):
- for keep in [True, False]:
- env = Environment(keep_trailing_newline=keep)
- for template,expected in [
- ('', {}),
- ('no\nnewline', {}),
- ('with\nnewline\n', {False: 'with\nnewline'}),
- ('with\nseveral\n\n\n', {False: 'with\nseveral\n\n'}),
- ]:
- tmpl = env.from_string(template)
- expect = expected.get(keep, template)
- result = tmpl.render()
- assert result == expect, (keep, template, result, expect)
-
-class ParserTestCase(JinjaTestCase):
-
- def test_php_syntax(self):
- env = Environment('', '?>', '=', '?>', '')
- tmpl = env.from_string('''\
-\
- for item in seq -?>
- = item ?>
-- endfor ?>''')
- assert tmpl.render(seq=list(range(5))) == '01234'
-
- def test_erb_syntax(self):
- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')
- tmpl = env.from_string('''\
-<%# I'm a comment, I'm not interesting %>\
-<% for item in seq -%>
- <%= item %>
-<%- endfor %>''')
- assert tmpl.render(seq=list(range(5))) == '01234'
-
- def test_comment_syntax(self):
- env = Environment('', '${', '}', '')
- tmpl = env.from_string('''\
-\
-
- ${item}
-''')
- assert tmpl.render(seq=list(range(5))) == '01234'
-
- def test_balancing(self):
- tmpl = env.from_string('''{{{'foo':'bar'}.foo}}''')
- assert tmpl.render() == 'bar'
-
- def test_start_comment(self):
- tmpl = env.from_string('''{# foo comment
-and bar comment #}
-{% macro blub() %}foo{% endmacro %}
-{{ blub() }}''')
- assert tmpl.render().strip() == 'foo'
-
- def test_line_syntax(self):
- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%')
- tmpl = env.from_string('''\
-<%# regular comment %>
-% for item in seq:
- ${item}
-% endfor''')
- assert [int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()] == \
- list(range(5))
-
- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##')
- tmpl = env.from_string('''\
-<%# regular comment %>
-% for item in seq:
- ${item} ## the rest of the stuff
-% endfor''')
- assert [int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()] == \
- list(range(5))
-
- def test_line_syntax_priority(self):
- # XXX: why is the whitespace there in front of the newline?
- env = Environment('{%', '%}', '${', '}', '/*', '*/', '##', '#')
- tmpl = env.from_string('''\
-/* ignore me.
- I'm a multiline comment */
-## for item in seq:
-* ${item} # this is just extra stuff
-## endfor''')
- assert tmpl.render(seq=[1, 2]).strip() == '* 1\n* 2'
- env = Environment('{%', '%}', '${', '}', '/*', '*/', '#', '##')
- tmpl = env.from_string('''\
-/* ignore me.
- I'm a multiline comment */
-# for item in seq:
-* ${item} ## this is just extra stuff
- ## extra stuff i just want to ignore
-# endfor''')
- assert tmpl.render(seq=[1, 2]).strip() == '* 1\n\n* 2'
-
- def test_error_messages(self):
- def assert_error(code, expected):
- try:
- Template(code)
- except TemplateSyntaxError as e:
- assert str(e) == expected, 'unexpected error message'
- else:
- assert False, 'that was supposed to be an error'
-
- assert_error('{% for item in seq %}...{% endif %}',
- "Encountered unknown tag 'endif'. Jinja was looking "
- "for the following tags: 'endfor' or 'else'. The "
- "innermost block that needs to be closed is 'for'.")
- assert_error('{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}',
- "Encountered unknown tag 'endfor'. Jinja was looking for "
- "the following tags: 'elif' or 'else' or 'endif'. The "
- "innermost block that needs to be closed is 'if'.")
- assert_error('{% if foo %}',
- "Unexpected end of template. Jinja was looking for the "
- "following tags: 'elif' or 'else' or 'endif'. The "
- "innermost block that needs to be closed is 'if'.")
- assert_error('{% for item in seq %}',
- "Unexpected end of template. Jinja was looking for the "
- "following tags: 'endfor' or 'else'. The innermost block "
- "that needs to be closed is 'for'.")
- assert_error('{% block foo-bar-baz %}',
- "Block names in Jinja have to be valid Python identifiers "
- "and may not contain hyphens, use an underscore instead.")
- assert_error('{% unknown_tag %}',
- "Encountered unknown tag 'unknown_tag'.")
-
-
-class SyntaxTestCase(JinjaTestCase):
-
- def test_call(self):
- env = Environment()
- env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g
- tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}")
- assert tmpl.render() == 'abdfh'
-
- def test_slicing(self):
- tmpl = env.from_string('{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}')
- assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'
-
- def test_attr(self):
- tmpl = env.from_string("{{ foo.bar }}|{{ foo['bar'] }}")
- assert tmpl.render(foo={'bar': 42}) == '42|42'
-
- def test_subscript(self):
- tmpl = env.from_string("{{ foo[0] }}|{{ foo[-1] }}")
- assert tmpl.render(foo=[0, 1, 2]) == '0|2'
-
- def test_tuple(self):
- tmpl = env.from_string('{{ () }}|{{ (1,) }}|{{ (1, 2) }}')
- assert tmpl.render() == '()|(1,)|(1, 2)'
-
- def test_math(self):
- tmpl = env.from_string('{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}')
- assert tmpl.render() == '1.5|8'
-
- def test_div(self):
- tmpl = env.from_string('{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}')
- assert tmpl.render() == '1|1.5|1'
-
- def test_unary(self):
- tmpl = env.from_string('{{ +3 }}|{{ -3 }}')
- assert tmpl.render() == '3|-3'
-
- def test_concat(self):
- tmpl = env.from_string("{{ [1, 2] ~ 'foo' }}")
- assert tmpl.render() == '[1, 2]foo'
-
- def test_compare(self):
- tmpl = env.from_string('{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|'
- '{{ 2 == 2 }}|{{ 1 <= 1 }}')
- assert tmpl.render() == 'True|True|True|True|True'
-
- def test_inop(self):
- tmpl = env.from_string('{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}')
- assert tmpl.render() == 'True|False'
-
- def test_literals(self):
- tmpl = env.from_string('{{ [] }}|{{ {} }}|{{ () }}')
- assert tmpl.render().lower() == '[]|{}|()'
-
- def test_bool(self):
- tmpl = env.from_string('{{ true and false }}|{{ false '
- 'or true }}|{{ not false }}')
- assert tmpl.render() == 'False|True|True'
-
- def test_grouping(self):
- tmpl = env.from_string('{{ (true and false) or (false and true) and not false }}')
- assert tmpl.render() == 'False'
-
- def test_django_attr(self):
- tmpl = env.from_string('{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}')
- assert tmpl.render() == '1|1'
-
- def test_conditional_expression(self):
- tmpl = env.from_string('''{{ 0 if true else 1 }}''')
- assert tmpl.render() == '0'
-
- def test_short_conditional_expression(self):
- tmpl = env.from_string('<{{ 1 if false }}>')
- assert tmpl.render() == '<>'
-
- tmpl = env.from_string('<{{ (1 if false).bar }}>')
- self.assert_raises(UndefinedError, tmpl.render)
-
- def test_filter_priority(self):
- tmpl = env.from_string('{{ "foo"|upper + "bar"|upper }}')
- assert tmpl.render() == 'FOOBAR'
-
- def test_function_calls(self):
- tests = [
- (True, '*foo, bar'),
- (True, '*foo, *bar'),
- (True, '*foo, bar=42'),
- (True, '**foo, *bar'),
- (True, '**foo, bar'),
- (False, 'foo, bar'),
- (False, 'foo, bar=42'),
- (False, 'foo, bar=23, *args'),
- (False, 'a, b=c, *d, **e'),
- (False, '*foo, **bar')
- ]
- for should_fail, sig in tests:
- if should_fail:
- self.assert_raises(TemplateSyntaxError,
- env.from_string, '{{ foo(%s) }}' % sig)
- else:
- env.from_string('foo(%s)' % sig)
-
- def test_tuple_expr(self):
- for tmpl in [
- '{{ () }}',
- '{{ (1, 2) }}',
- '{{ (1, 2,) }}',
- '{{ 1, }}',
- '{{ 1, 2 }}',
- '{% for foo, bar in seq %}...{% endfor %}',
- '{% for x in foo, bar %}...{% endfor %}',
- '{% for x in foo, %}...{% endfor %}'
- ]:
- assert env.from_string(tmpl)
-
- def test_trailing_comma(self):
- tmpl = env.from_string('{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}')
- assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}'
-
- def test_block_end_name(self):
- env.from_string('{% block foo %}...{% endblock foo %}')
- self.assert_raises(TemplateSyntaxError, env.from_string,
- '{% block x %}{% endblock y %}')
-
- def test_constant_casing(self):
- for const in True, False, None:
- tmpl = env.from_string('{{ %s }}|{{ %s }}|{{ %s }}' % (
- str(const), str(const).lower(), str(const).upper()
- ))
- assert tmpl.render() == '%s|%s|' % (const, const)
-
- def test_test_chaining(self):
- self.assert_raises(TemplateSyntaxError, env.from_string,
- '{{ foo is string is sequence }}')
- assert env.from_string('{{ 42 is string or 42 is number }}'
- ).render() == 'True'
-
- def test_string_concatenation(self):
- tmpl = env.from_string('{{ "foo" "bar" "baz" }}')
- assert tmpl.render() == 'foobarbaz'
-
- def test_notin(self):
- bar = range(100)
- tmpl = env.from_string('''{{ not 42 in bar }}''')
- assert tmpl.render(bar=bar) == text_type(not 42 in bar)
-
- def test_implicit_subscribed_tuple(self):
- class Foo(object):
- def __getitem__(self, x):
- return x
- t = env.from_string('{{ foo[1, 2] }}')
- assert t.render(foo=Foo()) == u'(1, 2)'
-
- def test_raw2(self):
- tmpl = env.from_string('{% raw %}{{ FOO }} and {% BAR %}{% endraw %}')
- assert tmpl.render() == '{{ FOO }} and {% BAR %}'
-
- def test_const(self):
- tmpl = env.from_string('{{ true }}|{{ false }}|{{ none }}|'
- '{{ none is defined }}|{{ missing is defined }}')
- assert tmpl.render() == 'True|False|None|True|False'
-
- def test_neg_filter_priority(self):
- node = env.parse('{{ -1|foo }}')
- assert isinstance(node.body[0].nodes[0], nodes.Filter)
- assert isinstance(node.body[0].nodes[0].node, nodes.Neg)
-
- def test_const_assign(self):
- constass1 = '''{% set true = 42 %}'''
- constass2 = '''{% for none in seq %}{% endfor %}'''
- for tmpl in constass1, constass2:
- self.assert_raises(TemplateSyntaxError, env.from_string, tmpl)
-
- def test_localset(self):
- tmpl = env.from_string('''{% set foo = 0 %}\
-{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\
-{{ foo }}''')
- assert tmpl.render() == '0'
-
- def test_parse_unary(self):
- tmpl = env.from_string('{{ -foo["bar"] }}')
- assert tmpl.render(foo={'bar': 42}) == '-42'
- tmpl = env.from_string('{{ -foo["bar"]|abs }}')
- assert tmpl.render(foo={'bar': 42}) == '42'
-
-
-class LstripBlocksTestCase(JinjaTestCase):
-
- def test_lstrip(self):
- env = Environment(lstrip_blocks=True, trim_blocks=False)
- tmpl = env.from_string(''' {% if True %}\n {% endif %}''')
- assert tmpl.render() == "\n"
-
- def test_lstrip_trim(self):
- env = Environment(lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string(''' {% if True %}\n {% endif %}''')
- assert tmpl.render() == ""
-
- def test_no_lstrip(self):
- env = Environment(lstrip_blocks=True, trim_blocks=False)
- tmpl = env.from_string(''' {%+ if True %}\n {%+ endif %}''')
- assert tmpl.render() == " \n "
-
- def test_lstrip_endline(self):
- env = Environment(lstrip_blocks=True, trim_blocks=False)
- tmpl = env.from_string(''' hello{% if True %}\n goodbye{% endif %}''')
- assert tmpl.render() == " hello\n goodbye"
-
- def test_lstrip_inline(self):
- env = Environment(lstrip_blocks=True, trim_blocks=False)
- tmpl = env.from_string(''' {% if True %}hello {% endif %}''')
- assert tmpl.render() == 'hello '
-
- def test_lstrip_nested(self):
- env = Environment(lstrip_blocks=True, trim_blocks=False)
- tmpl = env.from_string(''' {% if True %}a {% if True %}b {% endif %}c {% endif %}''')
- assert tmpl.render() == 'a b c '
-
- def test_lstrip_left_chars(self):
- env = Environment(lstrip_blocks=True, trim_blocks=False)
- tmpl = env.from_string(''' abc {% if True %}
- hello{% endif %}''')
- assert tmpl.render() == ' abc \n hello'
-
- def test_lstrip_embeded_strings(self):
- env = Environment(lstrip_blocks=True, trim_blocks=False)
- tmpl = env.from_string(''' {% set x = " {% str %} " %}{{ x }}''')
- assert tmpl.render() == ' {% str %} '
-
- def test_lstrip_preserve_leading_newlines(self):
- env = Environment(lstrip_blocks=True, trim_blocks=False)
- tmpl = env.from_string('''\n\n\n{% set hello = 1 %}''')
- assert tmpl.render() == '\n\n\n'
-
- def test_lstrip_comment(self):
- env = Environment(lstrip_blocks=True, trim_blocks=False)
- tmpl = env.from_string(''' {# if True #}
-hello
- {#endif#}''')
- assert tmpl.render() == '\nhello\n'
-
- def test_lstrip_angle_bracket_simple(self):
- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',
- lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string(''' <% if True %>hello <% endif %>''')
- assert tmpl.render() == 'hello '
-
- def test_lstrip_angle_bracket_comment(self):
- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',
- lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string(''' <%# if True %>hello <%# endif %>''')
- assert tmpl.render() == 'hello '
-
- def test_lstrip_angle_bracket(self):
- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',
- lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string('''\
- <%# regular comment %>
- <% for item in seq %>
-${item} ## the rest of the stuff
- <% endfor %>''')
- assert tmpl.render(seq=range(5)) == \
- ''.join('%s\n' % x for x in range(5))
-
- def test_lstrip_angle_bracket_compact(self):
- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',
- lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string('''\
- <%#regular comment%>
- <%for item in seq%>
-${item} ## the rest of the stuff
- <%endfor%>''')
- assert tmpl.render(seq=range(5)) == \
- ''.join('%s\n' % x for x in range(5))
-
- def test_php_syntax_with_manual(self):
- env = Environment('', '?>', '=', '?>', '',
- lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string('''\
-
- for item in seq -?>
- = item ?>
- - endfor ?>''')
- assert tmpl.render(seq=range(5)) == '01234'
-
- def test_php_syntax(self):
- env = Environment('', '?>', '=', '?>', '',
- lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string('''\
-
- for item in seq ?>
- = item ?>
- endfor ?>''')
- assert tmpl.render(seq=range(5)) == ''.join(' %s\n' % x for x in range(5))
-
- def test_php_syntax_compact(self):
- env = Environment('', '?>', '=', '?>', '',
- lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string('''\
-
-
- =item?>
- ''')
- assert tmpl.render(seq=range(5)) == ''.join(' %s\n' % x for x in range(5))
-
- def test_erb_syntax(self):
- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',
- lstrip_blocks=True, trim_blocks=True)
- #env.from_string('')
- #for n,r in env.lexer.rules.iteritems():
- # print n
- #print env.lexer.rules['root'][0][0].pattern
- #print "'%s'" % tmpl.render(seq=range(5))
- tmpl = env.from_string('''\
-<%# I'm a comment, I'm not interesting %>
- <% for item in seq %>
- <%= item %>
- <% endfor %>
-''')
- assert tmpl.render(seq=range(5)) == ''.join(' %s\n' % x for x in range(5))
-
- def test_erb_syntax_with_manual(self):
- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',
- lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string('''\
-<%# I'm a comment, I'm not interesting %>
- <% for item in seq -%>
- <%= item %>
- <%- endfor %>''')
- assert tmpl.render(seq=range(5)) == '01234'
-
- def test_erb_syntax_no_lstrip(self):
- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',
- lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string('''\
-<%# I'm a comment, I'm not interesting %>
- <%+ for item in seq -%>
- <%= item %>
- <%- endfor %>''')
- assert tmpl.render(seq=range(5)) == ' 01234'
-
- def test_comment_syntax(self):
- env = Environment('', '${', '}', '',
- lstrip_blocks=True, trim_blocks=True)
- tmpl = env.from_string('''\
-\
-
- ${item}
-''')
- assert tmpl.render(seq=range(5)) == '01234'
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(TokenStreamTestCase))
- suite.addTest(unittest.makeSuite(LexerTestCase))
- suite.addTest(unittest.makeSuite(ParserTestCase))
- suite.addTest(unittest.makeSuite(SyntaxTestCase))
- suite.addTest(unittest.makeSuite(LstripBlocksTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/loader.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/loader.py
deleted file mode 100644
index a7350aa..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/loader.py
+++ /dev/null
@@ -1,226 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.loader
- ~~~~~~~~~~~~~~~~~~~~~~~
-
- Test the loaders.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import os
-import sys
-import tempfile
-import shutil
-import unittest
-
-from jinja2.testsuite import JinjaTestCase, dict_loader, \
- package_loader, filesystem_loader, function_loader, \
- choice_loader, prefix_loader
-
-from jinja2 import Environment, loaders
-from jinja2._compat import PYPY, PY2
-from jinja2.loaders import split_template_path
-from jinja2.exceptions import TemplateNotFound
-
-
-class LoaderTestCase(JinjaTestCase):
-
- def test_dict_loader(self):
- env = Environment(loader=dict_loader)
- tmpl = env.get_template('justdict.html')
- assert tmpl.render().strip() == 'FOO'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
- def test_package_loader(self):
- env = Environment(loader=package_loader)
- tmpl = env.get_template('test.html')
- assert tmpl.render().strip() == 'BAR'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
- def test_filesystem_loader(self):
- env = Environment(loader=filesystem_loader)
- tmpl = env.get_template('test.html')
- assert tmpl.render().strip() == 'BAR'
- tmpl = env.get_template('foo/test.html')
- assert tmpl.render().strip() == 'FOO'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
- def test_choice_loader(self):
- env = Environment(loader=choice_loader)
- tmpl = env.get_template('justdict.html')
- assert tmpl.render().strip() == 'FOO'
- tmpl = env.get_template('test.html')
- assert tmpl.render().strip() == 'BAR'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
- def test_function_loader(self):
- env = Environment(loader=function_loader)
- tmpl = env.get_template('justfunction.html')
- assert tmpl.render().strip() == 'FOO'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
- def test_prefix_loader(self):
- env = Environment(loader=prefix_loader)
- tmpl = env.get_template('a/test.html')
- assert tmpl.render().strip() == 'BAR'
- tmpl = env.get_template('b/justdict.html')
- assert tmpl.render().strip() == 'FOO'
- self.assert_raises(TemplateNotFound, env.get_template, 'missing')
-
- def test_caching(self):
- changed = False
- class TestLoader(loaders.BaseLoader):
- def get_source(self, environment, template):
- return u'foo', None, lambda: not changed
- env = Environment(loader=TestLoader(), cache_size=-1)
- tmpl = env.get_template('template')
- assert tmpl is env.get_template('template')
- changed = True
- assert tmpl is not env.get_template('template')
- changed = False
-
- env = Environment(loader=TestLoader(), cache_size=0)
- assert env.get_template('template') \
- is not env.get_template('template')
-
- env = Environment(loader=TestLoader(), cache_size=2)
- t1 = env.get_template('one')
- t2 = env.get_template('two')
- assert t2 is env.get_template('two')
- assert t1 is env.get_template('one')
- t3 = env.get_template('three')
- assert 'one' in env.cache
- assert 'two' not in env.cache
- assert 'three' in env.cache
-
- def test_dict_loader_cache_invalidates(self):
- mapping = {'foo': "one"}
- env = Environment(loader=loaders.DictLoader(mapping))
- assert env.get_template('foo').render() == "one"
- mapping['foo'] = "two"
- assert env.get_template('foo').render() == "two"
-
- def test_split_template_path(self):
- assert split_template_path('foo/bar') == ['foo', 'bar']
- assert split_template_path('./foo/bar') == ['foo', 'bar']
- self.assert_raises(TemplateNotFound, split_template_path, '../foo')
-
-
-class ModuleLoaderTestCase(JinjaTestCase):
- archive = None
-
- def compile_down(self, zip='deflated', py_compile=False):
- super(ModuleLoaderTestCase, self).setup()
- log = []
- self.reg_env = Environment(loader=prefix_loader)
- if zip is not None:
- self.archive = tempfile.mkstemp(suffix='.zip')[1]
- else:
- self.archive = tempfile.mkdtemp()
- self.reg_env.compile_templates(self.archive, zip=zip,
- log_function=log.append,
- py_compile=py_compile)
- self.mod_env = Environment(loader=loaders.ModuleLoader(self.archive))
- return ''.join(log)
-
- def teardown(self):
- super(ModuleLoaderTestCase, self).teardown()
- if hasattr(self, 'mod_env'):
- if os.path.isfile(self.archive):
- os.remove(self.archive)
- else:
- shutil.rmtree(self.archive)
- self.archive = None
-
- def test_log(self):
- log = self.compile_down()
- assert 'Compiled "a/foo/test.html" as ' \
- 'tmpl_a790caf9d669e39ea4d280d597ec891c4ef0404a' in log
- assert 'Finished compiling templates' in log
- assert 'Could not compile "a/syntaxerror.html": ' \
- 'Encountered unknown tag \'endif\'' in log
-
- def _test_common(self):
- tmpl1 = self.reg_env.get_template('a/test.html')
- tmpl2 = self.mod_env.get_template('a/test.html')
- assert tmpl1.render() == tmpl2.render()
-
- tmpl1 = self.reg_env.get_template('b/justdict.html')
- tmpl2 = self.mod_env.get_template('b/justdict.html')
- assert tmpl1.render() == tmpl2.render()
-
- def test_deflated_zip_compile(self):
- self.compile_down(zip='deflated')
- self._test_common()
-
- def test_stored_zip_compile(self):
- self.compile_down(zip='stored')
- self._test_common()
-
- def test_filesystem_compile(self):
- self.compile_down(zip=None)
- self._test_common()
-
- def test_weak_references(self):
- self.compile_down()
- tmpl = self.mod_env.get_template('a/test.html')
- key = loaders.ModuleLoader.get_template_key('a/test.html')
- name = self.mod_env.loader.module.__name__
-
- assert hasattr(self.mod_env.loader.module, key)
- assert name in sys.modules
-
- # unset all, ensure the module is gone from sys.modules
- self.mod_env = tmpl = None
-
- try:
- import gc
- gc.collect()
- except:
- pass
-
- assert name not in sys.modules
-
- # This test only makes sense on non-pypy python 2
- if PY2 and not PYPY:
- def test_byte_compilation(self):
- log = self.compile_down(py_compile=True)
- assert 'Byte-compiled "a/test.html"' in log
- tmpl1 = self.mod_env.get_template('a/test.html')
- mod = self.mod_env.loader.module. \
- tmpl_3c4ddf650c1a73df961a6d3d2ce2752f1b8fd490
- assert mod.__file__.endswith('.pyc')
-
- def test_choice_loader(self):
- log = self.compile_down()
-
- self.mod_env.loader = loaders.ChoiceLoader([
- self.mod_env.loader,
- loaders.DictLoader({'DICT_SOURCE': 'DICT_TEMPLATE'})
- ])
-
- tmpl1 = self.mod_env.get_template('a/test.html')
- self.assert_equal(tmpl1.render(), 'BAR')
- tmpl2 = self.mod_env.get_template('DICT_SOURCE')
- self.assert_equal(tmpl2.render(), 'DICT_TEMPLATE')
-
- def test_prefix_loader(self):
- log = self.compile_down()
-
- self.mod_env.loader = loaders.PrefixLoader({
- 'MOD': self.mod_env.loader,
- 'DICT': loaders.DictLoader({'test.html': 'DICT_TEMPLATE'})
- })
-
- tmpl1 = self.mod_env.get_template('MOD/a/test.html')
- self.assert_equal(tmpl1.render(), 'BAR')
- tmpl2 = self.mod_env.get_template('DICT/test.html')
- self.assert_equal(tmpl2.render(), 'DICT_TEMPLATE')
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(LoaderTestCase))
- suite.addTest(unittest.makeSuite(ModuleLoaderTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/regression.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/regression.py
deleted file mode 100644
index c5f7d5c..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/regression.py
+++ /dev/null
@@ -1,279 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.regression
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Tests corner cases and bugs.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \
- TemplateNotFound, PrefixLoader
-from jinja2._compat import text_type
-
-env = Environment()
-
-
-class CornerTestCase(JinjaTestCase):
-
- def test_assigned_scoping(self):
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) -%}
- [{{ item }}]
- {%- endfor %}
- {{- item -}}
- ''')
- assert t.render(item=42) == '[1][2][3][4]42'
-
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) -%}
- [{{ item }}]
- {%- endfor %}
- {%- set item = 42 %}
- {{- item -}}
- ''')
- assert t.render() == '[1][2][3][4]42'
-
- t = env.from_string('''
- {%- set item = 42 %}
- {%- for item in (1, 2, 3, 4) -%}
- [{{ item }}]
- {%- endfor %}
- {{- item -}}
- ''')
- assert t.render() == '[1][2][3][4]42'
-
- def test_closure_scoping(self):
- t = env.from_string('''
- {%- set wrapper = "" %}
- {%- for item in (1, 2, 3, 4) %}
- {%- macro wrapper() %}[{{ item }}]{% endmacro %}
- {{- wrapper() }}
- {%- endfor %}
- {{- wrapper -}}
- ''')
- assert t.render() == '[1][2][3][4]'
-
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) %}
- {%- macro wrapper() %}[{{ item }}]{% endmacro %}
- {{- wrapper() }}
- {%- endfor %}
- {%- set wrapper = "" %}
- {{- wrapper -}}
- ''')
- assert t.render() == '[1][2][3][4]'
-
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) %}
- {%- macro wrapper() %}[{{ item }}]{% endmacro %}
- {{- wrapper() }}
- {%- endfor %}
- {{- wrapper -}}
- ''')
- assert t.render(wrapper=23) == '[1][2][3][4]23'
-
-
-class BugTestCase(JinjaTestCase):
-
- def test_keyword_folding(self):
- env = Environment()
- env.filters['testing'] = lambda value, some: value + some
- assert env.from_string("{{ 'test'|testing(some='stuff') }}") \
- .render() == 'teststuff'
-
- def test_extends_output_bugs(self):
- env = Environment(loader=DictLoader({
- 'parent.html': '(({% block title %}{% endblock %}))'
- }))
-
- t = env.from_string('{% if expr %}{% extends "parent.html" %}{% endif %}'
- '[[{% block title %}title{% endblock %}]]'
- '{% for item in [1, 2, 3] %}({{ item }}){% endfor %}')
- assert t.render(expr=False) == '[[title]](1)(2)(3)'
- assert t.render(expr=True) == '((title))'
-
- def test_urlize_filter_escaping(self):
- tmpl = env.from_string('{{ "http://www.example.org/http://www.example.org/<foo'
-
- def test_loop_call_loop(self):
- tmpl = env.from_string('''
-
- {% macro test() %}
- {{ caller() }}
- {% endmacro %}
-
- {% for num1 in range(5) %}
- {% call test() %}
- {% for num2 in range(10) %}
- {{ loop.index }}
- {% endfor %}
- {% endcall %}
- {% endfor %}
-
- ''')
-
- assert tmpl.render().split() == [text_type(x) for x in range(1, 11)] * 5
-
- def test_weird_inline_comment(self):
- env = Environment(line_statement_prefix='%')
- self.assert_raises(TemplateSyntaxError, env.from_string,
- '% for item in seq {# missing #}\n...% endfor')
-
- def test_old_macro_loop_scoping_bug(self):
- tmpl = env.from_string('{% for i in (1, 2) %}{{ i }}{% endfor %}'
- '{% macro i() %}3{% endmacro %}{{ i() }}')
- assert tmpl.render() == '123'
-
- def test_partial_conditional_assignments(self):
- tmpl = env.from_string('{% if b %}{% set a = 42 %}{% endif %}{{ a }}')
- assert tmpl.render(a=23) == '23'
- assert tmpl.render(b=True) == '42'
-
- def test_stacked_locals_scoping_bug(self):
- env = Environment(line_statement_prefix='#')
- t = env.from_string('''\
-# for j in [1, 2]:
-# set x = 1
-# for i in [1, 2]:
-# print x
-# if i % 2 == 0:
-# set x = x + 1
-# endif
-# endfor
-# endfor
-# if a
-# print 'A'
-# elif b
-# print 'B'
-# elif c == d
-# print 'C'
-# else
-# print 'D'
-# endif
- ''')
- assert t.render(a=0, b=False, c=42, d=42.0) == '1111C'
-
- def test_stacked_locals_scoping_bug_twoframe(self):
- t = Template('''
- {% set x = 1 %}
- {% for item in foo %}
- {% if item == 1 %}
- {% set x = 2 %}
- {% endif %}
- {% endfor %}
- {{ x }}
- ''')
- rv = t.render(foo=[1]).strip()
- assert rv == u'1'
-
- def test_call_with_args(self):
- t = Template("""{% macro dump_users(users) -%}
-
- {%- for user in users -%}
- {{ user.username|e }}
{{ caller(user) }}
- {%- endfor -%}
-
- {%- endmacro -%}
-
- {% call(user) dump_users(list_of_user) -%}
-
- Realname
- - {{ user.realname|e }}
- Description
- - {{ user.description }}
-
- {% endcall %}""")
-
- assert [x.strip() for x in t.render(list_of_user=[{
- 'username':'apo',
- 'realname':'something else',
- 'description':'test'
- }]).splitlines()] == [
- u'apo
',
- u'Realname
',
- u'- something else
',
- u'Description
',
- u'- test
',
- u'
',
- u'
'
- ]
-
- def test_empty_if_condition_fails(self):
- self.assert_raises(TemplateSyntaxError, Template, '{% if %}....{% endif %}')
- self.assert_raises(TemplateSyntaxError, Template, '{% if foo %}...{% elif %}...{% endif %}')
- self.assert_raises(TemplateSyntaxError, Template, '{% for x in %}..{% endfor %}')
-
- def test_recursive_loop_bug(self):
- tpl1 = Template("""
- {% for p in foo recursive%}
- {{p.bar}}
- {% for f in p.fields recursive%}
- {{f.baz}}
- {{p.bar}}
- {% if f.rec %}
- {{ loop(f.sub) }}
- {% endif %}
- {% endfor %}
- {% endfor %}
- """)
-
- tpl2 = Template("""
- {% for p in foo%}
- {{p.bar}}
- {% for f in p.fields recursive%}
- {{f.baz}}
- {{p.bar}}
- {% if f.rec %}
- {{ loop(f.sub) }}
- {% endif %}
- {% endfor %}
- {% endfor %}
- """)
-
- def test_else_loop_bug(self):
- t = Template('''
- {% for x in y %}
- {{ loop.index0 }}
- {% else %}
- {% for i in range(3) %}{{ i }}{% endfor %}
- {% endfor %}
- ''')
- self.assertEqual(t.render(y=[]).strip(), '012')
-
- def test_correct_prefix_loader_name(self):
- env = Environment(loader=PrefixLoader({
- 'foo': DictLoader({})
- }))
- try:
- env.get_template('foo/bar.html')
- except TemplateNotFound as e:
- assert e.name == 'foo/bar.html'
- else:
- assert False, 'expected error here'
-
- def test_contextfunction_callable_classes(self):
- from jinja2.utils import contextfunction
- class CallableClass(object):
- @contextfunction
- def __call__(self, ctx):
- return ctx.resolve('hello')
-
- tpl = Template("""{{ callableclass() }}""")
- output = tpl.render(callableclass = CallableClass(), hello = 'TEST')
- expected = 'TEST'
-
- self.assert_equal(output, expected)
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(CornerTestCase))
- suite.addTest(unittest.makeSuite(BugTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/__init__.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/broken.html b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/broken.html
deleted file mode 100644
index 77669fa..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/broken.html
+++ /dev/null
@@ -1,3 +0,0 @@
-Before
-{{ fail() }}
-After
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/foo/test.html b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/foo/test.html
deleted file mode 100644
index b7d6715..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/foo/test.html
+++ /dev/null
@@ -1 +0,0 @@
-FOO
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/syntaxerror.html b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/syntaxerror.html
deleted file mode 100644
index f21b817..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/syntaxerror.html
+++ /dev/null
@@ -1,4 +0,0 @@
-Foo
-{% for item in broken %}
- ...
-{% endif %}
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/test.html b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/test.html
deleted file mode 100644
index ba578e4..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/res/templates/test.html
+++ /dev/null
@@ -1 +0,0 @@
-BAR
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/security.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/security.py
deleted file mode 100644
index 246d0f0..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/security.py
+++ /dev/null
@@ -1,166 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.security
- ~~~~~~~~~~~~~~~~~~~~~~~~~
-
- Checks the sandbox and other security features.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Environment
-from jinja2.sandbox import SandboxedEnvironment, \
- ImmutableSandboxedEnvironment, unsafe
-from jinja2 import Markup, escape
-from jinja2.exceptions import SecurityError, TemplateSyntaxError, \
- TemplateRuntimeError
-from jinja2._compat import text_type
-
-
-class PrivateStuff(object):
-
- def bar(self):
- return 23
-
- @unsafe
- def foo(self):
- return 42
-
- def __repr__(self):
- return 'PrivateStuff'
-
-
-class PublicStuff(object):
- bar = lambda self: 23
- _foo = lambda self: 42
-
- def __repr__(self):
- return 'PublicStuff'
-
-
-class SandboxTestCase(JinjaTestCase):
-
- def test_unsafe(self):
- env = SandboxedEnvironment()
- self.assert_raises(SecurityError, env.from_string("{{ foo.foo() }}").render,
- foo=PrivateStuff())
- self.assert_equal(env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff()), '23')
-
- self.assert_raises(SecurityError, env.from_string("{{ foo._foo() }}").render,
- foo=PublicStuff())
- self.assert_equal(env.from_string("{{ foo.bar() }}").render(foo=PublicStuff()), '23')
- self.assert_equal(env.from_string("{{ foo.__class__ }}").render(foo=42), '')
- self.assert_equal(env.from_string("{{ foo.func_code }}").render(foo=lambda:None), '')
- # security error comes from __class__ already.
- self.assert_raises(SecurityError, env.from_string(
- "{{ foo.__class__.__subclasses__() }}").render, foo=42)
-
- def test_immutable_environment(self):
- env = ImmutableSandboxedEnvironment()
- self.assert_raises(SecurityError, env.from_string(
- '{{ [].append(23) }}').render)
- self.assert_raises(SecurityError, env.from_string(
- '{{ {1:2}.clear() }}').render)
-
- def test_restricted(self):
- env = SandboxedEnvironment()
- self.assert_raises(TemplateSyntaxError, env.from_string,
- "{% for item.attribute in seq %}...{% endfor %}")
- self.assert_raises(TemplateSyntaxError, env.from_string,
- "{% for foo, bar.baz in seq %}...{% endfor %}")
-
- def test_markup_operations(self):
- # adding two strings should escape the unsafe one
- unsafe = ''
- safe = Markup('username')
- assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)
-
- # string interpolations are safe to use too
- assert Markup('%s') % '' == \
- '<bad user>'
- assert Markup('%(username)s') % {
- 'username': ''
- } == '<bad user>'
-
- # an escaped object is markup too
- assert type(Markup('foo') + 'bar') is Markup
-
- # and it implements __html__ by returning itself
- x = Markup("foo")
- assert x.__html__() is x
-
- # it also knows how to treat __html__ objects
- class Foo(object):
- def __html__(self):
- return 'awesome'
- def __unicode__(self):
- return 'awesome'
- assert Markup(Foo()) == 'awesome'
- assert Markup('%s') % Foo() == \
- 'awesome'
-
- # escaping and unescaping
- assert escape('"<>&\'') == '"<>&''
- assert Markup("Foo & Bar").striptags() == "Foo & Bar"
- assert Markup("<test>").unescape() == ""
-
- def test_template_data(self):
- env = Environment(autoescape=True)
- t = env.from_string('{% macro say_hello(name) %}'
- 'Hello {{ name }}!
{% endmacro %}'
- '{{ say_hello("") }}')
- escaped_out = 'Hello <blink>foo</blink>!
'
- assert t.render() == escaped_out
- assert text_type(t.module) == escaped_out
- assert escape(t.module) == escaped_out
- assert t.module.say_hello('') == escaped_out
- assert escape(t.module.say_hello('')) == escaped_out
-
- def test_attr_filter(self):
- env = SandboxedEnvironment()
- tmpl = env.from_string('{{ cls|attr("__subclasses__")() }}')
- self.assert_raises(SecurityError, tmpl.render, cls=int)
-
- def test_binary_operator_intercepting(self):
- def disable_op(left, right):
- raise TemplateRuntimeError('that operator so does not work')
- for expr, ctx, rv in ('1 + 2', {}, '3'), ('a + 2', {'a': 2}, '4'):
- env = SandboxedEnvironment()
- env.binop_table['+'] = disable_op
- t = env.from_string('{{ %s }}' % expr)
- assert t.render(ctx) == rv
- env.intercepted_binops = frozenset(['+'])
- t = env.from_string('{{ %s }}' % expr)
- try:
- t.render(ctx)
- except TemplateRuntimeError as e:
- pass
- else:
- self.fail('expected runtime error')
-
- def test_unary_operator_intercepting(self):
- def disable_op(arg):
- raise TemplateRuntimeError('that operator so does not work')
- for expr, ctx, rv in ('-1', {}, '-1'), ('-a', {'a': 2}, '-2'):
- env = SandboxedEnvironment()
- env.unop_table['-'] = disable_op
- t = env.from_string('{{ %s }}' % expr)
- assert t.render(ctx) == rv
- env.intercepted_unops = frozenset(['-'])
- t = env.from_string('{{ %s }}' % expr)
- try:
- t.render(ctx)
- except TemplateRuntimeError as e:
- pass
- else:
- self.fail('expected runtime error')
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(SandboxTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/tests.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/tests.py
deleted file mode 100644
index 3ece7a8..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/tests.py
+++ /dev/null
@@ -1,93 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.tests
- ~~~~~~~~~~~~~~~~~~~~~~
-
- Who tests the tests?
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import unittest
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2 import Markup, Environment
-
-env = Environment()
-
-
-class TestsTestCase(JinjaTestCase):
-
- def test_defined(self):
- tmpl = env.from_string('{{ missing is defined }}|{{ true is defined }}')
- assert tmpl.render() == 'False|True'
-
- def test_even(self):
- tmpl = env.from_string('''{{ 1 is even }}|{{ 2 is even }}''')
- assert tmpl.render() == 'False|True'
-
- def test_odd(self):
- tmpl = env.from_string('''{{ 1 is odd }}|{{ 2 is odd }}''')
- assert tmpl.render() == 'True|False'
-
- def test_lower(self):
- tmpl = env.from_string('''{{ "foo" is lower }}|{{ "FOO" is lower }}''')
- assert tmpl.render() == 'True|False'
-
- def test_typechecks(self):
- tmpl = env.from_string('''
- {{ 42 is undefined }}
- {{ 42 is defined }}
- {{ 42 is none }}
- {{ none is none }}
- {{ 42 is number }}
- {{ 42 is string }}
- {{ "foo" is string }}
- {{ "foo" is sequence }}
- {{ [1] is sequence }}
- {{ range is callable }}
- {{ 42 is callable }}
- {{ range(5) is iterable }}
- {{ {} is mapping }}
- {{ mydict is mapping }}
- {{ [] is mapping }}
- ''')
- class MyDict(dict):
- pass
- assert tmpl.render(mydict=MyDict()).split() == [
- 'False', 'True', 'False', 'True', 'True', 'False',
- 'True', 'True', 'True', 'True', 'False', 'True',
- 'True', 'True', 'False'
- ]
-
- def test_sequence(self):
- tmpl = env.from_string(
- '{{ [1, 2, 3] is sequence }}|'
- '{{ "foo" is sequence }}|'
- '{{ 42 is sequence }}'
- )
- assert tmpl.render() == 'True|True|False'
-
- def test_upper(self):
- tmpl = env.from_string('{{ "FOO" is upper }}|{{ "foo" is upper }}')
- assert tmpl.render() == 'True|False'
-
- def test_sameas(self):
- tmpl = env.from_string('{{ foo is sameas false }}|'
- '{{ 0 is sameas false }}')
- assert tmpl.render(foo=False) == 'True|False'
-
- def test_no_paren_for_arg1(self):
- tmpl = env.from_string('{{ foo is sameas none }}')
- assert tmpl.render(foo=None) == 'True'
-
- def test_escaped(self):
- env = Environment(autoescape=True)
- tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}')
- assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True'
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(TestsTestCase))
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/utils.py b/Darwin/lib/python2.7/site-packages/jinja2/testsuite/utils.py
deleted file mode 100644
index cab9b09..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/testsuite/utils.py
+++ /dev/null
@@ -1,82 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.testsuite.utils
- ~~~~~~~~~~~~~~~~~~~~~~
-
- Tests utilities jinja uses.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import gc
-import unittest
-
-import pickle
-
-from jinja2.testsuite import JinjaTestCase
-
-from jinja2.utils import LRUCache, escape, object_type_repr
-
-
-class LRUCacheTestCase(JinjaTestCase):
-
- def test_simple(self):
- d = LRUCache(3)
- d["a"] = 1
- d["b"] = 2
- d["c"] = 3
- d["a"]
- d["d"] = 4
- assert len(d) == 3
- assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d
-
- def test_pickleable(self):
- cache = LRUCache(2)
- cache["foo"] = 42
- cache["bar"] = 23
- cache["foo"]
-
- for protocol in range(3):
- copy = pickle.loads(pickle.dumps(cache, protocol))
- assert copy.capacity == cache.capacity
- assert copy._mapping == cache._mapping
- assert copy._queue == cache._queue
-
-
-class HelpersTestCase(JinjaTestCase):
-
- def test_object_type_repr(self):
- class X(object):
- pass
- self.assert_equal(object_type_repr(42), 'int object')
- self.assert_equal(object_type_repr([]), 'list object')
- self.assert_equal(object_type_repr(X()),
- 'jinja2.testsuite.utils.X object')
- self.assert_equal(object_type_repr(None), 'None')
- self.assert_equal(object_type_repr(Ellipsis), 'Ellipsis')
-
-
-class MarkupLeakTestCase(JinjaTestCase):
-
- def test_markup_leaks(self):
- counts = set()
- for count in range(20):
- for item in range(1000):
- escape("foo")
- escape("")
- escape(u"foo")
- escape(u"")
- counts.add(len(gc.get_objects()))
- assert len(counts) == 1, 'ouch, c extension seems to leak objects'
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(LRUCacheTestCase))
- suite.addTest(unittest.makeSuite(HelpersTestCase))
-
- # this test only tests the c extension
- if not hasattr(escape, 'func_code'):
- suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
-
- return suite
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/utils.py b/Darwin/lib/python2.7/site-packages/jinja2/utils.py
deleted file mode 100644
index ddc47da..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/utils.py
+++ /dev/null
@@ -1,520 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.utils
- ~~~~~~~~~~~~
-
- Utility functions.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import re
-import errno
-from collections import deque
-from jinja2._compat import text_type, string_types, implements_iterator, \
- allocate_lock, url_quote
-
-
-_word_split_re = re.compile(r'(\s+)')
-_punctuation_re = re.compile(
- '^(?P(?:%s)*)(?P.*?)(?P(?:%s)*)$' % (
- '|'.join(map(re.escape, ('(', '<', '<'))),
- '|'.join(map(re.escape, ('.', ',', ')', '>', '\n', '>')))
- )
-)
-_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')
-_striptags_re = re.compile(r'(|<[^>]*>)')
-_entity_re = re.compile(r'&([^;]+);')
-_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
-_digits = '0123456789'
-
-# special singleton representing missing values for the runtime
-missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()
-
-# internal code
-internal_code = set()
-
-concat = u''.join
-
-
-def contextfunction(f):
- """This decorator can be used to mark a function or method context callable.
- A context callable is passed the active :class:`Context` as first argument when
- called from the template. This is useful if a function wants to get access
- to the context or functions provided on the context object. For example
- a function that returns a sorted list of template variables the current
- template exports could look like this::
-
- @contextfunction
- def get_exported_names(context):
- return sorted(context.exported_vars)
- """
- f.contextfunction = True
- return f
-
-
-def evalcontextfunction(f):
- """This decorator can be used to mark a function or method as an eval
- context callable. This is similar to the :func:`contextfunction`
- but instead of passing the context, an evaluation context object is
- passed. For more information about the eval context, see
- :ref:`eval-context`.
-
- .. versionadded:: 2.4
- """
- f.evalcontextfunction = True
- return f
-
-
-def environmentfunction(f):
- """This decorator can be used to mark a function or method as environment
- callable. This decorator works exactly like the :func:`contextfunction`
- decorator just that the first argument is the active :class:`Environment`
- and not context.
- """
- f.environmentfunction = True
- return f
-
-
-def internalcode(f):
- """Marks the function as internally used"""
- internal_code.add(f.__code__)
- return f
-
-
-def is_undefined(obj):
- """Check if the object passed is undefined. This does nothing more than
- performing an instance check against :class:`Undefined` but looks nicer.
- This can be used for custom filters or tests that want to react to
- undefined variables. For example a custom default filter can look like
- this::
-
- def default(var, default=''):
- if is_undefined(var):
- return default
- return var
- """
- from jinja2.runtime import Undefined
- return isinstance(obj, Undefined)
-
-
-def consume(iterable):
- """Consumes an iterable without doing anything with it."""
- for event in iterable:
- pass
-
-
-def clear_caches():
- """Jinja2 keeps internal caches for environments and lexers. These are
- used so that Jinja2 doesn't have to recreate environments and lexers all
- the time. Normally you don't have to care about that but if you are
- messuring memory consumption you may want to clean the caches.
- """
- from jinja2.environment import _spontaneous_environments
- from jinja2.lexer import _lexer_cache
- _spontaneous_environments.clear()
- _lexer_cache.clear()
-
-
-def import_string(import_name, silent=False):
- """Imports an object based on a string. This is useful if you want to
- use import paths as endpoints or something similar. An import path can
- be specified either in dotted notation (``xml.sax.saxutils.escape``)
- or with a colon as object delimiter (``xml.sax.saxutils:escape``).
-
- If the `silent` is True the return value will be `None` if the import
- fails.
-
- :return: imported object
- """
- try:
- if ':' in import_name:
- module, obj = import_name.split(':', 1)
- elif '.' in import_name:
- items = import_name.split('.')
- module = '.'.join(items[:-1])
- obj = items[-1]
- else:
- return __import__(import_name)
- return getattr(__import__(module, None, None, [obj]), obj)
- except (ImportError, AttributeError):
- if not silent:
- raise
-
-
-def open_if_exists(filename, mode='rb'):
- """Returns a file descriptor for the filename if that file exists,
- otherwise `None`.
- """
- try:
- return open(filename, mode)
- except IOError as e:
- if e.errno not in (errno.ENOENT, errno.EISDIR):
- raise
-
-
-def object_type_repr(obj):
- """Returns the name of the object's type. For some recognized
- singletons the name of the object is returned instead. (For
- example for `None` and `Ellipsis`).
- """
- if obj is None:
- return 'None'
- elif obj is Ellipsis:
- return 'Ellipsis'
- # __builtin__ in 2.x, builtins in 3.x
- if obj.__class__.__module__ in ('__builtin__', 'builtins'):
- name = obj.__class__.__name__
- else:
- name = obj.__class__.__module__ + '.' + obj.__class__.__name__
- return '%s object' % name
-
-
-def pformat(obj, verbose=False):
- """Prettyprint an object. Either use the `pretty` library or the
- builtin `pprint`.
- """
- try:
- from pretty import pretty
- return pretty(obj, verbose=verbose)
- except ImportError:
- from pprint import pformat
- return pformat(obj)
-
-
-def urlize(text, trim_url_limit=None, nofollow=False):
- """Converts any URLs in text into clickable links. Works on http://,
- https:// and www. links. Links can have trailing punctuation (periods,
- commas, close-parens) and leading punctuation (opening parens) and
- it'll still do the right thing.
-
- If trim_url_limit is not None, the URLs in link text will be limited
- to trim_url_limit characters.
-
- If nofollow is True, the URLs in link text will get a rel="nofollow"
- attribute.
- """
- trim_url = lambda x, limit=trim_url_limit: limit is not None \
- and (x[:limit] + (len(x) >=limit and '...'
- or '')) or x
- words = _word_split_re.split(text_type(escape(text)))
- nofollow_attr = nofollow and ' rel="nofollow"' or ''
- for i, word in enumerate(words):
- match = _punctuation_re.match(word)
- if match:
- lead, middle, trail = match.groups()
- if middle.startswith('www.') or (
- '@' not in middle and
- not middle.startswith('http://') and
- not middle.startswith('https://') and
- len(middle) > 0 and
- middle[0] in _letters + _digits and (
- middle.endswith('.org') or
- middle.endswith('.net') or
- middle.endswith('.com')
- )):
- middle = '%s' % (middle,
- nofollow_attr, trim_url(middle))
- if middle.startswith('http://') or \
- middle.startswith('https://'):
- middle = '%s' % (middle,
- nofollow_attr, trim_url(middle))
- if '@' in middle and not middle.startswith('www.') and \
- not ':' in middle and _simple_email_re.match(middle):
- middle = '%s' % (middle, middle)
- if lead + middle + trail != word:
- words[i] = lead + middle + trail
- return u''.join(words)
-
-
-def generate_lorem_ipsum(n=5, html=True, min=20, max=100):
- """Generate some lorem impsum for the template."""
- from jinja2.constants import LOREM_IPSUM_WORDS
- from random import choice, randrange
- words = LOREM_IPSUM_WORDS.split()
- result = []
-
- for _ in range(n):
- next_capitalized = True
- last_comma = last_fullstop = 0
- word = None
- last = None
- p = []
-
- # each paragraph contains out of 20 to 100 words.
- for idx, _ in enumerate(range(randrange(min, max))):
- while True:
- word = choice(words)
- if word != last:
- last = word
- break
- if next_capitalized:
- word = word.capitalize()
- next_capitalized = False
- # add commas
- if idx - randrange(3, 8) > last_comma:
- last_comma = idx
- last_fullstop += 2
- word += ','
- # add end of sentences
- if idx - randrange(10, 20) > last_fullstop:
- last_comma = last_fullstop = idx
- word += '.'
- next_capitalized = True
- p.append(word)
-
- # ensure that the paragraph ends with a dot.
- p = u' '.join(p)
- if p.endswith(','):
- p = p[:-1] + '.'
- elif not p.endswith('.'):
- p += '.'
- result.append(p)
-
- if not html:
- return u'\n\n'.join(result)
- return Markup(u'\n'.join(u'%s
' % escape(x) for x in result))
-
-
-def unicode_urlencode(obj, charset='utf-8'):
- """URL escapes a single bytestring or unicode string with the
- given charset if applicable to URL safe quoting under all rules
- that need to be considered under all supported Python versions.
-
- If non strings are provided they are converted to their unicode
- representation first.
- """
- if not isinstance(obj, string_types):
- obj = text_type(obj)
- if isinstance(obj, text_type):
- obj = obj.encode(charset)
- return text_type(url_quote(obj))
-
-
-class LRUCache(object):
- """A simple LRU Cache implementation."""
-
- # this is fast for small capacities (something below 1000) but doesn't
- # scale. But as long as it's only used as storage for templates this
- # won't do any harm.
-
- def __init__(self, capacity):
- self.capacity = capacity
- self._mapping = {}
- self._queue = deque()
- self._postinit()
-
- def _postinit(self):
- # alias all queue methods for faster lookup
- self._popleft = self._queue.popleft
- self._pop = self._queue.pop
- self._remove = self._queue.remove
- self._wlock = allocate_lock()
- self._append = self._queue.append
-
- def __getstate__(self):
- return {
- 'capacity': self.capacity,
- '_mapping': self._mapping,
- '_queue': self._queue
- }
-
- def __setstate__(self, d):
- self.__dict__.update(d)
- self._postinit()
-
- def __getnewargs__(self):
- return (self.capacity,)
-
- def copy(self):
- """Return a shallow copy of the instance."""
- rv = self.__class__(self.capacity)
- rv._mapping.update(self._mapping)
- rv._queue = deque(self._queue)
- return rv
-
- def get(self, key, default=None):
- """Return an item from the cache dict or `default`"""
- try:
- return self[key]
- except KeyError:
- return default
-
- def setdefault(self, key, default=None):
- """Set `default` if the key is not in the cache otherwise
- leave unchanged. Return the value of this key.
- """
- self._wlock.acquire()
- try:
- try:
- return self[key]
- except KeyError:
- self[key] = default
- return default
- finally:
- self._wlock.release()
-
- def clear(self):
- """Clear the cache."""
- self._wlock.acquire()
- try:
- self._mapping.clear()
- self._queue.clear()
- finally:
- self._wlock.release()
-
- def __contains__(self, key):
- """Check if a key exists in this cache."""
- return key in self._mapping
-
- def __len__(self):
- """Return the current size of the cache."""
- return len(self._mapping)
-
- def __repr__(self):
- return '<%s %r>' % (
- self.__class__.__name__,
- self._mapping
- )
-
- def __getitem__(self, key):
- """Get an item from the cache. Moves the item up so that it has the
- highest priority then.
-
- Raise a `KeyError` if it does not exist.
- """
- self._wlock.acquire()
- try:
- rv = self._mapping[key]
- if self._queue[-1] != key:
- try:
- self._remove(key)
- except ValueError:
- # if something removed the key from the container
- # when we read, ignore the ValueError that we would
- # get otherwise.
- pass
- self._append(key)
- return rv
- finally:
- self._wlock.release()
-
- def __setitem__(self, key, value):
- """Sets the value for an item. Moves the item up so that it
- has the highest priority then.
- """
- self._wlock.acquire()
- try:
- if key in self._mapping:
- self._remove(key)
- elif len(self._mapping) == self.capacity:
- del self._mapping[self._popleft()]
- self._append(key)
- self._mapping[key] = value
- finally:
- self._wlock.release()
-
- def __delitem__(self, key):
- """Remove an item from the cache dict.
- Raise a `KeyError` if it does not exist.
- """
- self._wlock.acquire()
- try:
- del self._mapping[key]
- try:
- self._remove(key)
- except ValueError:
- # __getitem__ is not locked, it might happen
- pass
- finally:
- self._wlock.release()
-
- def items(self):
- """Return a list of items."""
- result = [(key, self._mapping[key]) for key in list(self._queue)]
- result.reverse()
- return result
-
- def iteritems(self):
- """Iterate over all items."""
- return iter(self.items())
-
- def values(self):
- """Return a list of all values."""
- return [x[1] for x in self.items()]
-
- def itervalue(self):
- """Iterate over all values."""
- return iter(self.values())
-
- def keys(self):
- """Return a list of all keys ordered by most recent usage."""
- return list(self)
-
- def iterkeys(self):
- """Iterate over all keys in the cache dict, ordered by
- the most recent usage.
- """
- return reversed(tuple(self._queue))
-
- __iter__ = iterkeys
-
- def __reversed__(self):
- """Iterate over the values in the cache dict, oldest items
- coming first.
- """
- return iter(tuple(self._queue))
-
- __copy__ = copy
-
-
-# register the LRU cache as mutable mapping if possible
-try:
- from collections import MutableMapping
- MutableMapping.register(LRUCache)
-except ImportError:
- pass
-
-
-@implements_iterator
-class Cycler(object):
- """A cycle helper for templates."""
-
- def __init__(self, *items):
- if not items:
- raise RuntimeError('at least one item has to be provided')
- self.items = items
- self.reset()
-
- def reset(self):
- """Resets the cycle."""
- self.pos = 0
-
- @property
- def current(self):
- """Returns the current item."""
- return self.items[self.pos]
-
- def __next__(self):
- """Goes one item ahead and returns it."""
- rv = self.current
- self.pos = (self.pos + 1) % len(self.items)
- return rv
-
-
-class Joiner(object):
- """A joining helper for templates."""
-
- def __init__(self, sep=u', '):
- self.sep = sep
- self.used = False
-
- def __call__(self):
- if not self.used:
- self.used = True
- return u''
- return self.sep
-
-
-# Imported here because that's where it was in the past
-from markupsafe import Markup, escape, soft_unicode
diff --git a/Darwin/lib/python2.7/site-packages/jinja2/visitor.py b/Darwin/lib/python2.7/site-packages/jinja2/visitor.py
deleted file mode 100644
index 413e7c3..0000000
--- a/Darwin/lib/python2.7/site-packages/jinja2/visitor.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- jinja2.visitor
- ~~~~~~~~~~~~~~
-
- This module implements a visitor for the nodes.
-
- :copyright: (c) 2010 by the Jinja Team.
- :license: BSD.
-"""
-from jinja2.nodes import Node
-
-
-class NodeVisitor(object):
- """Walks the abstract syntax tree and call visitor functions for every
- node found. The visitor functions may return values which will be
- forwarded by the `visit` method.
-
- Per default the visitor functions for the nodes are ``'visit_'`` +
- class name of the node. So a `TryFinally` node visit function would
- be `visit_TryFinally`. This behavior can be changed by overriding
- the `get_visitor` function. If no visitor function exists for a node
- (return value `None`) the `generic_visit` visitor is used instead.
- """
-
- def get_visitor(self, node):
- """Return the visitor function for this node or `None` if no visitor
- exists for this node. In that case the generic visit function is
- used instead.
- """
- method = 'visit_' + node.__class__.__name__
- return getattr(self, method, None)
-
- def visit(self, node, *args, **kwargs):
- """Visit a node."""
- f = self.get_visitor(node)
- if f is not None:
- return f(node, *args, **kwargs)
- return self.generic_visit(node, *args, **kwargs)
-
- def generic_visit(self, node, *args, **kwargs):
- """Called if no explicit visitor function exists for a node."""
- for node in node.iter_child_nodes():
- self.visit(node, *args, **kwargs)
-
-
-class NodeTransformer(NodeVisitor):
- """Walks the abstract syntax tree and allows modifications of nodes.
-
- The `NodeTransformer` will walk the AST and use the return value of the
- visitor functions to replace or remove the old node. If the return
- value of the visitor function is `None` the node will be removed
- from the previous location otherwise it's replaced with the return
- value. The return value may be the original node in which case no
- replacement takes place.
- """
-
- def generic_visit(self, node, *args, **kwargs):
- for field, old_value in node.iter_fields():
- if isinstance(old_value, list):
- new_values = []
- for value in old_value:
- if isinstance(value, Node):
- value = self.visit(value, *args, **kwargs)
- if value is None:
- continue
- elif not isinstance(value, Node):
- new_values.extend(value)
- continue
- new_values.append(value)
- old_value[:] = new_values
- elif isinstance(old_value, Node):
- new_node = self.visit(old_value, *args, **kwargs)
- if new_node is None:
- delattr(node, field)
- else:
- setattr(node, field, new_node)
- return node
-
- def visit_list(self, node, *args, **kwargs):
- """As transformers may return lists in some places this method
- can be used to enforce a list as return value.
- """
- rv = self.visit(node, *args, **kwargs)
- if not isinstance(rv, list):
- rv = [rv]
- return rv
diff --git a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/PKG-INFO b/Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/PKG-INFO
similarity index 89%
rename from Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/PKG-INFO
rename to Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/PKG-INFO
index 9f660ec..b98b227 100644
--- a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/PKG-INFO
+++ b/Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/PKG-INFO
@@ -1,12 +1,12 @@
Metadata-Version: 1.1
Name: lxml
-Version: 3.3.5
+Version: 3.3.6
Summary: Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API.
Home-page: http://lxml.de/
Author: lxml dev team
Author-email: lxml-dev@lxml.de
License: UNKNOWN
-Download-URL: http://pypi.python.org/packages/source/l/lxml/lxml-3.3.5.tar.gz
+Download-URL: http://pypi.python.org/packages/source/l/lxml/lxml-3.3.6.tar.gz
Description: lxml is a Pythonic, mature binding for the libxml2 and libxslt libraries. It
provides safe and convenient access to these libraries using the ElementTree
API.
@@ -37,14 +37,18 @@ Description: lxml is a Pythonic, mature binding for the libxml2 and libxslt libr
as soon as a maintenance branch has been established. Note that this
requires Cython to be installed at an appropriate version for the build.
- 3.3.5 (2014-04-18)
+ 3.3.6 (2014-08-28)
==================
Bugs fixed
----------
- * HTML cleaning could fail to strip javascript links that mix control
- characters into the link scheme.
+ * Prevent tree cycle creation when adding Elements as siblings.
+
+ * LP#1361948: crash when deallocating Element siblings without parent.
+
+ * LP#1354652: crash when traversing internally loaded documents in XSLT
+ extension functions.
diff --git a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/SOURCES.txt
similarity index 99%
rename from Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/SOURCES.txt
rename to Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/SOURCES.txt
index b9be483..595cdcb 100644
--- a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/SOURCES.txt
+++ b/Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/SOURCES.txt
@@ -60,7 +60,7 @@ doc/html/FAQ.html
doc/html/api.html
doc/html/build.html
doc/html/capi.html
-doc/html/changes-3.3.5.html
+doc/html/changes-3.3.6.html
doc/html/compatibility.html
doc/html/credits.html
doc/html/cssselect.html
diff --git a/Darwin/lib/python2.7/site-packages/Flask_SQLAlchemy-1.0-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/dependency_links.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/Flask_SQLAlchemy-1.0-py2.7.egg-info/dependency_links.txt
rename to Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/dependency_links.txt
diff --git a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/installed-files.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/installed-files.txt
rename to Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/installed-files.txt
diff --git a/Darwin/lib/python2.7/site-packages/Flask_SQLAlchemy-1.0-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/not-zip-safe
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/Flask_SQLAlchemy-1.0-py2.7.egg-info/not-zip-safe
rename to Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/not-zip-safe
diff --git a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/requires.txt b/Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/requires.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/requires.txt
rename to Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/requires.txt
diff --git a/Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/top_level.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/lxml-3.3.5-py2.7.egg-info/top_level.txt
rename to Darwin/lib/python2.7/site-packages/lxml-3.3.6-py2.7.egg-info/top_level.txt
diff --git a/Darwin/lib/python2.7/site-packages/lxml/etree.so b/Darwin/lib/python2.7/site-packages/lxml/etree.so
index 47ff2fa..2886854 100755
Binary files a/Darwin/lib/python2.7/site-packages/lxml/etree.so and b/Darwin/lib/python2.7/site-packages/lxml/etree.so differ
diff --git a/Darwin/lib/python2.7/site-packages/lxml/includes/lxml-version.h b/Darwin/lib/python2.7/site-packages/lxml/includes/lxml-version.h
index cf1eaa3..62dece8 100644
--- a/Darwin/lib/python2.7/site-packages/lxml/includes/lxml-version.h
+++ b/Darwin/lib/python2.7/site-packages/lxml/includes/lxml-version.h
@@ -1,3 +1,3 @@
#ifndef LXML_VERSION_STRING
-#define LXML_VERSION_STRING "3.3.5"
+#define LXML_VERSION_STRING "3.3.6"
#endif
diff --git a/Darwin/lib/python2.7/site-packages/lxml/objectify.so b/Darwin/lib/python2.7/site-packages/lxml/objectify.so
index 6d93215..39a632b 100755
Binary files a/Darwin/lib/python2.7/site-packages/lxml/objectify.so and b/Darwin/lib/python2.7/site-packages/lxml/objectify.so differ
diff --git a/Darwin/lib/python2.7/site-packages/mako/__init__.py b/Darwin/lib/python2.7/site-packages/mako/__init__.py
deleted file mode 100644
index cb59f3a..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# mako/__init__.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-
-__version__ = '0.9.1'
-
diff --git a/Darwin/lib/python2.7/site-packages/mako/_ast_util.py b/Darwin/lib/python2.7/site-packages/mako/_ast_util.py
deleted file mode 100644
index 3b0bd21..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/_ast_util.py
+++ /dev/null
@@ -1,845 +0,0 @@
-# mako/_ast_util.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""
- ast
- ~~~
-
- The `ast` module helps Python applications to process trees of the Python
- abstract syntax grammar. The abstract syntax itself might change with
- each Python release; this module helps to find out programmatically what
- the current grammar looks like and allows modifications of it.
-
- An abstract syntax tree can be generated by passing `ast.PyCF_ONLY_AST` as
- a flag to the `compile()` builtin function or by using the `parse()`
- function from this module. The result will be a tree of objects whose
- classes all inherit from `ast.AST`.
-
- A modified abstract syntax tree can be compiled into a Python code object
- using the built-in `compile()` function.
-
- Additionally various helper functions are provided that make working with
- the trees simpler. The main intention of the helper functions and this
- module in general is to provide an easy to use interface for libraries
- that work tightly with the python syntax (template engines for example).
-
-
- :copyright: Copyright 2008 by Armin Ronacher.
- :license: Python License.
-"""
-from _ast import *
-from mako.compat import arg_stringname
-
-BOOLOP_SYMBOLS = {
- And: 'and',
- Or: 'or'
-}
-
-BINOP_SYMBOLS = {
- Add: '+',
- Sub: '-',
- Mult: '*',
- Div: '/',
- FloorDiv: '//',
- Mod: '%',
- LShift: '<<',
- RShift: '>>',
- BitOr: '|',
- BitAnd: '&',
- BitXor: '^'
-}
-
-CMPOP_SYMBOLS = {
- Eq: '==',
- Gt: '>',
- GtE: '>=',
- In: 'in',
- Is: 'is',
- IsNot: 'is not',
- Lt: '<',
- LtE: '<=',
- NotEq: '!=',
- NotIn: 'not in'
-}
-
-UNARYOP_SYMBOLS = {
- Invert: '~',
- Not: 'not',
- UAdd: '+',
- USub: '-'
-}
-
-ALL_SYMBOLS = {}
-ALL_SYMBOLS.update(BOOLOP_SYMBOLS)
-ALL_SYMBOLS.update(BINOP_SYMBOLS)
-ALL_SYMBOLS.update(CMPOP_SYMBOLS)
-ALL_SYMBOLS.update(UNARYOP_SYMBOLS)
-
-
-def parse(expr, filename='', mode='exec'):
- """Parse an expression into an AST node."""
- return compile(expr, filename, mode, PyCF_ONLY_AST)
-
-
-def to_source(node, indent_with=' ' * 4):
- """
- This function can convert a node tree back into python sourcecode. This
- is useful for debugging purposes, especially if you're dealing with custom
- asts not generated by python itself.
-
- It could be that the sourcecode is evaluable when the AST itself is not
- compilable / evaluable. The reason for this is that the AST contains some
- more data than regular sourcecode does, which is dropped during
- conversion.
-
- Each level of indentation is replaced with `indent_with`. Per default this
- parameter is equal to four spaces as suggested by PEP 8, but it might be
- adjusted to match the application's styleguide.
- """
- generator = SourceGenerator(indent_with)
- generator.visit(node)
- return ''.join(generator.result)
-
-
-def dump(node):
- """
- A very verbose representation of the node passed. This is useful for
- debugging purposes.
- """
- def _format(node):
- if isinstance(node, AST):
- return '%s(%s)' % (node.__class__.__name__,
- ', '.join('%s=%s' % (a, _format(b))
- for a, b in iter_fields(node)))
- elif isinstance(node, list):
- return '[%s]' % ', '.join(_format(x) for x in node)
- return repr(node)
- if not isinstance(node, AST):
- raise TypeError('expected AST, got %r' % node.__class__.__name__)
- return _format(node)
-
-
-def copy_location(new_node, old_node):
- """
- Copy the source location hint (`lineno` and `col_offset`) from the
- old to the new node if possible and return the new one.
- """
- for attr in 'lineno', 'col_offset':
- if attr in old_node._attributes and attr in new_node._attributes \
- and hasattr(old_node, attr):
- setattr(new_node, attr, getattr(old_node, attr))
- return new_node
-
-
-def fix_missing_locations(node):
- """
- Some nodes require a line number and the column offset. Without that
- information the compiler will abort the compilation. Because it can be
- a dull task to add appropriate line numbers and column offsets when
- adding new nodes this function can help. It copies the line number and
- column offset of the parent node to the child nodes without this
- information.
-
- Unlike `copy_location` this works recursive and won't touch nodes that
- already have a location information.
- """
- def _fix(node, lineno, col_offset):
- if 'lineno' in node._attributes:
- if not hasattr(node, 'lineno'):
- node.lineno = lineno
- else:
- lineno = node.lineno
- if 'col_offset' in node._attributes:
- if not hasattr(node, 'col_offset'):
- node.col_offset = col_offset
- else:
- col_offset = node.col_offset
- for child in iter_child_nodes(node):
- _fix(child, lineno, col_offset)
- _fix(node, 1, 0)
- return node
-
-
-def increment_lineno(node, n=1):
- """
- Increment the line numbers of all nodes by `n` if they have line number
- attributes. This is useful to "move code" to a different location in a
- file.
- """
- for node in zip((node,), walk(node)):
- if 'lineno' in node._attributes:
- node.lineno = getattr(node, 'lineno', 0) + n
-
-
-def iter_fields(node):
- """Iterate over all fields of a node, only yielding existing fields."""
- # CPython 2.5 compat
- if not hasattr(node, '_fields') or not node._fields:
- return
- for field in node._fields:
- try:
- yield field, getattr(node, field)
- except AttributeError:
- pass
-
-
-def get_fields(node):
- """Like `iter_fiels` but returns a dict."""
- return dict(iter_fields(node))
-
-
-def iter_child_nodes(node):
- """Iterate over all child nodes or a node."""
- for name, field in iter_fields(node):
- if isinstance(field, AST):
- yield field
- elif isinstance(field, list):
- for item in field:
- if isinstance(item, AST):
- yield item
-
-
-def get_child_nodes(node):
- """Like `iter_child_nodes` but returns a list."""
- return list(iter_child_nodes(node))
-
-
-def get_compile_mode(node):
- """
- Get the mode for `compile` of a given node. If the node is not a `mod`
- node (`Expression`, `Module` etc.) a `TypeError` is thrown.
- """
- if not isinstance(node, mod):
- raise TypeError('expected mod node, got %r' % node.__class__.__name__)
- return {
- Expression: 'eval',
- Interactive: 'single'
- }.get(node.__class__, 'expr')
-
-
-def get_docstring(node):
- """
- Return the docstring for the given node or `None` if no docstring can be
- found. If the node provided does not accept docstrings a `TypeError`
- will be raised.
- """
- if not isinstance(node, (FunctionDef, ClassDef, Module)):
- raise TypeError("%r can't have docstrings" % node.__class__.__name__)
- if node.body and isinstance(node.body[0], Str):
- return node.body[0].s
-
-
-def walk(node):
- """
- Iterate over all nodes. This is useful if you only want to modify nodes in
- place and don't care about the context or the order the nodes are returned.
- """
- from collections import deque
- todo = deque([node])
- while todo:
- node = todo.popleft()
- todo.extend(iter_child_nodes(node))
- yield node
-
-
-class NodeVisitor(object):
- """
- Walks the abstract syntax tree and call visitor functions for every node
- found. The visitor functions may return values which will be forwarded
- by the `visit` method.
-
- Per default the visitor functions for the nodes are ``'visit_'`` +
- class name of the node. So a `TryFinally` node visit function would
- be `visit_TryFinally`. This behavior can be changed by overriding
- the `get_visitor` function. If no visitor function exists for a node
- (return value `None`) the `generic_visit` visitor is used instead.
-
- Don't use the `NodeVisitor` if you want to apply changes to nodes during
- traversing. For this a special visitor exists (`NodeTransformer`) that
- allows modifications.
- """
-
- def get_visitor(self, node):
- """
- Return the visitor function for this node or `None` if no visitor
- exists for this node. In that case the generic visit function is
- used instead.
- """
- method = 'visit_' + node.__class__.__name__
- return getattr(self, method, None)
-
- def visit(self, node):
- """Visit a node."""
- f = self.get_visitor(node)
- if f is not None:
- return f(node)
- return self.generic_visit(node)
-
- def generic_visit(self, node):
- """Called if no explicit visitor function exists for a node."""
- for field, value in iter_fields(node):
- if isinstance(value, list):
- for item in value:
- if isinstance(item, AST):
- self.visit(item)
- elif isinstance(value, AST):
- self.visit(value)
-
-
-class NodeTransformer(NodeVisitor):
- """
- Walks the abstract syntax tree and allows modifications of nodes.
-
- The `NodeTransformer` will walk the AST and use the return value of the
- visitor functions to replace or remove the old node. If the return
- value of the visitor function is `None` the node will be removed
- from the previous location otherwise it's replaced with the return
- value. The return value may be the original node in which case no
- replacement takes place.
-
- Here an example transformer that rewrites all `foo` to `data['foo']`::
-
- class RewriteName(NodeTransformer):
-
- def visit_Name(self, node):
- return copy_location(Subscript(
- value=Name(id='data', ctx=Load()),
- slice=Index(value=Str(s=node.id)),
- ctx=node.ctx
- ), node)
-
- Keep in mind that if the node you're operating on has child nodes
- you must either transform the child nodes yourself or call the generic
- visit function for the node first.
-
- Nodes that were part of a collection of statements (that applies to
- all statement nodes) may also return a list of nodes rather than just
- a single node.
-
- Usually you use the transformer like this::
-
- node = YourTransformer().visit(node)
- """
-
- def generic_visit(self, node):
- for field, old_value in iter_fields(node):
- old_value = getattr(node, field, None)
- if isinstance(old_value, list):
- new_values = []
- for value in old_value:
- if isinstance(value, AST):
- value = self.visit(value)
- if value is None:
- continue
- elif not isinstance(value, AST):
- new_values.extend(value)
- continue
- new_values.append(value)
- old_value[:] = new_values
- elif isinstance(old_value, AST):
- new_node = self.visit(old_value)
- if new_node is None:
- delattr(node, field)
- else:
- setattr(node, field, new_node)
- return node
-
-
-class SourceGenerator(NodeVisitor):
- """
- This visitor is able to transform a well formed syntax tree into python
- sourcecode. For more details have a look at the docstring of the
- `node_to_source` function.
- """
-
- def __init__(self, indent_with):
- self.result = []
- self.indent_with = indent_with
- self.indentation = 0
- self.new_lines = 0
-
- def write(self, x):
- if self.new_lines:
- if self.result:
- self.result.append('\n' * self.new_lines)
- self.result.append(self.indent_with * self.indentation)
- self.new_lines = 0
- self.result.append(x)
-
- def newline(self, n=1):
- self.new_lines = max(self.new_lines, n)
-
- def body(self, statements):
- self.new_line = True
- self.indentation += 1
- for stmt in statements:
- self.visit(stmt)
- self.indentation -= 1
-
- def body_or_else(self, node):
- self.body(node.body)
- if node.orelse:
- self.newline()
- self.write('else:')
- self.body(node.orelse)
-
- def signature(self, node):
- want_comma = []
- def write_comma():
- if want_comma:
- self.write(', ')
- else:
- want_comma.append(True)
-
- padding = [None] * (len(node.args) - len(node.defaults))
- for arg, default in zip(node.args, padding + node.defaults):
- write_comma()
- self.visit(arg)
- if default is not None:
- self.write('=')
- self.visit(default)
- if node.vararg is not None:
- write_comma()
- self.write('*' + arg_stringname(node.vararg))
- if node.kwarg is not None:
- write_comma()
- self.write('**' + arg_stringname(node.kwarg))
-
- def decorators(self, node):
- for decorator in node.decorator_list:
- self.newline()
- self.write('@')
- self.visit(decorator)
-
- # Statements
-
- def visit_Assign(self, node):
- self.newline()
- for idx, target in enumerate(node.targets):
- if idx:
- self.write(', ')
- self.visit(target)
- self.write(' = ')
- self.visit(node.value)
-
- def visit_AugAssign(self, node):
- self.newline()
- self.visit(node.target)
- self.write(BINOP_SYMBOLS[type(node.op)] + '=')
- self.visit(node.value)
-
- def visit_ImportFrom(self, node):
- self.newline()
- self.write('from %s%s import ' % ('.' * node.level, node.module))
- for idx, item in enumerate(node.names):
- if idx:
- self.write(', ')
- self.write(item)
-
- def visit_Import(self, node):
- self.newline()
- for item in node.names:
- self.write('import ')
- self.visit(item)
-
- def visit_Expr(self, node):
- self.newline()
- self.generic_visit(node)
-
- def visit_FunctionDef(self, node):
- self.newline(n=2)
- self.decorators(node)
- self.newline()
- self.write('def %s(' % node.name)
- self.signature(node.args)
- self.write('):')
- self.body(node.body)
-
- def visit_ClassDef(self, node):
- have_args = []
- def paren_or_comma():
- if have_args:
- self.write(', ')
- else:
- have_args.append(True)
- self.write('(')
-
- self.newline(n=3)
- self.decorators(node)
- self.newline()
- self.write('class %s' % node.name)
- for base in node.bases:
- paren_or_comma()
- self.visit(base)
- # XXX: the if here is used to keep this module compatible
- # with python 2.6.
- if hasattr(node, 'keywords'):
- for keyword in node.keywords:
- paren_or_comma()
- self.write(keyword.arg + '=')
- self.visit(keyword.value)
- if node.starargs is not None:
- paren_or_comma()
- self.write('*')
- self.visit(node.starargs)
- if node.kwargs is not None:
- paren_or_comma()
- self.write('**')
- self.visit(node.kwargs)
- self.write(have_args and '):' or ':')
- self.body(node.body)
-
- def visit_If(self, node):
- self.newline()
- self.write('if ')
- self.visit(node.test)
- self.write(':')
- self.body(node.body)
- while True:
- else_ = node.orelse
- if len(else_) == 1 and isinstance(else_[0], If):
- node = else_[0]
- self.newline()
- self.write('elif ')
- self.visit(node.test)
- self.write(':')
- self.body(node.body)
- else:
- self.newline()
- self.write('else:')
- self.body(else_)
- break
-
- def visit_For(self, node):
- self.newline()
- self.write('for ')
- self.visit(node.target)
- self.write(' in ')
- self.visit(node.iter)
- self.write(':')
- self.body_or_else(node)
-
- def visit_While(self, node):
- self.newline()
- self.write('while ')
- self.visit(node.test)
- self.write(':')
- self.body_or_else(node)
-
- def visit_With(self, node):
- self.newline()
- self.write('with ')
- self.visit(node.context_expr)
- if node.optional_vars is not None:
- self.write(' as ')
- self.visit(node.optional_vars)
- self.write(':')
- self.body(node.body)
-
- def visit_Pass(self, node):
- self.newline()
- self.write('pass')
-
- def visit_Print(self, node):
- # XXX: python 2.6 only
- self.newline()
- self.write('print ')
- want_comma = False
- if node.dest is not None:
- self.write(' >> ')
- self.visit(node.dest)
- want_comma = True
- for value in node.values:
- if want_comma:
- self.write(', ')
- self.visit(value)
- want_comma = True
- if not node.nl:
- self.write(',')
-
- def visit_Delete(self, node):
- self.newline()
- self.write('del ')
- for idx, target in enumerate(node):
- if idx:
- self.write(', ')
- self.visit(target)
-
- def visit_TryExcept(self, node):
- self.newline()
- self.write('try:')
- self.body(node.body)
- for handler in node.handlers:
- self.visit(handler)
-
- def visit_TryFinally(self, node):
- self.newline()
- self.write('try:')
- self.body(node.body)
- self.newline()
- self.write('finally:')
- self.body(node.finalbody)
-
- def visit_Global(self, node):
- self.newline()
- self.write('global ' + ', '.join(node.names))
-
- def visit_Nonlocal(self, node):
- self.newline()
- self.write('nonlocal ' + ', '.join(node.names))
-
- def visit_Return(self, node):
- self.newline()
- self.write('return ')
- self.visit(node.value)
-
- def visit_Break(self, node):
- self.newline()
- self.write('break')
-
- def visit_Continue(self, node):
- self.newline()
- self.write('continue')
-
- def visit_Raise(self, node):
- # XXX: Python 2.6 / 3.0 compatibility
- self.newline()
- self.write('raise')
- if hasattr(node, 'exc') and node.exc is not None:
- self.write(' ')
- self.visit(node.exc)
- if node.cause is not None:
- self.write(' from ')
- self.visit(node.cause)
- elif hasattr(node, 'type') and node.type is not None:
- self.visit(node.type)
- if node.inst is not None:
- self.write(', ')
- self.visit(node.inst)
- if node.tback is not None:
- self.write(', ')
- self.visit(node.tback)
-
- # Expressions
-
- def visit_Attribute(self, node):
- self.visit(node.value)
- self.write('.' + node.attr)
-
- def visit_Call(self, node):
- want_comma = []
- def write_comma():
- if want_comma:
- self.write(', ')
- else:
- want_comma.append(True)
-
- self.visit(node.func)
- self.write('(')
- for arg in node.args:
- write_comma()
- self.visit(arg)
- for keyword in node.keywords:
- write_comma()
- self.write(keyword.arg + '=')
- self.visit(keyword.value)
- if node.starargs is not None:
- write_comma()
- self.write('*')
- self.visit(node.starargs)
- if node.kwargs is not None:
- write_comma()
- self.write('**')
- self.visit(node.kwargs)
- self.write(')')
-
- def visit_Name(self, node):
- self.write(node.id)
-
- def visit_NameConstant(self, node):
- self.write(str(node.value))
-
- def visit_arg(self, node):
- self.write(node.arg)
-
- def visit_Str(self, node):
- self.write(repr(node.s))
-
- def visit_Bytes(self, node):
- self.write(repr(node.s))
-
- def visit_Num(self, node):
- self.write(repr(node.n))
-
- def visit_Tuple(self, node):
- self.write('(')
- idx = -1
- for idx, item in enumerate(node.elts):
- if idx:
- self.write(', ')
- self.visit(item)
- self.write(idx and ')' or ',)')
-
- def sequence_visit(left, right):
- def visit(self, node):
- self.write(left)
- for idx, item in enumerate(node.elts):
- if idx:
- self.write(', ')
- self.visit(item)
- self.write(right)
- return visit
-
- visit_List = sequence_visit('[', ']')
- visit_Set = sequence_visit('{', '}')
- del sequence_visit
-
- def visit_Dict(self, node):
- self.write('{')
- for idx, (key, value) in enumerate(zip(node.keys, node.values)):
- if idx:
- self.write(', ')
- self.visit(key)
- self.write(': ')
- self.visit(value)
- self.write('}')
-
- def visit_BinOp(self, node):
- self.write('(')
- self.visit(node.left)
- self.write(' %s ' % BINOP_SYMBOLS[type(node.op)])
- self.visit(node.right)
- self.write(')')
-
- def visit_BoolOp(self, node):
- self.write('(')
- for idx, value in enumerate(node.values):
- if idx:
- self.write(' %s ' % BOOLOP_SYMBOLS[type(node.op)])
- self.visit(value)
- self.write(')')
-
- def visit_Compare(self, node):
- self.write('(')
- self.visit(node.left)
- for op, right in zip(node.ops, node.comparators):
- self.write(' %s ' % CMPOP_SYMBOLS[type(op)])
- self.visit(right)
- self.write(')')
-
- def visit_UnaryOp(self, node):
- self.write('(')
- op = UNARYOP_SYMBOLS[type(node.op)]
- self.write(op)
- if op == 'not':
- self.write(' ')
- self.visit(node.operand)
- self.write(')')
-
- def visit_Subscript(self, node):
- self.visit(node.value)
- self.write('[')
- self.visit(node.slice)
- self.write(']')
-
- def visit_Slice(self, node):
- if node.lower is not None:
- self.visit(node.lower)
- self.write(':')
- if node.upper is not None:
- self.visit(node.upper)
- if node.step is not None:
- self.write(':')
- if not (isinstance(node.step, Name) and node.step.id == 'None'):
- self.visit(node.step)
-
- def visit_ExtSlice(self, node):
- for idx, item in node.dims:
- if idx:
- self.write(', ')
- self.visit(item)
-
- def visit_Yield(self, node):
- self.write('yield ')
- self.visit(node.value)
-
- def visit_Lambda(self, node):
- self.write('lambda ')
- self.signature(node.args)
- self.write(': ')
- self.visit(node.body)
-
- def visit_Ellipsis(self, node):
- self.write('Ellipsis')
-
- def generator_visit(left, right):
- def visit(self, node):
- self.write(left)
- self.visit(node.elt)
- for comprehension in node.generators:
- self.visit(comprehension)
- self.write(right)
- return visit
-
- visit_ListComp = generator_visit('[', ']')
- visit_GeneratorExp = generator_visit('(', ')')
- visit_SetComp = generator_visit('{', '}')
- del generator_visit
-
- def visit_DictComp(self, node):
- self.write('{')
- self.visit(node.key)
- self.write(': ')
- self.visit(node.value)
- for comprehension in node.generators:
- self.visit(comprehension)
- self.write('}')
-
- def visit_IfExp(self, node):
- self.visit(node.body)
- self.write(' if ')
- self.visit(node.test)
- self.write(' else ')
- self.visit(node.orelse)
-
- def visit_Starred(self, node):
- self.write('*')
- self.visit(node.value)
-
- def visit_Repr(self, node):
- # XXX: python 2.6 only
- self.write('`')
- self.visit(node.value)
- self.write('`')
-
- # Helper Nodes
-
- def visit_alias(self, node):
- self.write(node.name)
- if node.asname is not None:
- self.write(' as ' + node.asname)
-
- def visit_comprehension(self, node):
- self.write(' for ')
- self.visit(node.target)
- self.write(' in ')
- self.visit(node.iter)
- if node.ifs:
- for if_ in node.ifs:
- self.write(' if ')
- self.visit(if_)
-
- def visit_excepthandler(self, node):
- self.newline()
- self.write('except')
- if node.type is not None:
- self.write(' ')
- self.visit(node.type)
- if node.name is not None:
- self.write(' as ')
- self.visit(node.name)
- self.write(':')
- self.body(node.body)
diff --git a/Darwin/lib/python2.7/site-packages/mako/ast.py b/Darwin/lib/python2.7/site-packages/mako/ast.py
deleted file mode 100644
index f9ae3e1..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/ast.py
+++ /dev/null
@@ -1,152 +0,0 @@
-# mako/ast.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""utilities for analyzing expressions and blocks of Python
-code, as well as generating Python from AST nodes"""
-
-from mako import exceptions, pyparser, compat
-from mako.compat import arg_stringname
-import re
-
-class PythonCode(object):
- """represents information about a string containing Python code"""
- def __init__(self, code, **exception_kwargs):
- self.code = code
-
- # represents all identifiers which are assigned to at some point in
- # the code
- self.declared_identifiers = set()
-
- # represents all identifiers which are referenced before their
- # assignment, if any
- self.undeclared_identifiers = set()
-
- # note that an identifier can be in both the undeclared and declared
- # lists.
-
- # using AST to parse instead of using code.co_varnames,
- # code.co_names has several advantages:
- # - we can locate an identifier as "undeclared" even if
- # its declared later in the same block of code
- # - AST is less likely to break with version changes
- # (for example, the behavior of co_names changed a little bit
- # in python version 2.5)
- if isinstance(code, compat.string_types):
- expr = pyparser.parse(code.lstrip(), "exec", **exception_kwargs)
- else:
- expr = code
-
- f = pyparser.FindIdentifiers(self, **exception_kwargs)
- f.visit(expr)
-
-class ArgumentList(object):
- """parses a fragment of code as a comma-separated list of expressions"""
- def __init__(self, code, **exception_kwargs):
- self.codeargs = []
- self.args = []
- self.declared_identifiers = set()
- self.undeclared_identifiers = set()
- if isinstance(code, compat.string_types):
- if re.match(r"\S", code) and not re.match(r",\s*$", code):
- # if theres text and no trailing comma, insure its parsed
- # as a tuple by adding a trailing comma
- code += ","
- expr = pyparser.parse(code, "exec", **exception_kwargs)
- else:
- expr = code
-
- f = pyparser.FindTuple(self, PythonCode, **exception_kwargs)
- f.visit(expr)
-
-class PythonFragment(PythonCode):
- """extends PythonCode to provide identifier lookups in partial control
- statements
-
- e.g.
- for x in 5:
- elif y==9:
- except (MyException, e):
- etc.
- """
- def __init__(self, code, **exception_kwargs):
- m = re.match(r'^(\w+)(?:\s+(.*?))?:\s*(#|$)', code.strip(), re.S)
- if not m:
- raise exceptions.CompileException(
- "Fragment '%s' is not a partial control statement" %
- code, **exception_kwargs)
- if m.group(3):
- code = code[:m.start(3)]
- (keyword, expr) = m.group(1,2)
- if keyword in ['for','if', 'while']:
- code = code + "pass"
- elif keyword == 'try':
- code = code + "pass\nexcept:pass"
- elif keyword == 'elif' or keyword == 'else':
- code = "if False:pass\n" + code + "pass"
- elif keyword == 'except':
- code = "try:pass\n" + code + "pass"
- elif keyword == 'with':
- code = code + "pass"
- else:
- raise exceptions.CompileException(
- "Unsupported control keyword: '%s'" %
- keyword, **exception_kwargs)
- super(PythonFragment, self).__init__(code, **exception_kwargs)
-
-
-class FunctionDecl(object):
- """function declaration"""
- def __init__(self, code, allow_kwargs=True, **exception_kwargs):
- self.code = code
- expr = pyparser.parse(code, "exec", **exception_kwargs)
-
- f = pyparser.ParseFunc(self, **exception_kwargs)
- f.visit(expr)
- if not hasattr(self, 'funcname'):
- raise exceptions.CompileException(
- "Code '%s' is not a function declaration" % code,
- **exception_kwargs)
- if not allow_kwargs and self.kwargs:
- raise exceptions.CompileException(
- "'**%s' keyword argument not allowed here" %
- self.argnames[-1], **exception_kwargs)
-
- def get_argument_expressions(self, include_defaults=True):
- """return the argument declarations of this FunctionDecl as a printable
- list."""
-
- namedecls = []
- defaults = [d for d in self.defaults]
- kwargs = self.kwargs
- varargs = self.varargs
- argnames = [f for f in self.argnames]
- argnames.reverse()
- for arg in argnames:
- default = None
- if kwargs:
- arg = "**" + arg_stringname(arg)
- kwargs = False
- elif varargs:
- arg = "*" + arg_stringname(arg)
- varargs = False
- else:
- default = len(defaults) and defaults.pop() or None
- if include_defaults and default:
- namedecls.insert(0, "%s=%s" %
- (arg,
- pyparser.ExpressionGenerator(default).value()
- )
- )
- else:
- namedecls.insert(0, arg)
- return namedecls
-
-class FunctionArgs(FunctionDecl):
- """the argument portion of a function declaration"""
-
- def __init__(self, code, **kwargs):
- super(FunctionArgs, self).__init__("def ANON(%s):pass" % code,
- **kwargs)
diff --git a/Darwin/lib/python2.7/site-packages/mako/cache.py b/Darwin/lib/python2.7/site-packages/mako/cache.py
deleted file mode 100644
index 4433040..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/cache.py
+++ /dev/null
@@ -1,236 +0,0 @@
-# mako/cache.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-from mako import compat, util
-
-_cache_plugins = util.PluginLoader("mako.cache")
-
-register_plugin = _cache_plugins.register
-register_plugin("beaker", "mako.ext.beaker_cache", "BeakerCacheImpl")
-
-
-class Cache(object):
- """Represents a data content cache made available to the module
- space of a specific :class:`.Template` object.
-
- .. versionadded:: 0.6
- :class:`.Cache` by itself is mostly a
- container for a :class:`.CacheImpl` object, which implements
- a fixed API to provide caching services; specific subclasses exist to
- implement different
- caching strategies. Mako includes a backend that works with
- the Beaker caching system. Beaker itself then supports
- a number of backends (i.e. file, memory, memcached, etc.)
-
- The construction of a :class:`.Cache` is part of the mechanics
- of a :class:`.Template`, and programmatic access to this
- cache is typically via the :attr:`.Template.cache` attribute.
-
- """
-
- impl = None
- """Provide the :class:`.CacheImpl` in use by this :class:`.Cache`.
-
- This accessor allows a :class:`.CacheImpl` with additional
- methods beyond that of :class:`.Cache` to be used programmatically.
-
- """
-
- id = None
- """Return the 'id' that identifies this cache.
-
- This is a value that should be globally unique to the
- :class:`.Template` associated with this cache, and can
- be used by a caching system to name a local container
- for data specific to this template.
-
- """
-
- starttime = None
- """Epochal time value for when the owning :class:`.Template` was
- first compiled.
-
- A cache implementation may wish to invalidate data earlier than
- this timestamp; this has the effect of the cache for a specific
- :class:`.Template` starting clean any time the :class:`.Template`
- is recompiled, such as when the original template file changed on
- the filesystem.
-
- """
-
- def __init__(self, template, *args):
- # check for a stale template calling the
- # constructor
- if isinstance(template, compat.string_types) and args:
- return
- self.template = template
- self.id = template.module.__name__
- self.starttime = template.module._modified_time
- self._def_regions = {}
- self.impl = self._load_impl(self.template.cache_impl)
-
- def _load_impl(self, name):
- return _cache_plugins.load(name)(self)
-
- def get_or_create(self, key, creation_function, **kw):
- """Retrieve a value from the cache, using the given creation function
- to generate a new value."""
-
- return self._ctx_get_or_create(key, creation_function, None, **kw)
-
- def _ctx_get_or_create(self, key, creation_function, context, **kw):
- """Retrieve a value from the cache, using the given creation function
- to generate a new value."""
-
- if not self.template.cache_enabled:
- return creation_function()
-
- return self.impl.get_or_create(key,
- creation_function,
- **self._get_cache_kw(kw, context))
-
- def set(self, key, value, **kw):
- """Place a value in the cache.
-
- :param key: the value's key.
- :param value: the value.
- :param \**kw: cache configuration arguments.
-
- """
-
- self.impl.set(key, value, **self._get_cache_kw(kw, None))
-
- put = set
- """A synonym for :meth:`.Cache.set`.
-
- This is here for backwards compatibility.
-
- """
-
- def get(self, key, **kw):
- """Retrieve a value from the cache.
-
- :param key: the value's key.
- :param \**kw: cache configuration arguments. The
- backend is configured using these arguments upon first request.
- Subsequent requests that use the same series of configuration
- values will use that same backend.
-
- """
- return self.impl.get(key, **self._get_cache_kw(kw, None))
-
- def invalidate(self, key, **kw):
- """Invalidate a value in the cache.
-
- :param key: the value's key.
- :param \**kw: cache configuration arguments. The
- backend is configured using these arguments upon first request.
- Subsequent requests that use the same series of configuration
- values will use that same backend.
-
- """
- self.impl.invalidate(key, **self._get_cache_kw(kw, None))
-
- def invalidate_body(self):
- """Invalidate the cached content of the "body" method for this
- template.
-
- """
- self.invalidate('render_body', __M_defname='render_body')
-
- def invalidate_def(self, name):
- """Invalidate the cached content of a particular ``<%def>`` within this
- template.
-
- """
-
- self.invalidate('render_%s' % name, __M_defname='render_%s' % name)
-
- def invalidate_closure(self, name):
- """Invalidate a nested ``<%def>`` within this template.
-
- Caching of nested defs is a blunt tool as there is no
- management of scope -- nested defs that use cache tags
- need to have names unique of all other nested defs in the
- template, else their content will be overwritten by
- each other.
-
- """
-
- self.invalidate(name, __M_defname=name)
-
- def _get_cache_kw(self, kw, context):
- defname = kw.pop('__M_defname', None)
- if not defname:
- tmpl_kw = self.template.cache_args.copy()
- tmpl_kw.update(kw)
- elif defname in self._def_regions:
- tmpl_kw = self._def_regions[defname]
- else:
- tmpl_kw = self.template.cache_args.copy()
- tmpl_kw.update(kw)
- self._def_regions[defname] = tmpl_kw
- if context and self.impl.pass_context:
- tmpl_kw = tmpl_kw.copy()
- tmpl_kw.setdefault('context', context)
- return tmpl_kw
-
-class CacheImpl(object):
- """Provide a cache implementation for use by :class:`.Cache`."""
-
- def __init__(self, cache):
- self.cache = cache
-
- pass_context = False
- """If ``True``, the :class:`.Context` will be passed to
- :meth:`get_or_create <.CacheImpl.get_or_create>` as the name ``'context'``.
- """
-
- def get_or_create(self, key, creation_function, **kw):
- """Retrieve a value from the cache, using the given creation function
- to generate a new value.
-
- This function *must* return a value, either from
- the cache, or via the given creation function.
- If the creation function is called, the newly
- created value should be populated into the cache
- under the given key before being returned.
-
- :param key: the value's key.
- :param creation_function: function that when called generates
- a new value.
- :param \**kw: cache configuration arguments.
-
- """
- raise NotImplementedError()
-
- def set(self, key, value, **kw):
- """Place a value in the cache.
-
- :param key: the value's key.
- :param value: the value.
- :param \**kw: cache configuration arguments.
-
- """
- raise NotImplementedError()
-
- def get(self, key, **kw):
- """Retrieve a value from the cache.
-
- :param key: the value's key.
- :param \**kw: cache configuration arguments.
-
- """
- raise NotImplementedError()
-
- def invalidate(self, key, **kw):
- """Invalidate a value in the cache.
-
- :param key: the value's key.
- :param \**kw: cache configuration arguments.
-
- """
- raise NotImplementedError()
diff --git a/Darwin/lib/python2.7/site-packages/mako/codegen.py b/Darwin/lib/python2.7/site-packages/mako/codegen.py
deleted file mode 100644
index 2779a6d..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/codegen.py
+++ /dev/null
@@ -1,1222 +0,0 @@
-# mako/codegen.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""provides functionality for rendering a parsetree constructing into module
-source code."""
-
-import time
-import re
-from mako.pygen import PythonPrinter
-from mako import util, ast, parsetree, filters, exceptions
-from mako import compat
-
-
-MAGIC_NUMBER = 9
-
-# names which are hardwired into the
-# template and are not accessed via the
-# context itself
-RESERVED_NAMES = set(['context', 'loop', 'UNDEFINED'])
-
-def compile(node,
- uri,
- filename=None,
- default_filters=None,
- buffer_filters=None,
- imports=None,
- future_imports=None,
- source_encoding=None,
- generate_magic_comment=True,
- disable_unicode=False,
- strict_undefined=False,
- enable_loop=True,
- reserved_names=frozenset()):
-
- """Generate module source code given a parsetree node,
- uri, and optional source filename"""
-
- # if on Py2K, push the "source_encoding" string to be
- # a bytestring itself, as we will be embedding it into
- # the generated source and we don't want to coerce the
- # result into a unicode object, in "disable_unicode" mode
- if not compat.py3k and isinstance(source_encoding, compat.text_type):
- source_encoding = source_encoding.encode(source_encoding)
-
-
- buf = util.FastEncodingBuffer()
-
- printer = PythonPrinter(buf)
- _GenerateRenderMethod(printer,
- _CompileContext(uri,
- filename,
- default_filters,
- buffer_filters,
- imports,
- future_imports,
- source_encoding,
- generate_magic_comment,
- disable_unicode,
- strict_undefined,
- enable_loop,
- reserved_names),
- node)
- return buf.getvalue()
-
-class _CompileContext(object):
- def __init__(self,
- uri,
- filename,
- default_filters,
- buffer_filters,
- imports,
- future_imports,
- source_encoding,
- generate_magic_comment,
- disable_unicode,
- strict_undefined,
- enable_loop,
- reserved_names):
- self.uri = uri
- self.filename = filename
- self.default_filters = default_filters
- self.buffer_filters = buffer_filters
- self.imports = imports
- self.future_imports = future_imports
- self.source_encoding = source_encoding
- self.generate_magic_comment = generate_magic_comment
- self.disable_unicode = disable_unicode
- self.strict_undefined = strict_undefined
- self.enable_loop = enable_loop
- self.reserved_names = reserved_names
-
-class _GenerateRenderMethod(object):
- """A template visitor object which generates the
- full module source for a template.
-
- """
- def __init__(self, printer, compiler, node):
- self.printer = printer
- self.last_source_line = -1
- self.compiler = compiler
- self.node = node
- self.identifier_stack = [None]
- self.in_def = isinstance(node, (parsetree.DefTag, parsetree.BlockTag))
-
- if self.in_def:
- name = "render_%s" % node.funcname
- args = node.get_argument_expressions()
- filtered = len(node.filter_args.args) > 0
- buffered = eval(node.attributes.get('buffered', 'False'))
- cached = eval(node.attributes.get('cached', 'False'))
- defs = None
- pagetag = None
- if node.is_block and not node.is_anonymous:
- args += ['**pageargs']
- else:
- defs = self.write_toplevel()
- pagetag = self.compiler.pagetag
- name = "render_body"
- if pagetag is not None:
- args = pagetag.body_decl.get_argument_expressions()
- if not pagetag.body_decl.kwargs:
- args += ['**pageargs']
- cached = eval(pagetag.attributes.get('cached', 'False'))
- self.compiler.enable_loop = self.compiler.enable_loop or eval(
- pagetag.attributes.get(
- 'enable_loop', 'False')
- )
- else:
- args = ['**pageargs']
- cached = False
- buffered = filtered = False
- if args is None:
- args = ['context']
- else:
- args = [a for a in ['context'] + args]
-
- self.write_render_callable(
- pagetag or node,
- name, args,
- buffered, filtered, cached)
-
- if defs is not None:
- for node in defs:
- _GenerateRenderMethod(printer, compiler, node)
-
- @property
- def identifiers(self):
- return self.identifier_stack[-1]
-
- def write_toplevel(self):
- """Traverse a template structure for module-level directives and
- generate the start of module-level code.
-
- """
- inherit = []
- namespaces = {}
- module_code = []
-
- self.compiler.pagetag = None
-
- class FindTopLevel(object):
- def visitInheritTag(s, node):
- inherit.append(node)
- def visitNamespaceTag(s, node):
- namespaces[node.name] = node
- def visitPageTag(s, node):
- self.compiler.pagetag = node
- def visitCode(s, node):
- if node.ismodule:
- module_code.append(node)
-
- f = FindTopLevel()
- for n in self.node.nodes:
- n.accept_visitor(f)
-
- self.compiler.namespaces = namespaces
-
- module_ident = set()
- for n in module_code:
- module_ident = module_ident.union(n.declared_identifiers())
-
- module_identifiers = _Identifiers(self.compiler)
- module_identifiers.declared = module_ident
-
- # module-level names, python code
- if self.compiler.generate_magic_comment and \
- self.compiler.source_encoding:
- self.printer.writeline("# -*- coding:%s -*-" %
- self.compiler.source_encoding)
-
- if self.compiler.future_imports:
- self.printer.writeline("from __future__ import %s" %
- (", ".join(self.compiler.future_imports),))
- self.printer.writeline("from mako import runtime, filters, cache")
- self.printer.writeline("UNDEFINED = runtime.UNDEFINED")
- self.printer.writeline("__M_dict_builtin = dict")
- self.printer.writeline("__M_locals_builtin = locals")
- self.printer.writeline("_magic_number = %r" % MAGIC_NUMBER)
- self.printer.writeline("_modified_time = %r" % time.time())
- self.printer.writeline("_enable_loop = %r" % self.compiler.enable_loop)
- self.printer.writeline(
- "_template_filename = %r" % self.compiler.filename)
- self.printer.writeline("_template_uri = %r" % self.compiler.uri)
- self.printer.writeline(
- "_source_encoding = %r" % self.compiler.source_encoding)
- if self.compiler.imports:
- buf = ''
- for imp in self.compiler.imports:
- buf += imp + "\n"
- self.printer.writeline(imp)
- impcode = ast.PythonCode(
- buf,
- source='', lineno=0,
- pos=0,
- filename='template defined imports')
- else:
- impcode = None
-
- main_identifiers = module_identifiers.branch(self.node)
- module_identifiers.topleveldefs = \
- module_identifiers.topleveldefs.\
- union(main_identifiers.topleveldefs)
- module_identifiers.declared.add("UNDEFINED")
- if impcode:
- module_identifiers.declared.update(impcode.declared_identifiers)
-
- self.compiler.identifiers = module_identifiers
- self.printer.writeline("_exports = %r" %
- [n.name for n in
- main_identifiers.topleveldefs.values()]
- )
- self.printer.write("\n\n")
-
- if len(module_code):
- self.write_module_code(module_code)
-
- if len(inherit):
- self.write_namespaces(namespaces)
- self.write_inherit(inherit[-1])
- elif len(namespaces):
- self.write_namespaces(namespaces)
-
- return list(main_identifiers.topleveldefs.values())
-
- def write_render_callable(self, node, name, args, buffered, filtered,
- cached):
- """write a top-level render callable.
-
- this could be the main render() method or that of a top-level def."""
-
- if self.in_def:
- decorator = node.decorator
- if decorator:
- self.printer.writeline(
- "@runtime._decorate_toplevel(%s)" % decorator)
-
- self.printer.writelines(
- "def %s(%s):" % (name, ','.join(args)),
- # push new frame, assign current frame to __M_caller
- "__M_caller = context.caller_stack._push_frame()",
- "try:"
- )
- if buffered or filtered or cached:
- self.printer.writeline("context._push_buffer()")
-
- self.identifier_stack.append(
- self.compiler.identifiers.branch(self.node))
- if (not self.in_def or self.node.is_block) and '**pageargs' in args:
- self.identifier_stack[-1].argument_declared.add('pageargs')
-
- if not self.in_def and (
- len(self.identifiers.locally_assigned) > 0 or
- len(self.identifiers.argument_declared) > 0
- ):
- self.printer.writeline("__M_locals = __M_dict_builtin(%s)" %
- ','.join([
- "%s=%s" % (x, x) for x in
- self.identifiers.argument_declared
- ]))
-
- self.write_variable_declares(self.identifiers, toplevel=True)
-
- for n in self.node.nodes:
- n.accept_visitor(self)
-
- self.write_def_finish(self.node, buffered, filtered, cached)
- self.printer.writeline(None)
- self.printer.write("\n\n")
- if cached:
- self.write_cache_decorator(
- node, name,
- args, buffered,
- self.identifiers, toplevel=True)
-
- def write_module_code(self, module_code):
- """write module-level template code, i.e. that which
- is enclosed in <%! %> tags in the template."""
- for n in module_code:
- self.write_source_comment(n)
- self.printer.write_indented_block(n.text)
-
- def write_inherit(self, node):
- """write the module-level inheritance-determination callable."""
-
- self.printer.writelines(
- "def _mako_inherit(template, context):",
- "_mako_generate_namespaces(context)",
- "return runtime._inherit_from(context, %s, _template_uri)" %
- (node.parsed_attributes['file']),
- None
- )
-
- def write_namespaces(self, namespaces):
- """write the module-level namespace-generating callable."""
- self.printer.writelines(
- "def _mako_get_namespace(context, name):",
- "try:",
- "return context.namespaces[(__name__, name)]",
- "except KeyError:",
- "_mako_generate_namespaces(context)",
- "return context.namespaces[(__name__, name)]",
- None, None
- )
- self.printer.writeline("def _mako_generate_namespaces(context):")
-
-
- for node in namespaces.values():
- if 'import' in node.attributes:
- self.compiler.has_ns_imports = True
- self.write_source_comment(node)
- if len(node.nodes):
- self.printer.writeline("def make_namespace():")
- export = []
- identifiers = self.compiler.identifiers.branch(node)
- self.in_def = True
- class NSDefVisitor(object):
- def visitDefTag(s, node):
- s.visitDefOrBase(node)
-
- def visitBlockTag(s, node):
- s.visitDefOrBase(node)
-
- def visitDefOrBase(s, node):
- if node.is_anonymous:
- raise exceptions.CompileException(
- "Can't put anonymous blocks inside "
- "<%namespace>",
- **node.exception_kwargs
- )
- self.write_inline_def(node, identifiers, nested=False)
- export.append(node.funcname)
- vis = NSDefVisitor()
- for n in node.nodes:
- n.accept_visitor(vis)
- self.printer.writeline("return [%s]" % (','.join(export)))
- self.printer.writeline(None)
- self.in_def = False
- callable_name = "make_namespace()"
- else:
- callable_name = "None"
-
- if 'file' in node.parsed_attributes:
- self.printer.writeline(
- "ns = runtime.TemplateNamespace(%r,"
- " context._clean_inheritance_tokens(),"
- " templateuri=%s, callables=%s, "
- " calling_uri=_template_uri)" %
- (
- node.name,
- node.parsed_attributes.get('file', 'None'),
- callable_name,
- )
- )
- elif 'module' in node.parsed_attributes:
- self.printer.writeline(
- "ns = runtime.ModuleNamespace(%r,"
- " context._clean_inheritance_tokens(),"
- " callables=%s, calling_uri=_template_uri,"
- " module=%s)" %
- (
- node.name,
- callable_name,
- node.parsed_attributes.get('module', 'None')
- )
- )
- else:
- self.printer.writeline(
- "ns = runtime.Namespace(%r,"
- " context._clean_inheritance_tokens(),"
- " callables=%s, calling_uri=_template_uri)" %
- (
- node.name,
- callable_name,
- )
- )
- if eval(node.attributes.get('inheritable', "False")):
- self.printer.writeline("context['self'].%s = ns" % (node.name))
-
- self.printer.writeline(
- "context.namespaces[(__name__, %s)] = ns" % repr(node.name))
- self.printer.write("\n")
- if not len(namespaces):
- self.printer.writeline("pass")
- self.printer.writeline(None)
-
- def write_variable_declares(self, identifiers, toplevel=False, limit=None):
- """write variable declarations at the top of a function.
-
- the variable declarations are in the form of callable
- definitions for defs and/or name lookup within the
- function's context argument. the names declared are based
- on the names that are referenced in the function body,
- which don't otherwise have any explicit assignment
- operation. names that are assigned within the body are
- assumed to be locally-scoped variables and are not
- separately declared.
-
- for def callable definitions, if the def is a top-level
- callable then a 'stub' callable is generated which wraps
- the current Context into a closure. if the def is not
- top-level, it is fully rendered as a local closure.
-
- """
-
- # collection of all defs available to us in this scope
- comp_idents = dict([(c.funcname, c) for c in identifiers.defs])
- to_write = set()
-
- # write "context.get()" for all variables we are going to
- # need that arent in the namespace yet
- to_write = to_write.union(identifiers.undeclared)
-
- # write closure functions for closures that we define
- # right here
- to_write = to_write.union(
- [c.funcname for c in identifiers.closuredefs.values()])
-
- # remove identifiers that are declared in the argument
- # signature of the callable
- to_write = to_write.difference(identifiers.argument_declared)
-
- # remove identifiers that we are going to assign to.
- # in this way we mimic Python's behavior,
- # i.e. assignment to a variable within a block
- # means that variable is now a "locally declared" var,
- # which cannot be referenced beforehand.
- to_write = to_write.difference(identifiers.locally_declared)
-
- if self.compiler.enable_loop:
- has_loop = "loop" in to_write
- to_write.discard("loop")
- else:
- has_loop = False
-
- # if a limiting set was sent, constraint to those items in that list
- # (this is used for the caching decorator)
- if limit is not None:
- to_write = to_write.intersection(limit)
-
- if toplevel and getattr(self.compiler, 'has_ns_imports', False):
- self.printer.writeline("_import_ns = {}")
- self.compiler.has_imports = True
- for ident, ns in self.compiler.namespaces.items():
- if 'import' in ns.attributes:
- self.printer.writeline(
- "_mako_get_namespace(context, %r)."\
- "_populate(_import_ns, %r)" %
- (
- ident,
- re.split(r'\s*,\s*', ns.attributes['import'])
- ))
-
- if has_loop:
- self.printer.writeline(
- 'loop = __M_loop = runtime.LoopStack()'
- )
-
- for ident in to_write:
- if ident in comp_idents:
- comp = comp_idents[ident]
- if comp.is_block:
- if not comp.is_anonymous:
- self.write_def_decl(comp, identifiers)
- else:
- self.write_inline_def(comp, identifiers, nested=True)
- else:
- if comp.is_root():
- self.write_def_decl(comp, identifiers)
- else:
- self.write_inline_def(comp, identifiers, nested=True)
-
- elif ident in self.compiler.namespaces:
- self.printer.writeline(
- "%s = _mako_get_namespace(context, %r)" %
- (ident, ident)
- )
- else:
- if getattr(self.compiler, 'has_ns_imports', False):
- if self.compiler.strict_undefined:
- self.printer.writelines(
- "%s = _import_ns.get(%r, UNDEFINED)" %
- (ident, ident),
- "if %s is UNDEFINED:" % ident,
- "try:",
- "%s = context[%r]" % (ident, ident),
- "except KeyError:",
- "raise NameError(\"'%s' is not defined\")" %
- ident,
- None, None
- )
- else:
- self.printer.writeline(
- "%s = _import_ns.get(%r, context.get(%r, UNDEFINED))" %
- (ident, ident, ident))
- else:
- if self.compiler.strict_undefined:
- self.printer.writelines(
- "try:",
- "%s = context[%r]" % (ident, ident),
- "except KeyError:",
- "raise NameError(\"'%s' is not defined\")" %
- ident,
- None
- )
- else:
- self.printer.writeline(
- "%s = context.get(%r, UNDEFINED)" % (ident, ident)
- )
-
- self.printer.writeline("__M_writer = context.writer()")
-
- def write_source_comment(self, node):
- """write a source comment containing the line number of the
- corresponding template line."""
- if self.last_source_line != node.lineno:
- self.printer.writeline("# SOURCE LINE %d" % node.lineno)
- self.last_source_line = node.lineno
-
- def write_def_decl(self, node, identifiers):
- """write a locally-available callable referencing a top-level def"""
- funcname = node.funcname
- namedecls = node.get_argument_expressions()
- nameargs = node.get_argument_expressions(include_defaults=False)
-
- if not self.in_def and (
- len(self.identifiers.locally_assigned) > 0 or
- len(self.identifiers.argument_declared) > 0):
- nameargs.insert(0, 'context._locals(__M_locals)')
- else:
- nameargs.insert(0, 'context')
- self.printer.writeline("def %s(%s):" % (funcname, ",".join(namedecls)))
- self.printer.writeline(
- "return render_%s(%s)" % (funcname, ",".join(nameargs)))
- self.printer.writeline(None)
-
- def write_inline_def(self, node, identifiers, nested):
- """write a locally-available def callable inside an enclosing def."""
-
- namedecls = node.get_argument_expressions()
-
- decorator = node.decorator
- if decorator:
- self.printer.writeline(
- "@runtime._decorate_inline(context, %s)" % decorator)
- self.printer.writeline(
- "def %s(%s):" % (node.funcname, ",".join(namedecls)))
- filtered = len(node.filter_args.args) > 0
- buffered = eval(node.attributes.get('buffered', 'False'))
- cached = eval(node.attributes.get('cached', 'False'))
- self.printer.writelines(
- # push new frame, assign current frame to __M_caller
- "__M_caller = context.caller_stack._push_frame()",
- "try:"
- )
- if buffered or filtered or cached:
- self.printer.writelines(
- "context._push_buffer()",
- )
-
- identifiers = identifiers.branch(node, nested=nested)
-
- self.write_variable_declares(identifiers)
-
- self.identifier_stack.append(identifiers)
- for n in node.nodes:
- n.accept_visitor(self)
- self.identifier_stack.pop()
-
- self.write_def_finish(node, buffered, filtered, cached)
- self.printer.writeline(None)
- if cached:
- self.write_cache_decorator(node, node.funcname,
- namedecls, False, identifiers,
- inline=True, toplevel=False)
-
- def write_def_finish(self, node, buffered, filtered, cached,
- callstack=True):
- """write the end section of a rendering function, either outermost or
- inline.
-
- this takes into account if the rendering function was filtered,
- buffered, etc. and closes the corresponding try: block if any, and
- writes code to retrieve captured content, apply filters, send proper
- return value."""
-
- if not buffered and not cached and not filtered:
- self.printer.writeline("return ''")
- if callstack:
- self.printer.writelines(
- "finally:",
- "context.caller_stack._pop_frame()",
- None
- )
-
- if buffered or filtered or cached:
- if buffered or cached:
- # in a caching scenario, don't try to get a writer
- # from the context after popping; assume the caching
- # implemenation might be using a context with no
- # extra buffers
- self.printer.writelines(
- "finally:",
- "__M_buf = context._pop_buffer()"
- )
- else:
- self.printer.writelines(
- "finally:",
- "__M_buf, __M_writer = context._pop_buffer_and_writer()"
- )
-
- if callstack:
- self.printer.writeline("context.caller_stack._pop_frame()")
-
- s = "__M_buf.getvalue()"
- if filtered:
- s = self.create_filter_callable(node.filter_args.args, s,
- False)
- self.printer.writeline(None)
- if buffered and not cached:
- s = self.create_filter_callable(self.compiler.buffer_filters,
- s, False)
- if buffered or cached:
- self.printer.writeline("return %s" % s)
- else:
- self.printer.writelines(
- "__M_writer(%s)" % s,
- "return ''"
- )
-
- def write_cache_decorator(self, node_or_pagetag, name,
- args, buffered, identifiers,
- inline=False, toplevel=False):
- """write a post-function decorator to replace a rendering
- callable with a cached version of itself."""
-
- self.printer.writeline("__M_%s = %s" % (name, name))
- cachekey = node_or_pagetag.parsed_attributes.get('cache_key',
- repr(name))
-
- cache_args = {}
- if self.compiler.pagetag is not None:
- cache_args.update(
- (
- pa[6:],
- self.compiler.pagetag.parsed_attributes[pa]
- )
- for pa in self.compiler.pagetag.parsed_attributes
- if pa.startswith('cache_') and pa != 'cache_key'
- )
- cache_args.update(
- (
- pa[6:],
- node_or_pagetag.parsed_attributes[pa]
- ) for pa in node_or_pagetag.parsed_attributes
- if pa.startswith('cache_') and pa != 'cache_key'
- )
- if 'timeout' in cache_args:
- cache_args['timeout'] = int(eval(cache_args['timeout']))
-
- self.printer.writeline("def %s(%s):" % (name, ','.join(args)))
-
- # form "arg1, arg2, arg3=arg3, arg4=arg4", etc.
- pass_args = [
- '=' in a and "%s=%s" % ((a.split('=')[0],)*2) or a
- for a in args
- ]
-
- self.write_variable_declares(
- identifiers,
- toplevel=toplevel,
- limit=node_or_pagetag.undeclared_identifiers()
- )
- if buffered:
- s = "context.get('local')."\
- "cache._ctx_get_or_create("\
- "%s, lambda:__M_%s(%s), context, %s__M_defname=%r)" % \
- (cachekey, name, ','.join(pass_args),
- ''.join(["%s=%s, " % (k, v)
- for k, v in cache_args.items()]),
- name
- )
- # apply buffer_filters
- s = self.create_filter_callable(self.compiler.buffer_filters, s,
- False)
- self.printer.writelines("return " + s, None)
- else:
- self.printer.writelines(
- "__M_writer(context.get('local')."
- "cache._ctx_get_or_create("\
- "%s, lambda:__M_%s(%s), context, %s__M_defname=%r))" %
- (cachekey, name, ','.join(pass_args),
- ''.join(["%s=%s, " % (k, v)
- for k, v in cache_args.items()]),
- name,
- ),
- "return ''",
- None
- )
-
- def create_filter_callable(self, args, target, is_expression):
- """write a filter-applying expression based on the filters
- present in the given filter names, adjusting for the global
- 'default' filter aliases as needed."""
-
- def locate_encode(name):
- if re.match(r'decode\..+', name):
- return "filters." + name
- elif self.compiler.disable_unicode:
- return filters.NON_UNICODE_ESCAPES.get(name, name)
- else:
- return filters.DEFAULT_ESCAPES.get(name, name)
-
- if 'n' not in args:
- if is_expression:
- if self.compiler.pagetag:
- args = self.compiler.pagetag.filter_args.args + args
- if self.compiler.default_filters:
- args = self.compiler.default_filters + args
- for e in args:
- # if filter given as a function, get just the identifier portion
- if e == 'n':
- continue
- m = re.match(r'(.+?)(\(.*\))', e)
- if m:
- (ident, fargs) = m.group(1,2)
- f = locate_encode(ident)
- e = f + fargs
- else:
- x = e
- e = locate_encode(e)
- assert e is not None
- target = "%s(%s)" % (e, target)
- return target
-
- def visitExpression(self, node):
- self.write_source_comment(node)
- if len(node.escapes) or \
- (
- self.compiler.pagetag is not None and
- len(self.compiler.pagetag.filter_args.args)
- ) or \
- len(self.compiler.default_filters):
-
- s = self.create_filter_callable(node.escapes_code.args,
- "%s" % node.text, True)
- self.printer.writeline("__M_writer(%s)" % s)
- else:
- self.printer.writeline("__M_writer(%s)" % node.text)
-
- def visitControlLine(self, node):
- if node.isend:
- self.printer.writeline(None)
- if node.has_loop_context:
- self.printer.writeline('finally:')
- self.printer.writeline("loop = __M_loop._exit()")
- self.printer.writeline(None)
- else:
- self.write_source_comment(node)
- if self.compiler.enable_loop and node.keyword == 'for':
- text = mangle_mako_loop(node, self.printer)
- else:
- text = node.text
- self.printer.writeline(text)
- children = node.get_children()
- # this covers the three situations where we want to insert a pass:
- # 1) a ternary control line with no children,
- # 2) a primary control line with nothing but its own ternary
- # and end control lines, and
- # 3) any control line with no content other than comments
- if not children or (
- compat.all(isinstance(c, (parsetree.Comment,
- parsetree.ControlLine))
- for c in children) and
- compat.all((node.is_ternary(c.keyword) or c.isend)
- for c in children
- if isinstance(c, parsetree.ControlLine))):
- self.printer.writeline("pass")
-
- def visitText(self, node):
- self.write_source_comment(node)
- self.printer.writeline("__M_writer(%s)" % repr(node.content))
-
- def visitTextTag(self, node):
- filtered = len(node.filter_args.args) > 0
- if filtered:
- self.printer.writelines(
- "__M_writer = context._push_writer()",
- "try:",
- )
- for n in node.nodes:
- n.accept_visitor(self)
- if filtered:
- self.printer.writelines(
- "finally:",
- "__M_buf, __M_writer = context._pop_buffer_and_writer()",
- "__M_writer(%s)" %
- self.create_filter_callable(
- node.filter_args.args,
- "__M_buf.getvalue()",
- False),
- None
- )
-
- def visitCode(self, node):
- if not node.ismodule:
- self.write_source_comment(node)
- self.printer.write_indented_block(node.text)
-
- if not self.in_def and len(self.identifiers.locally_assigned) > 0:
- # if we are the "template" def, fudge locally
- # declared/modified variables into the "__M_locals" dictionary,
- # which is used for def calls within the same template,
- # to simulate "enclosing scope"
- self.printer.writeline(
- '__M_locals_builtin_stored = __M_locals_builtin()')
- self.printer.writeline(
- '__M_locals.update(__M_dict_builtin([(__M_key,'
- ' __M_locals_builtin_stored[__M_key]) for __M_key in'
- ' [%s] if __M_key in __M_locals_builtin_stored]))' %
- ','.join([repr(x) for x in node.declared_identifiers()]))
-
- def visitIncludeTag(self, node):
- self.write_source_comment(node)
- args = node.attributes.get('args')
- if args:
- self.printer.writeline(
- "runtime._include_file(context, %s, _template_uri, %s)" %
- (node.parsed_attributes['file'], args))
- else:
- self.printer.writeline(
- "runtime._include_file(context, %s, _template_uri)" %
- (node.parsed_attributes['file']))
-
- def visitNamespaceTag(self, node):
- pass
-
- def visitDefTag(self, node):
- pass
-
- def visitBlockTag(self, node):
- if node.is_anonymous:
- self.printer.writeline("%s()" % node.funcname)
- else:
- nameargs = node.get_argument_expressions(include_defaults=False)
- nameargs += ['**pageargs']
- self.printer.writeline("if 'parent' not in context._data or "
- "not hasattr(context._data['parent'], '%s'):"
- % node.funcname)
- self.printer.writeline(
- "context['self'].%s(%s)" % (node.funcname, ",".join(nameargs)))
- self.printer.writeline("\n")
-
- def visitCallNamespaceTag(self, node):
- # TODO: we can put namespace-specific checks here, such
- # as ensure the given namespace will be imported,
- # pre-import the namespace, etc.
- self.visitCallTag(node)
-
- def visitCallTag(self, node):
- self.printer.writeline("def ccall(caller):")
- export = ['body']
- callable_identifiers = self.identifiers.branch(node, nested=True)
- body_identifiers = callable_identifiers.branch(node, nested=False)
- # we want the 'caller' passed to ccall to be used
- # for the body() function, but for other non-body()
- # <%def>s within <%call> we want the current caller
- # off the call stack (if any)
- body_identifiers.add_declared('caller')
-
- self.identifier_stack.append(body_identifiers)
- class DefVisitor(object):
- def visitDefTag(s, node):
- s.visitDefOrBase(node)
-
- def visitBlockTag(s, node):
- s.visitDefOrBase(node)
-
- def visitDefOrBase(s, node):
- self.write_inline_def(node, callable_identifiers, nested=False)
- if not node.is_anonymous:
- export.append(node.funcname)
- # remove defs that are within the <%call> from the
- # "closuredefs" defined in the body, so they dont render twice
- if node.funcname in body_identifiers.closuredefs:
- del body_identifiers.closuredefs[node.funcname]
-
- vis = DefVisitor()
- for n in node.nodes:
- n.accept_visitor(vis)
- self.identifier_stack.pop()
-
- bodyargs = node.body_decl.get_argument_expressions()
- self.printer.writeline("def body(%s):" % ','.join(bodyargs))
-
- # TODO: figure out best way to specify
- # buffering/nonbuffering (at call time would be better)
- buffered = False
- if buffered:
- self.printer.writelines(
- "context._push_buffer()",
- "try:"
- )
- self.write_variable_declares(body_identifiers)
- self.identifier_stack.append(body_identifiers)
-
- for n in node.nodes:
- n.accept_visitor(self)
- self.identifier_stack.pop()
-
- self.write_def_finish(node, buffered, False, False, callstack=False)
- self.printer.writelines(
- None,
- "return [%s]" % (','.join(export)),
- None
- )
-
- self.printer.writelines(
- # push on caller for nested call
- "context.caller_stack.nextcaller = "
- "runtime.Namespace('caller', context, "
- "callables=ccall(__M_caller))",
- "try:")
- self.write_source_comment(node)
- self.printer.writelines(
- "__M_writer(%s)" % self.create_filter_callable(
- [], node.expression, True),
- "finally:",
- "context.caller_stack.nextcaller = None",
- None
- )
-
-class _Identifiers(object):
- """tracks the status of identifier names as template code is rendered."""
-
- def __init__(self, compiler, node=None, parent=None, nested=False):
- if parent is not None:
- # if we are the branch created in write_namespaces(),
- # we don't share any context from the main body().
- if isinstance(node, parsetree.NamespaceTag):
- self.declared = set()
- self.topleveldefs = util.SetLikeDict()
- else:
- # things that have already been declared
- # in an enclosing namespace (i.e. names we can just use)
- self.declared = set(parent.declared).\
- union([c.name for c in parent.closuredefs.values()]).\
- union(parent.locally_declared).\
- union(parent.argument_declared)
-
- # if these identifiers correspond to a "nested"
- # scope, it means whatever the parent identifiers
- # had as undeclared will have been declared by that parent,
- # and therefore we have them in our scope.
- if nested:
- self.declared = self.declared.union(parent.undeclared)
-
- # top level defs that are available
- self.topleveldefs = util.SetLikeDict(**parent.topleveldefs)
- else:
- self.declared = set()
- self.topleveldefs = util.SetLikeDict()
-
- self.compiler = compiler
-
- # things within this level that are referenced before they
- # are declared (e.g. assigned to)
- self.undeclared = set()
-
- # things that are declared locally. some of these things
- # could be in the "undeclared" list as well if they are
- # referenced before declared
- self.locally_declared = set()
-
- # assignments made in explicit python blocks.
- # these will be propagated to
- # the context of local def calls.
- self.locally_assigned = set()
-
- # things that are declared in the argument
- # signature of the def callable
- self.argument_declared = set()
-
- # closure defs that are defined in this level
- self.closuredefs = util.SetLikeDict()
-
- self.node = node
-
- if node is not None:
- node.accept_visitor(self)
-
- illegal_names = self.compiler.reserved_names.intersection(
- self.locally_declared)
- if illegal_names:
- raise exceptions.NameConflictError(
- "Reserved words declared in template: %s" %
- ", ".join(illegal_names))
-
-
- def branch(self, node, **kwargs):
- """create a new Identifiers for a new Node, with
- this Identifiers as the parent."""
-
- return _Identifiers(self.compiler, node, self, **kwargs)
-
- @property
- def defs(self):
- return set(self.topleveldefs.union(self.closuredefs).values())
-
- def __repr__(self):
- return "Identifiers(declared=%r, locally_declared=%r, "\
- "undeclared=%r, topleveldefs=%r, closuredefs=%r, "\
- "argumentdeclared=%r)" %\
- (
- list(self.declared),
- list(self.locally_declared),
- list(self.undeclared),
- [c.name for c in self.topleveldefs.values()],
- [c.name for c in self.closuredefs.values()],
- self.argument_declared)
-
- def check_declared(self, node):
- """update the state of this Identifiers with the undeclared
- and declared identifiers of the given node."""
-
- for ident in node.undeclared_identifiers():
- if ident != 'context' and\
- ident not in self.declared.union(self.locally_declared):
- self.undeclared.add(ident)
- for ident in node.declared_identifiers():
- self.locally_declared.add(ident)
-
- def add_declared(self, ident):
- self.declared.add(ident)
- if ident in self.undeclared:
- self.undeclared.remove(ident)
-
- def visitExpression(self, node):
- self.check_declared(node)
-
- def visitControlLine(self, node):
- self.check_declared(node)
-
- def visitCode(self, node):
- if not node.ismodule:
- self.check_declared(node)
- self.locally_assigned = self.locally_assigned.union(
- node.declared_identifiers())
-
- def visitNamespaceTag(self, node):
- # only traverse into the sub-elements of a
- # <%namespace> tag if we are the branch created in
- # write_namespaces()
- if self.node is node:
- for n in node.nodes:
- n.accept_visitor(self)
-
- def _check_name_exists(self, collection, node):
- existing = collection.get(node.funcname)
- collection[node.funcname] = node
- if existing is not None and \
- existing is not node and \
- (node.is_block or existing.is_block):
- raise exceptions.CompileException(
- "%%def or %%block named '%s' already "
- "exists in this template." %
- node.funcname, **node.exception_kwargs)
-
- def visitDefTag(self, node):
- if node.is_root() and not node.is_anonymous:
- self._check_name_exists(self.topleveldefs, node)
- elif node is not self.node:
- self._check_name_exists(self.closuredefs, node)
-
- for ident in node.undeclared_identifiers():
- if ident != 'context' and\
- ident not in self.declared.union(self.locally_declared):
- self.undeclared.add(ident)
-
- # visit defs only one level deep
- if node is self.node:
- for ident in node.declared_identifiers():
- self.argument_declared.add(ident)
-
- for n in node.nodes:
- n.accept_visitor(self)
-
- def visitBlockTag(self, node):
- if node is not self.node and \
- not node.is_anonymous:
-
- if isinstance(self.node, parsetree.DefTag):
- raise exceptions.CompileException(
- "Named block '%s' not allowed inside of def '%s'"
- % (node.name, self.node.name), **node.exception_kwargs)
- elif isinstance(self.node,
- (parsetree.CallTag, parsetree.CallNamespaceTag)):
- raise exceptions.CompileException(
- "Named block '%s' not allowed inside of <%%call> tag"
- % (node.name, ), **node.exception_kwargs)
-
- for ident in node.undeclared_identifiers():
- if ident != 'context' and \
- ident not in self.declared.union(self.locally_declared):
- self.undeclared.add(ident)
-
- if not node.is_anonymous:
- self._check_name_exists(self.topleveldefs, node)
- self.undeclared.add(node.funcname)
- elif node is not self.node:
- self._check_name_exists(self.closuredefs, node)
- for ident in node.declared_identifiers():
- self.argument_declared.add(ident)
- for n in node.nodes:
- n.accept_visitor(self)
-
- def visitTextTag(self, node):
- for ident in node.undeclared_identifiers():
- if ident != 'context' and \
- ident not in self.declared.union(self.locally_declared):
- self.undeclared.add(ident)
-
- def visitIncludeTag(self, node):
- self.check_declared(node)
-
- def visitPageTag(self, node):
- for ident in node.declared_identifiers():
- self.argument_declared.add(ident)
- self.check_declared(node)
-
- def visitCallNamespaceTag(self, node):
- self.visitCallTag(node)
-
- def visitCallTag(self, node):
- if node is self.node:
- for ident in node.undeclared_identifiers():
- if ident != 'context' and\
- ident not in self.declared.union(self.locally_declared):
- self.undeclared.add(ident)
- for ident in node.declared_identifiers():
- self.argument_declared.add(ident)
- for n in node.nodes:
- n.accept_visitor(self)
- else:
- for ident in node.undeclared_identifiers():
- if ident != 'context' and\
- ident not in self.declared.union(self.locally_declared):
- self.undeclared.add(ident)
-
-
-_FOR_LOOP = re.compile(
- r'^for\s+((?:\(?)\s*[A-Za-z_][A-Za-z_0-9]*'
- r'(?:\s*,\s*(?:[A-Za-z_][A-Za-z0-9_]*),??)*\s*(?:\)?))\s+in\s+(.*):'
- )
-
-def mangle_mako_loop(node, printer):
- """converts a for loop into a context manager wrapped around a for loop
- when access to the `loop` variable has been detected in the for loop body
- """
- loop_variable = LoopVariable()
- node.accept_visitor(loop_variable)
- if loop_variable.detected:
- node.nodes[-1].has_loop_context = True
- match = _FOR_LOOP.match(node.text)
- if match:
- printer.writelines(
- 'loop = __M_loop._enter(%s)' % match.group(2),
- 'try:'
- #'with __M_loop(%s) as loop:' % match.group(2)
- )
- text = 'for %s in loop:' % match.group(1)
- else:
- raise SyntaxError("Couldn't apply loop context: %s" % node.text)
- else:
- text = node.text
- return text
-
-
-class LoopVariable(object):
- """A node visitor which looks for the name 'loop' within undeclared
- identifiers."""
-
- def __init__(self):
- self.detected = False
-
- def _loop_reference_detected(self, node):
- if 'loop' in node.undeclared_identifiers():
- self.detected = True
- else:
- for n in node.get_children():
- n.accept_visitor(self)
-
- def visitControlLine(self, node):
- self._loop_reference_detected(node)
-
- def visitCode(self, node):
- self._loop_reference_detected(node)
-
- def visitExpression(self, node):
- self._loop_reference_detected(node)
diff --git a/Darwin/lib/python2.7/site-packages/mako/compat.py b/Darwin/lib/python2.7/site-packages/mako/compat.py
deleted file mode 100644
index 31da8bd..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/compat.py
+++ /dev/null
@@ -1,167 +0,0 @@
-import sys
-import time
-
-py3k = sys.version_info >= (3, 0)
-py33 = sys.version_info >= (3, 3)
-py26 = sys.version_info >= (2, 6)
-py25 = sys.version_info >= (2, 5)
-jython = sys.platform.startswith('java')
-win32 = sys.platform.startswith('win')
-pypy = hasattr(sys, 'pypy_version_info')
-
-if py3k:
- from io import StringIO
- import builtins as compat_builtins
- from urllib.parse import quote_plus, unquote_plus
- from html.entities import codepoint2name, name2codepoint
- string_types = str,
- binary_type = bytes
- text_type = str
-
- from io import BytesIO as byte_buffer
-
- def u(s):
- return s
-
- def octal(lit):
- return eval("0o" + lit)
-
-else:
- import __builtin__ as compat_builtins
- try:
- from cStringIO import StringIO
- except:
- from StringIO import StringIO
-
- byte_buffer = StringIO
-
- from urllib import quote_plus, unquote_plus
- from htmlentitydefs import codepoint2name, name2codepoint
- string_types = basestring,
- binary_type = str
- text_type = unicode
-
- def u(s):
- return unicode(s, "utf-8")
-
- def octal(lit):
- return eval("0" + lit)
-
-
-if py33:
- from importlib import machinery
- def load_module(module_id, path):
- return machinery.SourceFileLoader(module_id, path).load_module()
-else:
- import imp
- def load_module(module_id, path):
- fp = open(path, 'rb')
- try:
- return imp.load_source(module_id, path, fp)
- finally:
- fp.close()
-
-
-def exception_as():
- return sys.exc_info()[1]
-
-try:
- import threading
- if py3k:
- import _thread as thread
- else:
- import thread
-except ImportError:
- import dummy_threading as threading
- if py3k:
- import _dummy_thread as thread
- else:
- import dummy_thread as thread
-
-if win32 or jython:
- time_func = time.clock
-else:
- time_func = time.time
-
-try:
- from functools import partial
-except:
- def partial(func, *args, **keywords):
- def newfunc(*fargs, **fkeywords):
- newkeywords = keywords.copy()
- newkeywords.update(fkeywords)
- return func(*(args + fargs), **newkeywords)
- return newfunc
-
-if not py25:
- def all(iterable):
- for i in iterable:
- if not i:
- return False
- return True
-
- def exception_name(exc):
- try:
- return exc.__class__.__name__
- except AttributeError:
- return exc.__name__
-else:
- all = all
-
- def exception_name(exc):
- return exc.__class__.__name__
-
-try:
- from inspect import CO_VARKEYWORDS, CO_VARARGS
- def inspect_func_args(fn):
- if py3k:
- co = fn.__code__
- else:
- co = fn.func_code
-
- nargs = co.co_argcount
- names = co.co_varnames
- args = list(names[:nargs])
-
- varargs = None
- if co.co_flags & CO_VARARGS:
- varargs = co.co_varnames[nargs]
- nargs = nargs + 1
- varkw = None
- if co.co_flags & CO_VARKEYWORDS:
- varkw = co.co_varnames[nargs]
-
- if py3k:
- return args, varargs, varkw, fn.__defaults__
- else:
- return args, varargs, varkw, fn.func_defaults
-except ImportError:
- import inspect
- def inspect_func_args(fn):
- return inspect.getargspec(fn)
-
-if py3k:
- def callable(fn):
- return hasattr(fn, '__call__')
-else:
- callable = callable
-
-
-################################################
-# cross-compatible metaclass implementation
-# Copyright (c) 2010-2012 Benjamin Peterson
-def with_metaclass(meta, base=object):
- """Create a base class with a metaclass."""
- return meta("%sBase" % meta.__name__, (base,), {})
-################################################
-
-
-def arg_stringname(func_arg):
- """Gets the string name of a kwarg or vararg
- In Python3.4 a function's args are
- of _ast.arg type not _ast.name
- """
- if hasattr(func_arg, 'arg'):
- return func_arg.arg
- else:
- return str(func_arg)
diff --git a/Darwin/lib/python2.7/site-packages/mako/exceptions.py b/Darwin/lib/python2.7/site-packages/mako/exceptions.py
deleted file mode 100644
index dcf81a6..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/exceptions.py
+++ /dev/null
@@ -1,374 +0,0 @@
-# mako/exceptions.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""exception classes"""
-
-import traceback
-import sys
-import re
-from mako import util, compat
-
-class MakoException(Exception):
- pass
-
-class RuntimeException(MakoException):
- pass
-
-def _format_filepos(lineno, pos, filename):
- if filename is None:
- return " at line: %d char: %d" % (lineno, pos)
- else:
- return " in file '%s' at line: %d char: %d" % (filename, lineno, pos)
-
-
-class CompileException(MakoException):
- def __init__(self, message, source, lineno, pos, filename):
- MakoException.__init__(self,
- message + _format_filepos(lineno, pos, filename))
- self.lineno =lineno
- self.pos = pos
- self.filename = filename
- self.source = source
-
-class SyntaxException(MakoException):
- def __init__(self, message, source, lineno, pos, filename):
- MakoException.__init__(self,
- message + _format_filepos(lineno, pos, filename))
- self.lineno =lineno
- self.pos = pos
- self.filename = filename
- self.source = source
-
-class UnsupportedError(MakoException):
- """raised when a retired feature is used."""
-
-class NameConflictError(MakoException):
- """raised when a reserved word is used inappropriately"""
-
-class TemplateLookupException(MakoException):
- pass
-
-class TopLevelLookupException(TemplateLookupException):
- pass
-
-class RichTraceback(object):
- """Pull the current exception from the ``sys`` traceback and extracts
- Mako-specific template information.
-
- See the usage examples in :ref:`handling_exceptions`.
-
- """
- def __init__(self, error=None, traceback=None):
- self.source, self.lineno = "", 0
-
- if error is None or traceback is None:
- t, value, tback = sys.exc_info()
-
- if error is None:
- error = value or t
-
- if traceback is None:
- traceback = tback
-
- self.error = error
- self.records = self._init(traceback)
-
- if isinstance(self.error, (CompileException, SyntaxException)):
- import mako.template
- self.source = self.error.source
- self.lineno = self.error.lineno
- self._has_source = True
-
- self._init_message()
-
- @property
- def errorname(self):
- return compat.exception_name(self.error)
-
- def _init_message(self):
- """Find a unicode representation of self.error"""
- try:
- self.message = compat.text_type(self.error)
- except UnicodeError:
- try:
- self.message = str(self.error)
- except UnicodeEncodeError:
- # Fallback to args as neither unicode nor
- # str(Exception(u'\xe6')) work in Python < 2.6
- self.message = self.error.args[0]
- if not isinstance(self.message, compat.text_type):
- self.message = compat.text_type(self.message, 'ascii', 'replace')
-
- def _get_reformatted_records(self, records):
- for rec in records:
- if rec[6] is not None:
- yield (rec[4], rec[5], rec[2], rec[6])
- else:
- yield tuple(rec[0:4])
-
- @property
- def traceback(self):
- """Return a list of 4-tuple traceback records (i.e. normal python
- format) with template-corresponding lines remapped to the originating
- template.
-
- """
- return list(self._get_reformatted_records(self.records))
-
- @property
- def reverse_records(self):
- return reversed(self.records)
-
- @property
- def reverse_traceback(self):
- """Return the same data as traceback, except in reverse order.
- """
-
- return list(self._get_reformatted_records(self.reverse_records))
-
- def _init(self, trcback):
- """format a traceback from sys.exc_info() into 7-item tuples,
- containing the regular four traceback tuple items, plus the original
- template filename, the line number adjusted relative to the template
- source, and code line from that line number of the template."""
-
- import mako.template
- mods = {}
- rawrecords = traceback.extract_tb(trcback)
- new_trcback = []
- for filename, lineno, function, line in rawrecords:
- if not line:
- line = ''
- try:
- (line_map, template_lines) = mods[filename]
- except KeyError:
- try:
- info = mako.template._get_module_info(filename)
- module_source = info.code
- template_source = info.source
- template_filename = info.template_filename or filename
- except KeyError:
- # A normal .py file (not a Template)
- if not compat.py3k:
- try:
- fp = open(filename, 'rb')
- encoding = util.parse_encoding(fp)
- fp.close()
- except IOError:
- encoding = None
- if encoding:
- line = line.decode(encoding)
- else:
- line = line.decode('ascii', 'replace')
- new_trcback.append((filename, lineno, function, line,
- None, None, None, None))
- continue
-
- template_ln = module_ln = 1
- line_map = {}
- for line in module_source.split("\n"):
- match = re.match(r'\s*# SOURCE LINE (\d+)', line)
- if match:
- template_ln = int(match.group(1))
- module_ln += 1
- line_map[module_ln] = template_ln
- template_lines = [line for line in
- template_source.split("\n")]
- mods[filename] = (line_map, template_lines)
-
- template_ln = line_map[lineno]
- if template_ln <= len(template_lines):
- template_line = template_lines[template_ln - 1]
- else:
- template_line = None
- new_trcback.append((filename, lineno, function,
- line, template_filename, template_ln,
- template_line, template_source))
- if not self.source:
- for l in range(len(new_trcback)-1, 0, -1):
- if new_trcback[l][5]:
- self.source = new_trcback[l][7]
- self.lineno = new_trcback[l][5]
- break
- else:
- if new_trcback:
- try:
- # A normal .py file (not a Template)
- fp = open(new_trcback[-1][0], 'rb')
- encoding = util.parse_encoding(fp)
- fp.seek(0)
- self.source = fp.read()
- fp.close()
- if encoding:
- self.source = self.source.decode(encoding)
- except IOError:
- self.source = ''
- self.lineno = new_trcback[-1][1]
- return new_trcback
-
-
-def text_error_template(lookup=None):
- """Provides a template that renders a stack trace in a similar format to
- the Python interpreter, substituting source template filenames, line
- numbers and code for that of the originating source template, as
- applicable.
-
- """
- import mako.template
- return mako.template.Template(r"""
-<%page args="error=None, traceback=None"/>
-<%!
- from mako.exceptions import RichTraceback
-%>\
-<%
- tback = RichTraceback(error=error, traceback=traceback)
-%>\
-Traceback (most recent call last):
-% for (filename, lineno, function, line) in tback.traceback:
- File "${filename}", line ${lineno}, in ${function or '?'}
- ${line | trim}
-% endfor
-${tback.errorname}: ${tback.message}
-""")
-
-
-def _install_pygments():
- global syntax_highlight, pygments_html_formatter
- from mako.ext.pygmentplugin import syntax_highlight,\
- pygments_html_formatter
-
-def _install_fallback():
- global syntax_highlight, pygments_html_formatter
- from mako.filters import html_escape
- pygments_html_formatter = None
- def syntax_highlight(filename='', language=None):
- return html_escape
-
-def _install_highlighting():
- try:
- _install_pygments()
- except ImportError:
- _install_fallback()
-_install_highlighting()
-
-def html_error_template():
- """Provides a template that renders a stack trace in an HTML format,
- providing an excerpt of code as well as substituting source template
- filenames, line numbers and code for that of the originating source
- template, as applicable.
-
- The template's default ``encoding_errors`` value is ``'htmlentityreplace'``. The
- template has two options. With the ``full`` option disabled, only a section of
- an HTML document is returned. With the ``css`` option disabled, the default
- stylesheet won't be included.
-
- """
- import mako.template
- return mako.template.Template(r"""
-<%!
- from mako.exceptions import RichTraceback, syntax_highlight,\
- pygments_html_formatter
-%>
-<%page args="full=True, css=True, error=None, traceback=None"/>
-% if full:
-
-
- Mako Runtime Error
-% endif
-% if css:
-
-% endif
-% if full:
-
-
-% endif
-
-Error !
-<%
- tback = RichTraceback(error=error, traceback=traceback)
- src = tback.source
- line = tback.lineno
- if src:
- lines = src.split('\n')
- else:
- lines = None
-%>
-${tback.errorname}: ${tback.message|h}
-
-% if lines:
-
-
-% for index in range(max(0, line-4),min(len(lines), line+5)):
- <%
- if pygments_html_formatter:
- pygments_html_formatter.linenostart = index + 1
- %>
- % if index + 1 == line:
- <%
- if pygments_html_formatter:
- old_cssclass = pygments_html_formatter.cssclass
- pygments_html_formatter.cssclass = 'error ' + old_cssclass
- %>
- ${lines[index] | syntax_highlight(language='mako')}
- <%
- if pygments_html_formatter:
- pygments_html_formatter.cssclass = old_cssclass
- %>
- % else:
- ${lines[index] | syntax_highlight(language='mako')}
- % endif
-% endfor
-
-
-% endif
-
-
-% for (filename, lineno, function, line) in tback.reverse_traceback:
-
${filename}, line ${lineno}:
-
- <%
- if pygments_html_formatter:
- pygments_html_formatter.linenostart = lineno
- %>
-
${line | syntax_highlight(filename)}
-
-% endfor
-
-
-% if full:
-
-
-% endif
-""", output_encoding=sys.getdefaultencoding(),
- encoding_errors='htmlentityreplace')
diff --git a/Darwin/lib/python2.7/site-packages/mako/ext/__init__.py b/Darwin/lib/python2.7/site-packages/mako/ext/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/Darwin/lib/python2.7/site-packages/mako/ext/autohandler.py b/Darwin/lib/python2.7/site-packages/mako/ext/autohandler.py
deleted file mode 100644
index d56cbc1..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/ext/autohandler.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# ext/autohandler.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""adds autohandler functionality to Mako templates.
-
-requires that the TemplateLookup class is used with templates.
-
-usage:
-
-<%!
- from mako.ext.autohandler import autohandler
-%>
-<%inherit file="${autohandler(template, context)}"/>
-
-
-or with custom autohandler filename:
-
-<%!
- from mako.ext.autohandler import autohandler
-%>
-<%inherit file="${autohandler(template, context, name='somefilename')}"/>
-
-"""
-
-import posixpath, os, re
-
-def autohandler(template, context, name='autohandler'):
- lookup = context.lookup
- _template_uri = template.module._template_uri
- if not lookup.filesystem_checks:
- try:
- return lookup._uri_cache[(autohandler, _template_uri, name)]
- except KeyError:
- pass
-
- tokens = re.findall(r'([^/]+)', posixpath.dirname(_template_uri)) + [name]
- while len(tokens):
- path = '/' + '/'.join(tokens)
- if path != _template_uri and _file_exists(lookup, path):
- if not lookup.filesystem_checks:
- return lookup._uri_cache.setdefault(
- (autohandler, _template_uri, name), path)
- else:
- return path
- if len(tokens) == 1:
- break
- tokens[-2:] = [name]
-
- if not lookup.filesystem_checks:
- return lookup._uri_cache.setdefault(
- (autohandler, _template_uri, name), None)
- else:
- return None
-
-def _file_exists(lookup, path):
- psub = re.sub(r'^/', '',path)
- for d in lookup.directories:
- if os.path.exists(d + '/' + psub):
- return True
- else:
- return False
-
diff --git a/Darwin/lib/python2.7/site-packages/mako/ext/babelplugin.py b/Darwin/lib/python2.7/site-packages/mako/ext/babelplugin.py
deleted file mode 100644
index 538c048..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/ext/babelplugin.py
+++ /dev/null
@@ -1,126 +0,0 @@
-# ext/babelplugin.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""gettext message extraction via Babel: http://babel.edgewall.org/"""
-from babel.messages.extract import extract_python
-from mako.compat import StringIO
-from mako import compat
-from mako import lexer, parsetree
-
-def extract(fileobj, keywords, comment_tags, options):
- """Extract messages from Mako templates.
-
- :param fileobj: the file-like object the messages should be extracted from
- :param keywords: a list of keywords (i.e. function names) that should be
- recognized as translation functions
- :param comment_tags: a list of translator tags to search for and include
- in the results
- :param options: a dictionary of additional options (optional)
- :return: an iterator over ``(lineno, funcname, message, comments)`` tuples
- :rtype: ``iterator``
- """
- encoding = options.get('input_encoding', options.get('encoding', None))
-
- template_node = lexer.Lexer(fileobj.read(),
- input_encoding=encoding).parse()
- for extracted in extract_nodes(template_node.get_children(),
- keywords, comment_tags, options):
- yield extracted
-
-def extract_nodes(nodes, keywords, comment_tags, options):
- """Extract messages from Mako's lexer node objects
-
- :param nodes: an iterable of Mako parsetree.Node objects to extract from
- :param keywords: a list of keywords (i.e. function names) that should be
- recognized as translation functions
- :param comment_tags: a list of translator tags to search for and include
- in the results
- :param options: a dictionary of additional options (optional)
- :return: an iterator over ``(lineno, funcname, message, comments)`` tuples
- :rtype: ``iterator``
- """
- translator_comments = []
- in_translator_comments = False
-
- for node in nodes:
- child_nodes = None
- if in_translator_comments and isinstance(node, parsetree.Text) and \
- not node.content.strip():
- # Ignore whitespace within translator comments
- continue
-
- if isinstance(node, parsetree.Comment):
- value = node.text.strip()
- if in_translator_comments:
- translator_comments.extend(_split_comment(node.lineno, value))
- continue
- for comment_tag in comment_tags:
- if value.startswith(comment_tag):
- in_translator_comments = True
- translator_comments.extend(_split_comment(node.lineno,
- value))
- continue
-
- if isinstance(node, parsetree.DefTag):
- code = node.function_decl.code
- child_nodes = node.nodes
- elif isinstance(node, parsetree.BlockTag):
- code = node.body_decl.code
- child_nodes = node.nodes
- elif isinstance(node, parsetree.CallTag):
- code = node.code.code
- child_nodes = node.nodes
- elif isinstance(node, parsetree.PageTag):
- code = node.body_decl.code
- elif isinstance(node, parsetree.CallNamespaceTag):
- code = node.expression
- child_nodes = node.nodes
- elif isinstance(node, parsetree.ControlLine):
- if node.isend:
- in_translator_comments = False
- continue
- code = node.text
- elif isinstance(node, parsetree.Code):
- in_translator_comments = False
- code = node.code.code
- elif isinstance(node, parsetree.Expression):
- code = node.code.code
- else:
- continue
-
- # Comments don't apply unless they immediately preceed the message
- if translator_comments and \
- translator_comments[-1][0] < node.lineno - 1:
- translator_comments = []
-
- translator_strings = [comment[1] for comment in translator_comments]
-
- if isinstance(code, compat.text_type):
- code = code.encode('ascii', 'backslashreplace')
-
- used_translator_comments = False
- code = compat.byte_buffer(code)
- for lineno, funcname, messages, python_translator_comments \
- in extract_python(code, keywords, comment_tags, options):
- yield (node.lineno + (lineno - 1), funcname, messages,
- translator_strings + python_translator_comments)
- used_translator_comments = True
-
- if used_translator_comments:
- translator_comments = []
- in_translator_comments = False
-
- if child_nodes:
- for extracted in extract_nodes(child_nodes, keywords, comment_tags,
- options):
- yield extracted
-
-
-def _split_comment(lineno, comment):
- """Return the multiline comment at lineno split into a list of comment line
- numbers and the accompanying comment line"""
- return [(lineno + index, line) for index, line in
- enumerate(comment.splitlines())]
diff --git a/Darwin/lib/python2.7/site-packages/mako/ext/beaker_cache.py b/Darwin/lib/python2.7/site-packages/mako/ext/beaker_cache.py
deleted file mode 100644
index c9fbf0a..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/ext/beaker_cache.py
+++ /dev/null
@@ -1,70 +0,0 @@
-"""Provide a :class:`.CacheImpl` for the Beaker caching system."""
-
-from mako import exceptions
-
-from mako.cache import CacheImpl
-
-_beaker_cache = None
-class BeakerCacheImpl(CacheImpl):
- """A :class:`.CacheImpl` provided for the Beaker caching system.
-
- This plugin is used by default, based on the default
- value of ``'beaker'`` for the ``cache_impl`` parameter of the
- :class:`.Template` or :class:`.TemplateLookup` classes.
-
- """
-
- def __init__(self, cache):
- global _beaker_cache
- if _beaker_cache is None:
- try:
- from beaker import cache as beaker_cache
- except ImportError:
- raise exceptions.RuntimeException(
- "the Beaker package is required to use cache "
- "functionality.")
-
- if 'manager' in cache.template.cache_args:
- _beaker_cache = cache.template.cache_args['manager']
- else:
- _beaker_cache = beaker_cache.CacheManager()
- super(BeakerCacheImpl, self).__init__(cache)
-
- def _get_cache(self, **kw):
- expiretime = kw.pop('timeout', None)
- if 'dir' in kw:
- kw['data_dir'] = kw.pop('dir')
- elif self.cache.template.module_directory:
- kw['data_dir'] = self.cache.template.module_directory
-
- if 'manager' in kw:
- kw.pop('manager')
-
- if kw.get('type') == 'memcached':
- kw['type'] = 'ext:memcached'
-
- if 'region' in kw:
- region = kw.pop('region')
- cache = _beaker_cache.get_cache_region(self.cache.id, region, **kw)
- else:
- cache = _beaker_cache.get_cache(self.cache.id, **kw)
- cache_args = {'starttime':self.cache.starttime}
- if expiretime:
- cache_args['expiretime'] = expiretime
- return cache, cache_args
-
- def get_or_create(self, key, creation_function, **kw):
- cache, kw = self._get_cache(**kw)
- return cache.get(key, createfunc=creation_function, **kw)
-
- def put(self, key, value, **kw):
- cache, kw = self._get_cache(**kw)
- cache.put(key, value, **kw)
-
- def get(self, key, **kw):
- cache, kw = self._get_cache(**kw)
- return cache.get(key, **kw)
-
- def invalidate(self, key, **kw):
- cache, kw = self._get_cache(**kw)
- cache.remove_value(key, **kw)
diff --git a/Darwin/lib/python2.7/site-packages/mako/ext/preprocessors.py b/Darwin/lib/python2.7/site-packages/mako/ext/preprocessors.py
deleted file mode 100644
index 5a15ff3..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/ext/preprocessors.py
+++ /dev/null
@@ -1,20 +0,0 @@
-# ext/preprocessors.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""preprocessing functions, used with the 'preprocessor'
-argument on Template, TemplateLookup"""
-
-import re
-
-def convert_comments(text):
- """preprocess old style comments.
-
- example:
-
- from mako.ext.preprocessors import convert_comments
- t = Template(..., preprocessor=preprocess_comments)"""
- return re.sub(r'(?<=\n)\s*#[^#]', "##", text)
-
diff --git a/Darwin/lib/python2.7/site-packages/mako/ext/pygmentplugin.py b/Darwin/lib/python2.7/site-packages/mako/ext/pygmentplugin.py
deleted file mode 100644
index 040a25c..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/ext/pygmentplugin.py
+++ /dev/null
@@ -1,122 +0,0 @@
-# ext/pygmentplugin.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-from pygments.lexers.web import \
- HtmlLexer, XmlLexer, JavascriptLexer, CssLexer
-from pygments.lexers.agile import PythonLexer, Python3Lexer
-from pygments.lexer import DelegatingLexer, RegexLexer, bygroups, \
- include, using
-from pygments.token import \
- Text, Comment, Operator, Keyword, Name, String, Other
-from pygments.formatters.html import HtmlFormatter
-from pygments import highlight
-from mako import compat
-
-class MakoLexer(RegexLexer):
- name = 'Mako'
- aliases = ['mako']
- filenames = ['*.mao']
-
- tokens = {
- 'root': [
- (r'(\s*)(\%)(\s*end(?:\w+))(\n|\Z)',
- bygroups(Text, Comment.Preproc, Keyword, Other)),
- (r'(\s*)(\%(?!%))([^\n]*)(\n|\Z)',
- bygroups(Text, Comment.Preproc, using(PythonLexer), Other)),
- (r'(\s*)(##[^\n]*)(\n|\Z)',
- bygroups(Text, Comment.Preproc, Other)),
- (r'''(?s)<%doc>.*?%doc>''', Comment.Preproc),
- (r'(<%)([\w\.\:]+)',
- bygroups(Comment.Preproc, Name.Builtin), 'tag'),
- (r'(%)([\w\.\:]+)(>)',
- bygroups(Comment.Preproc, Name.Builtin, Comment.Preproc)),
- (r'<%(?=([\w\.\:]+))', Comment.Preproc, 'ondeftags'),
- (r'(<%(?:!?))(.*?)(%>)(?s)',
- bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
- (r'(\$\{)(.*?)(\})',
- bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)),
- (r'''(?sx)
- (.+?) # anything, followed by:
- (?:
- (?<=\n)(?=%(?!%)|\#\#) | # an eval or comment line
- (?=\#\*) | # multiline comment
- (?=?%) | # a python block
- # call start or end
- (?=\$\{) | # a substitution
- (?<=\n)(?=\s*%) |
- # - don't consume
- (\\\n) | # an escaped newline
- \Z # end of string
- )
- ''', bygroups(Other, Operator)),
- (r'\s+', Text),
- ],
- 'ondeftags': [
- (r'<%', Comment.Preproc),
- (r'(?<=<%)(include|inherit|namespace|page)', Name.Builtin),
- include('tag'),
- ],
- 'tag': [
- (r'((?:\w+)\s*=)\s*(".*?")',
- bygroups(Name.Attribute, String)),
- (r'/?\s*>', Comment.Preproc, '#pop'),
- (r'\s+', Text),
- ],
- 'attr': [
- ('".*?"', String, '#pop'),
- ("'.*?'", String, '#pop'),
- (r'[^\s>]+', String, '#pop'),
- ],
- }
-
-
-class MakoHtmlLexer(DelegatingLexer):
- name = 'HTML+Mako'
- aliases = ['html+mako']
-
- def __init__(self, **options):
- super(MakoHtmlLexer, self).__init__(HtmlLexer, MakoLexer,
- **options)
-
-class MakoXmlLexer(DelegatingLexer):
- name = 'XML+Mako'
- aliases = ['xml+mako']
-
- def __init__(self, **options):
- super(MakoXmlLexer, self).__init__(XmlLexer, MakoLexer,
- **options)
-
-class MakoJavascriptLexer(DelegatingLexer):
- name = 'JavaScript+Mako'
- aliases = ['js+mako', 'javascript+mako']
-
- def __init__(self, **options):
- super(MakoJavascriptLexer, self).__init__(JavascriptLexer,
- MakoLexer, **options)
-
-class MakoCssLexer(DelegatingLexer):
- name = 'CSS+Mako'
- aliases = ['css+mako']
-
- def __init__(self, **options):
- super(MakoCssLexer, self).__init__(CssLexer, MakoLexer,
- **options)
-
-
-pygments_html_formatter = HtmlFormatter(cssclass='syntax-highlighted',
- linenos=True)
-def syntax_highlight(filename='', language=None):
- mako_lexer = MakoLexer()
- if compat.py3k:
- python_lexer = Python3Lexer()
- else:
- python_lexer = PythonLexer()
- if filename.startswith('memory:') or language == 'mako':
- return lambda string: highlight(string, mako_lexer,
- pygments_html_formatter)
- return lambda string: highlight(string, python_lexer,
- pygments_html_formatter)
-
diff --git a/Darwin/lib/python2.7/site-packages/mako/ext/turbogears.py b/Darwin/lib/python2.7/site-packages/mako/ext/turbogears.py
deleted file mode 100644
index a4179d0..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/ext/turbogears.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# ext/turbogears.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-import inspect
-from mako import compat
-from mako.lookup import TemplateLookup
-from mako.template import Template
-
-class TGPlugin(object):
- """TurboGears compatible Template Plugin."""
-
- def __init__(self, extra_vars_func=None, options=None, extension='mak'):
- self.extra_vars_func = extra_vars_func
- self.extension = extension
- if not options:
- options = {}
-
- # Pull the options out and initialize the lookup
- lookup_options = {}
- for k, v in options.items():
- if k.startswith('mako.'):
- lookup_options[k[5:]] = v
- elif k in ['directories', 'filesystem_checks', 'module_directory']:
- lookup_options[k] = v
- self.lookup = TemplateLookup(**lookup_options)
-
- self.tmpl_options = {}
- # transfer lookup args to template args, based on those available
- # in getargspec
- for kw in inspect.getargspec(Template.__init__)[0]:
- if kw in lookup_options:
- self.tmpl_options[kw] = lookup_options[kw]
-
- def load_template(self, templatename, template_string=None):
- """Loads a template from a file or a string"""
- if template_string is not None:
- return Template(template_string, **self.tmpl_options)
- # Translate TG dot notation to normal / template path
- if '/' not in templatename:
- templatename = '/' + templatename.replace('.', '/') + '.' +\
- self.extension
-
- # Lookup template
- return self.lookup.get_template(templatename)
-
- def render(self, info, format="html", fragment=False, template=None):
- if isinstance(template, compat.string_types):
- template = self.load_template(template)
-
- # Load extra vars func if provided
- if self.extra_vars_func:
- info.update(self.extra_vars_func())
-
- return template.render(**info)
-
diff --git a/Darwin/lib/python2.7/site-packages/mako/filters.py b/Darwin/lib/python2.7/site-packages/mako/filters.py
deleted file mode 100644
index 77aaf75..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/filters.py
+++ /dev/null
@@ -1,196 +0,0 @@
-# mako/filters.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-
-import re
-import codecs
-
-from mako.compat import quote_plus, unquote_plus, codepoint2name, \
- name2codepoint
-
-from mako import compat
-
-xml_escapes = {
- '&': '&',
- '>': '>',
- '<': '<',
- '"': '"', # also " in html-only
- "'": ''' # also ' in html-only
-}
-
-# XXX: " is valid in HTML and XML
-# ' is not valid HTML, but is valid XML
-
-def legacy_html_escape(s):
- """legacy HTML escape for non-unicode mode."""
- s = s.replace("&", "&")
- s = s.replace(">", ">")
- s = s.replace("<", "<")
- s = s.replace('"', """)
- s = s.replace("'", "'")
- return s
-
-
-try:
- import markupsafe
- html_escape = markupsafe.escape
-except ImportError:
- html_escape = legacy_html_escape
-
-def xml_escape(string):
- return re.sub(r'([&<"\'>])', lambda m: xml_escapes[m.group()], string)
-
-def url_escape(string):
- # convert into a list of octets
- string = string.encode("utf8")
- return quote_plus(string)
-
-def url_unescape(string):
- text = unquote_plus(string)
- if not is_ascii_str(text):
- text = text.decode("utf8")
- return text
-
-def trim(string):
- return string.strip()
-
-
-class Decode(object):
- def __getattr__(self, key):
- def decode(x):
- if isinstance(x, compat.text_type):
- return x
- elif not isinstance(x, compat.binary_type):
- return compat.text_type(str(x), encoding=key)
- else:
- return compat.text_type(x, encoding=key)
- return decode
-decode = Decode()
-
-
-_ASCII_re = re.compile(r'\A[\x00-\x7f]*\Z')
-
-def is_ascii_str(text):
- return isinstance(text, str) and _ASCII_re.match(text)
-
-################################################################
-
-class XMLEntityEscaper(object):
- def __init__(self, codepoint2name, name2codepoint):
- self.codepoint2entity = dict([(c, compat.text_type('&%s;' % n))
- for c, n in codepoint2name.items()])
- self.name2codepoint = name2codepoint
-
- def escape_entities(self, text):
- """Replace characters with their character entity references.
-
- Only characters corresponding to a named entity are replaced.
- """
- return compat.text_type(text).translate(self.codepoint2entity)
-
- def __escape(self, m):
- codepoint = ord(m.group())
- try:
- return self.codepoint2entity[codepoint]
- except (KeyError, IndexError):
- return '%X;' % codepoint
-
-
- __escapable = re.compile(r'["&<>]|[^\x00-\x7f]')
-
- def escape(self, text):
- """Replace characters with their character references.
-
- Replace characters by their named entity references.
- Non-ASCII characters, if they do not have a named entity reference,
- are replaced by numerical character references.
-
- The return value is guaranteed to be ASCII.
- """
- return self.__escapable.sub(self.__escape, compat.text_type(text)
- ).encode('ascii')
-
- # XXX: This regexp will not match all valid XML entity names__.
- # (It punts on details involving involving CombiningChars and Extenders.)
- #
- # .. __: http://www.w3.org/TR/2000/REC-xml-20001006#NT-EntityRef
- __characterrefs = re.compile(r'''& (?:
- \#(\d+)
- | \#x([\da-f]+)
- | ( (?!\d) [:\w] [-.:\w]+ )
- ) ;''',
- re.X | re.UNICODE)
-
- def __unescape(self, m):
- dval, hval, name = m.groups()
- if dval:
- codepoint = int(dval)
- elif hval:
- codepoint = int(hval, 16)
- else:
- codepoint = self.name2codepoint.get(name, 0xfffd)
- # U+FFFD = "REPLACEMENT CHARACTER"
- if codepoint < 128:
- return chr(codepoint)
- return chr(codepoint)
-
- def unescape(self, text):
- """Unescape character references.
-
- All character references (both entity references and numerical
- character references) are unescaped.
- """
- return self.__characterrefs.sub(self.__unescape, text)
-
-
-_html_entities_escaper = XMLEntityEscaper(codepoint2name, name2codepoint)
-
-html_entities_escape = _html_entities_escaper.escape_entities
-html_entities_unescape = _html_entities_escaper.unescape
-
-
-def htmlentityreplace_errors(ex):
- """An encoding error handler.
-
- This python `codecs`_ error handler replaces unencodable
- characters with HTML entities, or, if no HTML entity exists for
- the character, XML character references.
-
- >>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace')
- 'The cost was €12.'
- """
- if isinstance(ex, UnicodeEncodeError):
- # Handle encoding errors
- bad_text = ex.object[ex.start:ex.end]
- text = _html_entities_escaper.escape(bad_text)
- return (compat.text_type(text), ex.end)
- raise ex
-
-codecs.register_error('htmlentityreplace', htmlentityreplace_errors)
-
-
-# TODO: options to make this dynamic per-compilation will be added in a later
-# release
-DEFAULT_ESCAPES = {
- 'x': 'filters.xml_escape',
- 'h': 'filters.html_escape',
- 'u': 'filters.url_escape',
- 'trim': 'filters.trim',
- 'entity': 'filters.html_entities_escape',
- 'unicode': 'unicode',
- 'decode': 'decode',
- 'str': 'str',
- 'n': 'n'
-}
-
-if compat.py3k:
- DEFAULT_ESCAPES.update({
- 'unicode': 'str'
- })
-
-NON_UNICODE_ESCAPES = DEFAULT_ESCAPES.copy()
-NON_UNICODE_ESCAPES['h'] = 'filters.legacy_html_escape'
-
diff --git a/Darwin/lib/python2.7/site-packages/mako/lexer.py b/Darwin/lib/python2.7/site-packages/mako/lexer.py
deleted file mode 100644
index 42b9ecd..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/lexer.py
+++ /dev/null
@@ -1,441 +0,0 @@
-# mako/lexer.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""provides the Lexer class for parsing template strings into parse trees."""
-
-import re
-import codecs
-from mako import parsetree, exceptions, compat
-from mako.pygen import adjust_whitespace
-
-_regexp_cache = {}
-
-class Lexer(object):
- def __init__(self, text, filename=None,
- disable_unicode=False,
- input_encoding=None, preprocessor=None):
- self.text = text
- self.filename = filename
- self.template = parsetree.TemplateNode(self.filename)
- self.matched_lineno = 1
- self.matched_charpos = 0
- self.lineno = 1
- self.match_position = 0
- self.tag = []
- self.control_line = []
- self.ternary_stack = []
- self.disable_unicode = disable_unicode
- self.encoding = input_encoding
-
- if compat.py3k and disable_unicode:
- raise exceptions.UnsupportedError(
- "Mako for Python 3 does not "
- "support disabling Unicode")
-
- if preprocessor is None:
- self.preprocessor = []
- elif not hasattr(preprocessor, '__iter__'):
- self.preprocessor = [preprocessor]
- else:
- self.preprocessor = preprocessor
-
- @property
- def exception_kwargs(self):
- return {'source':self.text,
- 'lineno':self.matched_lineno,
- 'pos':self.matched_charpos,
- 'filename':self.filename}
-
- def match(self, regexp, flags=None):
- """compile the given regexp, cache the reg, and call match_reg()."""
-
- try:
- reg = _regexp_cache[(regexp, flags)]
- except KeyError:
- if flags:
- reg = re.compile(regexp, flags)
- else:
- reg = re.compile(regexp)
- _regexp_cache[(regexp, flags)] = reg
-
- return self.match_reg(reg)
-
- def match_reg(self, reg):
- """match the given regular expression object to the current text
- position.
-
- if a match occurs, update the current text and line position.
-
- """
-
- mp = self.match_position
-
- match = reg.match(self.text, self.match_position)
- if match:
- (start, end) = match.span()
- if end == start:
- self.match_position = end + 1
- else:
- self.match_position = end
- self.matched_lineno = self.lineno
- lines = re.findall(r"\n", self.text[mp:self.match_position])
- cp = mp - 1
- while (cp >= 0 and cp 0:
- brace_level -= 1
- continue
- return \
- self.text[startpos:\
- self.match_position-len(match.group(1))],\
- match.group(1)
- match = self.match(r"(.*?)(?=\"|\'|#|%s)" % text_re, re.S)
- if match:
- brace_level += match.group(1).count('{')
- brace_level -= match.group(1).count('}')
- continue
- raise exceptions.SyntaxException(
- "Expected: %s" %
- ','.join(text),
- **self.exception_kwargs)
-
- def append_node(self, nodecls, *args, **kwargs):
- kwargs.setdefault('source', self.text)
- kwargs.setdefault('lineno', self.matched_lineno)
- kwargs.setdefault('pos', self.matched_charpos)
- kwargs['filename'] = self.filename
- node = nodecls(*args, **kwargs)
- if len(self.tag):
- self.tag[-1].nodes.append(node)
- else:
- self.template.nodes.append(node)
- # build a set of child nodes for the control line
- # (used for loop variable detection)
- # also build a set of child nodes on ternary control lines
- # (used for determining if a pass needs to be auto-inserted
- if self.control_line:
- control_frame = self.control_line[-1]
- control_frame.nodes.append(node)
- if not (isinstance(node, parsetree.ControlLine) and
- control_frame.is_ternary(node.keyword)):
- if self.ternary_stack and self.ternary_stack[-1]:
- self.ternary_stack[-1][-1].nodes.append(node)
- if isinstance(node, parsetree.Tag):
- if len(self.tag):
- node.parent = self.tag[-1]
- self.tag.append(node)
- elif isinstance(node, parsetree.ControlLine):
- if node.isend:
- self.control_line.pop()
- self.ternary_stack.pop()
- elif node.is_primary:
- self.control_line.append(node)
- self.ternary_stack.append([])
- elif self.control_line and \
- self.control_line[-1].is_ternary(node.keyword):
- self.ternary_stack[-1].append(node)
- elif self.control_line and \
- not self.control_line[-1].is_ternary(node.keyword):
- raise exceptions.SyntaxException(
- "Keyword '%s' not a legal ternary for keyword '%s'" %
- (node.keyword, self.control_line[-1].keyword),
- **self.exception_kwargs)
-
- _coding_re = re.compile(r'#.*coding[:=]\s*([-\w.]+).*\r?\n')
-
- def decode_raw_stream(self, text, decode_raw, known_encoding, filename):
- """given string/unicode or bytes/string, determine encoding
- from magic encoding comment, return body as unicode
- or raw if decode_raw=False
-
- """
- if isinstance(text, compat.text_type):
- m = self._coding_re.match(text)
- encoding = m and m.group(1) or known_encoding or 'ascii'
- return encoding, text
-
- if text.startswith(codecs.BOM_UTF8):
- text = text[len(codecs.BOM_UTF8):]
- parsed_encoding = 'utf-8'
- m = self._coding_re.match(text.decode('utf-8', 'ignore'))
- if m is not None and m.group(1) != 'utf-8':
- raise exceptions.CompileException(
- "Found utf-8 BOM in file, with conflicting "
- "magic encoding comment of '%s'" % m.group(1),
- text.decode('utf-8', 'ignore'),
- 0, 0, filename)
- else:
- m = self._coding_re.match(text.decode('utf-8', 'ignore'))
- if m:
- parsed_encoding = m.group(1)
- else:
- parsed_encoding = known_encoding or 'ascii'
-
- if decode_raw:
- try:
- text = text.decode(parsed_encoding)
- except UnicodeDecodeError:
- raise exceptions.CompileException(
- "Unicode decode operation of encoding '%s' failed" %
- parsed_encoding,
- text.decode('utf-8', 'ignore'),
- 0, 0, filename)
-
- return parsed_encoding, text
-
- def parse(self):
- self.encoding, self.text = self.decode_raw_stream(self.text,
- not self.disable_unicode,
- self.encoding,
- self.filename,)
-
- for preproc in self.preprocessor:
- self.text = preproc(self.text)
-
- # push the match marker past the
- # encoding comment.
- self.match_reg(self._coding_re)
-
- self.textlength = len(self.text)
-
- while (True):
- if self.match_position > self.textlength:
- break
-
- if self.match_end():
- break
- if self.match_expression():
- continue
- if self.match_control_line():
- continue
- if self.match_comment():
- continue
- if self.match_tag_start():
- continue
- if self.match_tag_end():
- continue
- if self.match_python_block():
- continue
- if self.match_text():
- continue
-
- if self.match_position > self.textlength:
- break
- raise exceptions.CompileException("assertion failed")
-
- if len(self.tag):
- raise exceptions.SyntaxException("Unclosed tag: <%%%s>" %
- self.tag[-1].keyword,
- **self.exception_kwargs)
- if len(self.control_line):
- raise exceptions.SyntaxException(
- "Unterminated control keyword: '%s'" %
- self.control_line[-1].keyword,
- self.text,
- self.control_line[-1].lineno,
- self.control_line[-1].pos, self.filename)
- return self.template
-
- def match_tag_start(self):
- match = self.match(r'''
- \<% # opening tag
-
- ([\w\.\:]+) # keyword
-
- ((?:\s+\w+|\s*=\s*|".*?"|'.*?')*) # attrname, = \
- # sign, string expression
-
- \s* # more whitespace
-
- (/)?> # closing
-
- ''',
-
- re.I | re.S | re.X)
-
- if match:
- keyword, attr, isend = match.groups()
- self.keyword = keyword
- attributes = {}
- if attr:
- for att in re.findall(
- r"\s*(\w+)\s*=\s*(?:'([^']*)'|\"([^\"]*)\")", attr):
- key, val1, val2 = att
- text = val1 or val2
- text = text.replace('\r\n', '\n')
- attributes[key] = text
- self.append_node(parsetree.Tag, keyword, attributes)
- if isend:
- self.tag.pop()
- else:
- if keyword == 'text':
- match = self.match(r'(.*?)(?=\%text>)', re.S)
- if not match:
- raise exceptions.SyntaxException(
- "Unclosed tag: <%%%s>" %
- self.tag[-1].keyword,
- **self.exception_kwargs)
- self.append_node(parsetree.Text, match.group(1))
- return self.match_tag_end()
- return True
- else:
- return False
-
- def match_tag_end(self):
- match = self.match(r'\%[\t ]*(.+?)[\t ]*>')
- if match:
- if not len(self.tag):
- raise exceptions.SyntaxException(
- "Closing tag without opening tag: %%%s>" %
- match.group(1),
- **self.exception_kwargs)
- elif self.tag[-1].keyword != match.group(1):
- raise exceptions.SyntaxException(
- "Closing tag %%%s> does not match tag: <%%%s>" %
- (match.group(1), self.tag[-1].keyword),
- **self.exception_kwargs)
- self.tag.pop()
- return True
- else:
- return False
-
- def match_end(self):
- match = self.match(r'\Z', re.S)
- if match:
- string = match.group()
- if string:
- return string
- else:
- return True
- else:
- return False
-
- def match_text(self):
- match = self.match(r"""
- (.*?) # anything, followed by:
- (
- (?<=\n)(?=[ \t]*(?=%|\#\#)) # an eval or line-based
- # comment preceded by a
- # consumed newline and whitespace
- |
- (?=\${) # an expression
- |
- (?=?[%&]) # a substitution or block or call start or end
- # - don't consume
- |
- (\\\r?\n) # an escaped newline - throw away
- |
- \Z # end of string
- )""", re.X | re.S)
-
- if match:
- text = match.group(1)
- if text:
- self.append_node(parsetree.Text, text)
- return True
- else:
- return False
-
- def match_python_block(self):
- match = self.match(r"<%(!)?")
- if match:
- line, pos = self.matched_lineno, self.matched_charpos
- text, end = self.parse_until_text(r'%>')
- # the trailing newline helps
- # compiler.parse() not complain about indentation
- text = adjust_whitespace(text) + "\n"
- self.append_node(
- parsetree.Code,
- text,
- match.group(1)=='!', lineno=line, pos=pos)
- return True
- else:
- return False
-
- def match_expression(self):
- match = self.match(r"\${")
- if match:
- line, pos = self.matched_lineno, self.matched_charpos
- text, end = self.parse_until_text(r'\|', r'}')
- if end == '|':
- escapes, end = self.parse_until_text(r'}')
- else:
- escapes = ""
- text = text.replace('\r\n', '\n')
- self.append_node(
- parsetree.Expression,
- text, escapes.strip(),
- lineno=line, pos=pos)
- return True
- else:
- return False
-
- def match_control_line(self):
- match = self.match(
- r"(?<=^)[\t ]*(%(?!%)|##)[\t ]*((?:(?:\\r?\n)|[^\r\n])*)"
- r"(?:\r?\n|\Z)", re.M)
- if match:
- operator = match.group(1)
- text = match.group(2)
- if operator == '%':
- m2 = re.match(r'(end)?(\w+)\s*(.*)', text)
- if not m2:
- raise exceptions.SyntaxException(
- "Invalid control line: '%s'" %
- text,
- **self.exception_kwargs)
- isend, keyword = m2.group(1, 2)
- isend = (isend is not None)
-
- if isend:
- if not len(self.control_line):
- raise exceptions.SyntaxException(
- "No starting keyword '%s' for '%s'" %
- (keyword, text),
- **self.exception_kwargs)
- elif self.control_line[-1].keyword != keyword:
- raise exceptions.SyntaxException(
- "Keyword '%s' doesn't match keyword '%s'" %
- (text, self.control_line[-1].keyword),
- **self.exception_kwargs)
- self.append_node(parsetree.ControlLine, keyword, isend, text)
- else:
- self.append_node(parsetree.Comment, text)
- return True
- else:
- return False
-
- def match_comment(self):
- """matches the multiline version of a comment"""
- match = self.match(r"<%doc>(.*?)%doc>", re.S)
- if match:
- self.append_node(parsetree.Comment, match.group(1))
- return True
- else:
- return False
-
diff --git a/Darwin/lib/python2.7/site-packages/mako/lookup.py b/Darwin/lib/python2.7/site-packages/mako/lookup.py
deleted file mode 100644
index 3edd101..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/lookup.py
+++ /dev/null
@@ -1,359 +0,0 @@
-# mako/lookup.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-import os, stat, posixpath, re
-from mako import exceptions, util
-from mako.template import Template
-
-try:
- import threading
-except:
- import dummy_threading as threading
-
-class TemplateCollection(object):
- """Represent a collection of :class:`.Template` objects,
- identifiable via URI.
-
- A :class:`.TemplateCollection` is linked to the usage of
- all template tags that address other templates, such
- as ``<%include>``, ``<%namespace>``, and ``<%inherit>``.
- The ``file`` attribute of each of those tags refers
- to a string URI that is passed to that :class:`.Template`
- object's :class:`.TemplateCollection` for resolution.
-
- :class:`.TemplateCollection` is an abstract class,
- with the usual default implementation being :class:`.TemplateLookup`.
-
- """
-
- def has_template(self, uri):
- """Return ``True`` if this :class:`.TemplateLookup` is
- capable of returning a :class:`.Template` object for the
- given ``uri``.
-
- :param uri: String URI of the template to be resolved.
-
- """
- try:
- self.get_template(uri)
- return True
- except exceptions.TemplateLookupException:
- return False
-
- def get_template(self, uri, relativeto=None):
- """Return a :class:`.Template` object corresponding to the given
- ``uri``.
-
- The default implementation raises
- :class:`.NotImplementedError`. Implementations should
- raise :class:`.TemplateLookupException` if the given ``uri``
- cannot be resolved.
-
- :param uri: String URI of the template to be resolved.
- :param relativeto: if present, the given ``uri`` is assumed to
- be relative to this URI.
-
- """
- raise NotImplementedError()
-
- def filename_to_uri(self, uri, filename):
- """Convert the given ``filename`` to a URI relative to
- this :class:`.TemplateCollection`."""
-
- return uri
-
- def adjust_uri(self, uri, filename):
- """Adjust the given ``uri`` based on the calling ``filename``.
-
- When this method is called from the runtime, the
- ``filename`` parameter is taken directly to the ``filename``
- attribute of the calling template. Therefore a custom
- :class:`.TemplateCollection` subclass can place any string
- identifier desired in the ``filename`` parameter of the
- :class:`.Template` objects it constructs and have them come back
- here.
-
- """
- return uri
-
-class TemplateLookup(TemplateCollection):
- """Represent a collection of templates that locates template source files
- from the local filesystem.
-
- The primary argument is the ``directories`` argument, the list of
- directories to search:
-
- .. sourcecode:: python
-
- lookup = TemplateLookup(["/path/to/templates"])
- some_template = lookup.get_template("/index.html")
-
- The :class:`.TemplateLookup` can also be given :class:`.Template` objects
- programatically using :meth:`.put_string` or :meth:`.put_template`:
-
- .. sourcecode:: python
-
- lookup = TemplateLookup()
- lookup.put_string("base.html", '''
- ${self.next()}
- ''')
- lookup.put_string("hello.html", '''
- <%include file='base.html'/>
-
- Hello, world !
- ''')
-
-
- :param directories: A list of directory names which will be
- searched for a particular template URI. The URI is appended
- to each directory and the filesystem checked.
-
- :param collection_size: Approximate size of the collection used
- to store templates. If left at its default of ``-1``, the size
- is unbounded, and a plain Python dictionary is used to
- relate URI strings to :class:`.Template` instances.
- Otherwise, a least-recently-used cache object is used which
- will maintain the size of the collection approximately to
- the number given.
-
- :param filesystem_checks: When at its default value of ``True``,
- each call to :meth:`.TemplateLookup.get_template()` will
- compare the filesystem last modified time to the time in
- which an existing :class:`.Template` object was created.
- This allows the :class:`.TemplateLookup` to regenerate a
- new :class:`.Template` whenever the original source has
- been updated. Set this to ``False`` for a very minor
- performance increase.
-
- :param modulename_callable: A callable which, when present,
- is passed the path of the source file as well as the
- requested URI, and then returns the full path of the
- generated Python module file. This is used to inject
- alternate schemes for Python module location. If left at
- its default of ``None``, the built in system of generation
- based on ``module_directory`` plus ``uri`` is used.
-
- All other keyword parameters available for
- :class:`.Template` are mirrored here. When new
- :class:`.Template` objects are created, the keywords
- established with this :class:`.TemplateLookup` are passed on
- to each new :class:`.Template`.
-
- """
-
- def __init__(self,
- directories=None,
- module_directory=None,
- filesystem_checks=True,
- collection_size=-1,
- format_exceptions=False,
- error_handler=None,
- disable_unicode=False,
- bytestring_passthrough=False,
- output_encoding=None,
- encoding_errors='strict',
-
- cache_args=None,
- cache_impl='beaker',
- cache_enabled=True,
- cache_type=None,
- cache_dir=None,
- cache_url=None,
-
- modulename_callable=None,
- module_writer=None,
- default_filters=None,
- buffer_filters=(),
- strict_undefined=False,
- imports=None,
- future_imports=None,
- enable_loop=True,
- input_encoding=None,
- preprocessor=None,
- lexer_cls=None):
-
- self.directories = [posixpath.normpath(d) for d in
- util.to_list(directories, ())
- ]
- self.module_directory = module_directory
- self.modulename_callable = modulename_callable
- self.filesystem_checks = filesystem_checks
- self.collection_size = collection_size
-
- if cache_args is None:
- cache_args = {}
- # transfer deprecated cache_* args
- if cache_dir:
- cache_args.setdefault('dir', cache_dir)
- if cache_url:
- cache_args.setdefault('url', cache_url)
- if cache_type:
- cache_args.setdefault('type', cache_type)
-
- self.template_args = {
- 'format_exceptions':format_exceptions,
- 'error_handler':error_handler,
- 'disable_unicode':disable_unicode,
- 'bytestring_passthrough':bytestring_passthrough,
- 'output_encoding':output_encoding,
- 'cache_impl':cache_impl,
- 'encoding_errors':encoding_errors,
- 'input_encoding':input_encoding,
- 'module_directory':module_directory,
- 'module_writer':module_writer,
- 'cache_args':cache_args,
- 'cache_enabled':cache_enabled,
- 'default_filters':default_filters,
- 'buffer_filters':buffer_filters,
- 'strict_undefined':strict_undefined,
- 'imports':imports,
- 'future_imports':future_imports,
- 'enable_loop':enable_loop,
- 'preprocessor':preprocessor,
- 'lexer_cls':lexer_cls
- }
-
- if collection_size == -1:
- self._collection = {}
- self._uri_cache = {}
- else:
- self._collection = util.LRUCache(collection_size)
- self._uri_cache = util.LRUCache(collection_size)
- self._mutex = threading.Lock()
-
- def get_template(self, uri):
- """Return a :class:`.Template` object corresponding to the given
- ``uri``.
-
- .. note:: The ``relativeto`` argument is not supported here at the moment.
-
- """
-
- try:
- if self.filesystem_checks:
- return self._check(uri, self._collection[uri])
- else:
- return self._collection[uri]
- except KeyError:
- u = re.sub(r'^\/+', '', uri)
- for dir in self.directories:
- srcfile = posixpath.normpath(posixpath.join(dir, u))
- if os.path.isfile(srcfile):
- return self._load(srcfile, uri)
- else:
- raise exceptions.TopLevelLookupException(
- "Cant locate template for uri %r" % uri)
-
- def adjust_uri(self, uri, relativeto):
- """Adjust the given ``uri`` based on the given relative URI."""
-
- key = (uri, relativeto)
- if key in self._uri_cache:
- return self._uri_cache[key]
-
- if uri[0] != '/':
- if relativeto is not None:
- v = self._uri_cache[key] = posixpath.join(
- posixpath.dirname(relativeto), uri)
- else:
- v = self._uri_cache[key] = '/' + uri
- else:
- v = self._uri_cache[key] = uri
- return v
-
-
- def filename_to_uri(self, filename):
- """Convert the given ``filename`` to a URI relative to
- this :class:`.TemplateCollection`."""
-
- try:
- return self._uri_cache[filename]
- except KeyError:
- value = self._relativeize(filename)
- self._uri_cache[filename] = value
- return value
-
- def _relativeize(self, filename):
- """Return the portion of a filename that is 'relative'
- to the directories in this lookup.
-
- """
-
- filename = posixpath.normpath(filename)
- for dir in self.directories:
- if filename[0:len(dir)] == dir:
- return filename[len(dir):]
- else:
- return None
-
- def _load(self, filename, uri):
- self._mutex.acquire()
- try:
- try:
- # try returning from collection one
- # more time in case concurrent thread already loaded
- return self._collection[uri]
- except KeyError:
- pass
- try:
- if self.modulename_callable is not None:
- module_filename = self.modulename_callable(filename, uri)
- else:
- module_filename = None
- self._collection[uri] = template = Template(
- uri=uri,
- filename=posixpath.normpath(filename),
- lookup=self,
- module_filename=module_filename,
- **self.template_args)
- return template
- except:
- # if compilation fails etc, ensure
- # template is removed from collection,
- # re-raise
- self._collection.pop(uri, None)
- raise
- finally:
- self._mutex.release()
-
- def _check(self, uri, template):
- if template.filename is None:
- return template
-
- try:
- template_stat = os.stat(template.filename)
- if template.module._modified_time < \
- template_stat[stat.ST_MTIME]:
- self._collection.pop(uri, None)
- return self._load(template.filename, uri)
- else:
- return template
- except OSError:
- self._collection.pop(uri, None)
- raise exceptions.TemplateLookupException(
- "Cant locate template for uri %r" % uri)
-
-
- def put_string(self, uri, text):
- """Place a new :class:`.Template` object into this
- :class:`.TemplateLookup`, based on the given string of
- ``text``.
-
- """
- self._collection[uri] = Template(
- text,
- lookup=self,
- uri=uri,
- **self.template_args)
-
- def put_template(self, uri, template):
- """Place a new :class:`.Template` object into this
- :class:`.TemplateLookup`, based on the given
- :class:`.Template` object.
-
- """
- self._collection[uri] = template
-
diff --git a/Darwin/lib/python2.7/site-packages/mako/parsetree.py b/Darwin/lib/python2.7/site-packages/mako/parsetree.py
deleted file mode 100644
index 1c04c26..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/parsetree.py
+++ /dev/null
@@ -1,594 +0,0 @@
-# mako/parsetree.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""defines the parse tree components for Mako templates."""
-
-from mako import exceptions, ast, util, filters, compat
-import re
-
-class Node(object):
- """base class for a Node in the parse tree."""
-
- def __init__(self, source, lineno, pos, filename):
- self.source = source
- self.lineno = lineno
- self.pos = pos
- self.filename = filename
-
- @property
- def exception_kwargs(self):
- return {'source': self.source, 'lineno': self.lineno,
- 'pos': self.pos, 'filename': self.filename}
-
- def get_children(self):
- return []
-
- def accept_visitor(self, visitor):
- def traverse(node):
- for n in node.get_children():
- n.accept_visitor(visitor)
-
- method = getattr(visitor, "visit" + self.__class__.__name__, traverse)
- method(self)
-
-class TemplateNode(Node):
- """a 'container' node that stores the overall collection of nodes."""
-
- def __init__(self, filename):
- super(TemplateNode, self).__init__('', 0, 0, filename)
- self.nodes = []
- self.page_attributes = {}
-
- def get_children(self):
- return self.nodes
-
- def __repr__(self):
- return "TemplateNode(%s, %r)" % (
- util.sorted_dict_repr(self.page_attributes),
- self.nodes)
-
-class ControlLine(Node):
- """defines a control line, a line-oriented python line or end tag.
-
- e.g.::
-
- % if foo:
- (markup)
- % endif
-
- """
-
- has_loop_context = False
-
- def __init__(self, keyword, isend, text, **kwargs):
- super(ControlLine, self).__init__(**kwargs)
- self.text = text
- self.keyword = keyword
- self.isend = isend
- self.is_primary = keyword in ['for', 'if', 'while', 'try', 'with']
- self.nodes = []
- if self.isend:
- self._declared_identifiers = []
- self._undeclared_identifiers = []
- else:
- code = ast.PythonFragment(text, **self.exception_kwargs)
- self._declared_identifiers = code.declared_identifiers
- self._undeclared_identifiers = code.undeclared_identifiers
-
- def get_children(self):
- return self.nodes
-
- def declared_identifiers(self):
- return self._declared_identifiers
-
- def undeclared_identifiers(self):
- return self._undeclared_identifiers
-
- def is_ternary(self, keyword):
- """return true if the given keyword is a ternary keyword
- for this ControlLine"""
-
- return keyword in {
- 'if':set(['else', 'elif']),
- 'try':set(['except', 'finally']),
- 'for':set(['else'])
- }.get(self.keyword, [])
-
- def __repr__(self):
- return "ControlLine(%r, %r, %r, %r)" % (
- self.keyword,
- self.text,
- self.isend,
- (self.lineno, self.pos)
- )
-
-class Text(Node):
- """defines plain text in the template."""
-
- def __init__(self, content, **kwargs):
- super(Text, self).__init__(**kwargs)
- self.content = content
-
- def __repr__(self):
- return "Text(%r, %r)" % (self.content, (self.lineno, self.pos))
-
-class Code(Node):
- """defines a Python code block, either inline or module level.
-
- e.g.::
-
- inline:
- <%
- x = 12
- %>
-
- module level:
- <%!
- import logger
- %>
-
- """
-
- def __init__(self, text, ismodule, **kwargs):
- super(Code, self).__init__(**kwargs)
- self.text = text
- self.ismodule = ismodule
- self.code = ast.PythonCode(text, **self.exception_kwargs)
-
- def declared_identifiers(self):
- return self.code.declared_identifiers
-
- def undeclared_identifiers(self):
- return self.code.undeclared_identifiers
-
- def __repr__(self):
- return "Code(%r, %r, %r)" % (
- self.text,
- self.ismodule,
- (self.lineno, self.pos)
- )
-
-class Comment(Node):
- """defines a comment line.
-
- # this is a comment
-
- """
-
- def __init__(self, text, **kwargs):
- super(Comment, self).__init__(**kwargs)
- self.text = text
-
- def __repr__(self):
- return "Comment(%r, %r)" % (self.text, (self.lineno, self.pos))
-
-class Expression(Node):
- """defines an inline expression.
-
- ${x+y}
-
- """
-
- def __init__(self, text, escapes, **kwargs):
- super(Expression, self).__init__(**kwargs)
- self.text = text
- self.escapes = escapes
- self.escapes_code = ast.ArgumentList(escapes, **self.exception_kwargs)
- self.code = ast.PythonCode(text, **self.exception_kwargs)
-
- def declared_identifiers(self):
- return []
-
- def undeclared_identifiers(self):
- # TODO: make the "filter" shortcut list configurable at parse/gen time
- return self.code.undeclared_identifiers.union(
- self.escapes_code.undeclared_identifiers.difference(
- set(filters.DEFAULT_ESCAPES.keys())
- )
- ).difference(self.code.declared_identifiers)
-
- def __repr__(self):
- return "Expression(%r, %r, %r)" % (
- self.text,
- self.escapes_code.args,
- (self.lineno, self.pos)
- )
-
-class _TagMeta(type):
- """metaclass to allow Tag to produce a subclass according to
- its keyword"""
-
- _classmap = {}
-
- def __init__(cls, clsname, bases, dict):
- if getattr(cls, '__keyword__', None) is not None:
- cls._classmap[cls.__keyword__] = cls
- super(_TagMeta, cls).__init__(clsname, bases, dict)
-
- def __call__(cls, keyword, attributes, **kwargs):
- if ":" in keyword:
- ns, defname = keyword.split(':')
- return type.__call__(CallNamespaceTag, ns, defname,
- attributes, **kwargs)
-
- try:
- cls = _TagMeta._classmap[keyword]
- except KeyError:
- raise exceptions.CompileException(
- "No such tag: '%s'" % keyword,
- source=kwargs['source'],
- lineno=kwargs['lineno'],
- pos=kwargs['pos'],
- filename=kwargs['filename']
- )
- return type.__call__(cls, keyword, attributes, **kwargs)
-
-class Tag(compat.with_metaclass(_TagMeta, Node)):
- """abstract base class for tags.
-
- <%sometag/>
-
- <%someothertag>
- stuff
- %someothertag>
-
- """
- __keyword__ = None
-
- def __init__(self, keyword, attributes, expressions,
- nonexpressions, required, **kwargs):
- """construct a new Tag instance.
-
- this constructor not called directly, and is only called
- by subclasses.
-
- :param keyword: the tag keyword
-
- :param attributes: raw dictionary of attribute key/value pairs
-
- :param expressions: a set of identifiers that are legal attributes,
- which can also contain embedded expressions
-
- :param nonexpressions: a set of identifiers that are legal
- attributes, which cannot contain embedded expressions
-
- :param \**kwargs:
- other arguments passed to the Node superclass (lineno, pos)
-
- """
- super(Tag, self).__init__(**kwargs)
- self.keyword = keyword
- self.attributes = attributes
- self._parse_attributes(expressions, nonexpressions)
- missing = [r for r in required if r not in self.parsed_attributes]
- if len(missing):
- raise exceptions.CompileException(
- "Missing attribute(s): %s" %
- ",".join([repr(m) for m in missing]),
- **self.exception_kwargs)
- self.parent = None
- self.nodes = []
-
- def is_root(self):
- return self.parent is None
-
- def get_children(self):
- return self.nodes
-
- def _parse_attributes(self, expressions, nonexpressions):
- undeclared_identifiers = set()
- self.parsed_attributes = {}
- for key in self.attributes:
- if key in expressions:
- expr = []
- for x in re.compile(r'(\${.+?})',
- re.S).split(self.attributes[key]):
- m = re.compile(r'^\${(.+?)}$', re.S).match(x)
- if m:
- code = ast.PythonCode(m.group(1).rstrip(),
- **self.exception_kwargs)
- # we aren't discarding "declared_identifiers" here,
- # which we do so that list comprehension-declared
- # variables aren't counted. As yet can't find a
- # condition that requires it here.
- undeclared_identifiers = \
- undeclared_identifiers.union(
- code.undeclared_identifiers)
- expr.append('(%s)' % m.group(1))
- else:
- if x:
- expr.append(repr(x))
- self.parsed_attributes[key] = " + ".join(expr) or repr('')
- elif key in nonexpressions:
- if re.search(r'\${.+?}', self.attributes[key]):
- raise exceptions.CompileException(
- "Attibute '%s' in tag '%s' does not allow embedded "
- "expressions" % (key, self.keyword),
- **self.exception_kwargs)
- self.parsed_attributes[key] = repr(self.attributes[key])
- else:
- raise exceptions.CompileException(
- "Invalid attribute for tag '%s': '%s'" %
- (self.keyword, key),
- **self.exception_kwargs)
- self.expression_undeclared_identifiers = undeclared_identifiers
-
- def declared_identifiers(self):
- return []
-
- def undeclared_identifiers(self):
- return self.expression_undeclared_identifiers
-
- def __repr__(self):
- return "%s(%r, %s, %r, %r)" % (self.__class__.__name__,
- self.keyword,
- util.sorted_dict_repr(self.attributes),
- (self.lineno, self.pos),
- self.nodes
- )
-
-class IncludeTag(Tag):
- __keyword__ = 'include'
-
- def __init__(self, keyword, attributes, **kwargs):
- super(IncludeTag, self).__init__(
- keyword,
- attributes,
- ('file', 'import', 'args'),
- (), ('file',), **kwargs)
- self.page_args = ast.PythonCode(
- "__DUMMY(%s)" % attributes.get('args', ''),
- **self.exception_kwargs)
-
- def declared_identifiers(self):
- return []
-
- def undeclared_identifiers(self):
- identifiers = self.page_args.undeclared_identifiers.\
- difference(set(["__DUMMY"])).\
- difference(self.page_args.declared_identifiers)
- return identifiers.union(super(IncludeTag, self).
- undeclared_identifiers())
-
-class NamespaceTag(Tag):
- __keyword__ = 'namespace'
-
- def __init__(self, keyword, attributes, **kwargs):
- super(NamespaceTag, self).__init__(
- keyword, attributes,
- ('file',),
- ('name','inheritable',
- 'import','module'),
- (), **kwargs)
-
- self.name = attributes.get('name', '__anon_%s' % hex(abs(id(self))))
- if not 'name' in attributes and not 'import' in attributes:
- raise exceptions.CompileException(
- "'name' and/or 'import' attributes are required "
- "for <%namespace>",
- **self.exception_kwargs)
- if 'file' in attributes and 'module' in attributes:
- raise exceptions.CompileException(
- "<%namespace> may only have one of 'file' or 'module'",
- **self.exception_kwargs
- )
-
- def declared_identifiers(self):
- return []
-
-class TextTag(Tag):
- __keyword__ = 'text'
-
- def __init__(self, keyword, attributes, **kwargs):
- super(TextTag, self).__init__(
- keyword,
- attributes, (),
- ('filter'), (), **kwargs)
- self.filter_args = ast.ArgumentList(
- attributes.get('filter', ''),
- **self.exception_kwargs)
-
- def undeclared_identifiers(self):
- return self.filter_args.\
- undeclared_identifiers.\
- difference(filters.DEFAULT_ESCAPES.keys()).union(
- self.expression_undeclared_identifiers
- )
-
-class DefTag(Tag):
- __keyword__ = 'def'
-
- def __init__(self, keyword, attributes, **kwargs):
- expressions = ['buffered', 'cached'] + [
- c for c in attributes if c.startswith('cache_')]
-
-
- super(DefTag, self).__init__(
- keyword,
- attributes,
- expressions,
- ('name', 'filter', 'decorator'),
- ('name',),
- **kwargs)
- name = attributes['name']
- if re.match(r'^[\w_]+$', name):
- raise exceptions.CompileException(
- "Missing parenthesis in %def",
- **self.exception_kwargs)
- self.function_decl = ast.FunctionDecl("def " + name + ":pass",
- **self.exception_kwargs)
- self.name = self.function_decl.funcname
- self.decorator = attributes.get('decorator', '')
- self.filter_args = ast.ArgumentList(
- attributes.get('filter', ''),
- **self.exception_kwargs)
-
- is_anonymous = False
- is_block = False
-
- @property
- def funcname(self):
- return self.function_decl.funcname
-
- def get_argument_expressions(self, **kw):
- return self.function_decl.get_argument_expressions(**kw)
-
- def declared_identifiers(self):
- return self.function_decl.argnames
-
- def undeclared_identifiers(self):
- res = []
- for c in self.function_decl.defaults:
- res += list(ast.PythonCode(c, **self.exception_kwargs).
- undeclared_identifiers)
- return set(res).union(
- self.filter_args.\
- undeclared_identifiers.\
- difference(filters.DEFAULT_ESCAPES.keys())
- ).union(
- self.expression_undeclared_identifiers
- ).difference(
- self.function_decl.argnames
- )
-
-class BlockTag(Tag):
- __keyword__ = 'block'
-
- def __init__(self, keyword, attributes, **kwargs):
- expressions = ['buffered', 'cached', 'args'] + [
- c for c in attributes if c.startswith('cache_')]
-
- super(BlockTag, self).__init__(
- keyword,
- attributes,
- expressions,
- ('name','filter', 'decorator'),
- (),
- **kwargs)
- name = attributes.get('name')
- if name and not re.match(r'^[\w_]+$',name):
- raise exceptions.CompileException(
- "%block may not specify an argument signature",
- **self.exception_kwargs)
- if not name and attributes.get('args', None):
- raise exceptions.CompileException(
- "Only named %blocks may specify args",
- **self.exception_kwargs
- )
- self.body_decl = ast.FunctionArgs(attributes.get('args', ''),
- **self.exception_kwargs)
-
- self.name = name
- self.decorator = attributes.get('decorator', '')
- self.filter_args = ast.ArgumentList(
- attributes.get('filter', ''),
- **self.exception_kwargs)
-
-
- is_block = True
-
- @property
- def is_anonymous(self):
- return self.name is None
-
- @property
- def funcname(self):
- return self.name or "__M_anon_%d" % (self.lineno, )
-
- def get_argument_expressions(self, **kw):
- return self.body_decl.get_argument_expressions(**kw)
-
- def declared_identifiers(self):
- return self.body_decl.argnames
-
- def undeclared_identifiers(self):
- return (self.filter_args.\
- undeclared_identifiers.\
- difference(filters.DEFAULT_ESCAPES.keys())
- ).union(self.expression_undeclared_identifiers)
-
-
-
-class CallTag(Tag):
- __keyword__ = 'call'
-
- def __init__(self, keyword, attributes, **kwargs):
- super(CallTag, self).__init__(keyword, attributes,
- ('args'), ('expr',), ('expr',), **kwargs)
- self.expression = attributes['expr']
- self.code = ast.PythonCode(self.expression, **self.exception_kwargs)
- self.body_decl = ast.FunctionArgs(attributes.get('args', ''),
- **self.exception_kwargs)
-
- def declared_identifiers(self):
- return self.code.declared_identifiers.union(self.body_decl.argnames)
-
- def undeclared_identifiers(self):
- return self.code.undeclared_identifiers.\
- difference(self.code.declared_identifiers)
-
-class CallNamespaceTag(Tag):
-
- def __init__(self, namespace, defname, attributes, **kwargs):
- super(CallNamespaceTag, self).__init__(
- namespace + ":" + defname,
- attributes,
- tuple(attributes.keys()) + ('args', ),
- (),
- (),
- **kwargs)
-
- self.expression = "%s.%s(%s)" % (
- namespace,
- defname,
- ",".join(["%s=%s" % (k, v) for k, v in
- self.parsed_attributes.items()
- if k != 'args'])
- )
- self.code = ast.PythonCode(self.expression, **self.exception_kwargs)
- self.body_decl = ast.FunctionArgs(
- attributes.get('args', ''),
- **self.exception_kwargs)
-
- def declared_identifiers(self):
- return self.code.declared_identifiers.union(self.body_decl.argnames)
-
- def undeclared_identifiers(self):
- return self.code.undeclared_identifiers.\
- difference(self.code.declared_identifiers)
-
-class InheritTag(Tag):
- __keyword__ = 'inherit'
-
- def __init__(self, keyword, attributes, **kwargs):
- super(InheritTag, self).__init__(
- keyword, attributes,
- ('file',), (), ('file',), **kwargs)
-
-class PageTag(Tag):
- __keyword__ = 'page'
-
- def __init__(self, keyword, attributes, **kwargs):
- expressions = ['cached', 'args', 'expression_filter', 'enable_loop'] + [
- c for c in attributes if c.startswith('cache_')]
-
- super(PageTag, self).__init__(
- keyword,
- attributes,
- expressions,
- (),
- (),
- **kwargs)
- self.body_decl = ast.FunctionArgs(attributes.get('args', ''),
- **self.exception_kwargs)
- self.filter_args = ast.ArgumentList(
- attributes.get('expression_filter', ''),
- **self.exception_kwargs)
-
- def declared_identifiers(self):
- return self.body_decl.argnames
-
-
diff --git a/Darwin/lib/python2.7/site-packages/mako/pygen.py b/Darwin/lib/python2.7/site-packages/mako/pygen.py
deleted file mode 100644
index ed7ccc7..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/pygen.py
+++ /dev/null
@@ -1,282 +0,0 @@
-# mako/pygen.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""utilities for generating and formatting literal Python code."""
-
-import re
-from mako import exceptions
-
-class PythonPrinter(object):
- def __init__(self, stream):
- # indentation counter
- self.indent = 0
-
- # a stack storing information about why we incremented
- # the indentation counter, to help us determine if we
- # should decrement it
- self.indent_detail = []
-
- # the string of whitespace multiplied by the indent
- # counter to produce a line
- self.indentstring = " "
-
- # the stream we are writing to
- self.stream = stream
-
- # a list of lines that represents a buffered "block" of code,
- # which can be later printed relative to an indent level
- self.line_buffer = []
-
- self.in_indent_lines = False
-
- self._reset_multi_line_flags()
-
- def write(self, text):
- self.stream.write(text)
-
- def write_indented_block(self, block):
- """print a line or lines of python which already contain indentation.
-
- The indentation of the total block of lines will be adjusted to that of
- the current indent level."""
- self.in_indent_lines = False
- for l in re.split(r'\r?\n', block):
- self.line_buffer.append(l)
-
- def writelines(self, *lines):
- """print a series of lines of python."""
- for line in lines:
- self.writeline(line)
-
- def writeline(self, line):
- """print a line of python, indenting it according to the current
- indent level.
-
- this also adjusts the indentation counter according to the
- content of the line.
-
- """
-
- if not self.in_indent_lines:
- self._flush_adjusted_lines()
- self.in_indent_lines = True
-
- if (line is None or
- re.match(r"^\s*#",line) or
- re.match(r"^\s*$", line)
- ):
- hastext = False
- else:
- hastext = True
-
- is_comment = line and len(line) and line[0] == '#'
-
- # see if this line should decrease the indentation level
- if (not is_comment and
- (not hastext or self._is_unindentor(line))
- ):
-
- if self.indent > 0:
- self.indent -=1
- # if the indent_detail stack is empty, the user
- # probably put extra closures - the resulting
- # module wont compile.
- if len(self.indent_detail) == 0:
- raise exceptions.SyntaxException(
- "Too many whitespace closures")
- self.indent_detail.pop()
-
- if line is None:
- return
-
- # write the line
- self.stream.write(self._indent_line(line) + "\n")
-
- # see if this line should increase the indentation level.
- # note that a line can both decrase (before printing) and
- # then increase (after printing) the indentation level.
-
- if re.search(r":[ \t]*(?:#.*)?$", line):
- # increment indentation count, and also
- # keep track of what the keyword was that indented us,
- # if it is a python compound statement keyword
- # where we might have to look for an "unindent" keyword
- match = re.match(r"^\s*(if|try|elif|while|for|with)", line)
- if match:
- # its a "compound" keyword, so we will check for "unindentors"
- indentor = match.group(1)
- self.indent +=1
- self.indent_detail.append(indentor)
- else:
- indentor = None
- # its not a "compound" keyword. but lets also
- # test for valid Python keywords that might be indenting us,
- # else assume its a non-indenting line
- m2 = re.match(r"^\s*(def|class|else|elif|except|finally)",
- line)
- if m2:
- self.indent += 1
- self.indent_detail.append(indentor)
-
- def close(self):
- """close this printer, flushing any remaining lines."""
- self._flush_adjusted_lines()
-
- def _is_unindentor(self, line):
- """return true if the given line is an 'unindentor',
- relative to the last 'indent' event received.
-
- """
-
- # no indentation detail has been pushed on; return False
- if len(self.indent_detail) == 0:
- return False
-
- indentor = self.indent_detail[-1]
-
- # the last indent keyword we grabbed is not a
- # compound statement keyword; return False
- if indentor is None:
- return False
-
- # if the current line doesnt have one of the "unindentor" keywords,
- # return False
- match = re.match(r"^\s*(else|elif|except|finally).*\:", line)
- if not match:
- return False
-
- # whitespace matches up, we have a compound indentor,
- # and this line has an unindentor, this
- # is probably good enough
- return True
-
- # should we decide that its not good enough, heres
- # more stuff to check.
- #keyword = match.group(1)
-
- # match the original indent keyword
- #for crit in [
- # (r'if|elif', r'else|elif'),
- # (r'try', r'except|finally|else'),
- # (r'while|for', r'else'),
- #]:
- # if re.match(crit[0], indentor) and re.match(crit[1], keyword):
- # return True
-
- #return False
-
- def _indent_line(self, line, stripspace=''):
- """indent the given line according to the current indent level.
-
- stripspace is a string of space that will be truncated from the
- start of the line before indenting."""
-
- return re.sub(r"^%s" % stripspace, self.indentstring
- * self.indent, line)
-
- def _reset_multi_line_flags(self):
- """reset the flags which would indicate we are in a backslashed
- or triple-quoted section."""
-
- self.backslashed, self.triplequoted = False, False
-
- def _in_multi_line(self, line):
- """return true if the given line is part of a multi-line block,
- via backslash or triple-quote."""
-
- # we are only looking for explicitly joined lines here, not
- # implicit ones (i.e. brackets, braces etc.). this is just to
- # guard against the possibility of modifying the space inside of
- # a literal multiline string with unfortunately placed
- # whitespace
-
- current_state = (self.backslashed or self.triplequoted)
-
- if re.search(r"\\$", line):
- self.backslashed = True
- else:
- self.backslashed = False
-
- triples = len(re.findall(r"\"\"\"|\'\'\'", line))
- if triples == 1 or triples % 2 != 0:
- self.triplequoted = not self.triplequoted
-
- return current_state
-
- def _flush_adjusted_lines(self):
- stripspace = None
- self._reset_multi_line_flags()
-
- for entry in self.line_buffer:
- if self._in_multi_line(entry):
- self.stream.write(entry + "\n")
- else:
- entry = entry.expandtabs()
- if stripspace is None and re.search(r"^[ \t]*[^# \t]", entry):
- stripspace = re.match(r"^([ \t]*)", entry).group(1)
- self.stream.write(self._indent_line(entry, stripspace) + "\n")
-
- self.line_buffer = []
- self._reset_multi_line_flags()
-
-
-def adjust_whitespace(text):
- """remove the left-whitespace margin of a block of Python code."""
-
- state = [False, False]
- (backslashed, triplequoted) = (0, 1)
-
- def in_multi_line(line):
- start_state = (state[backslashed] or state[triplequoted])
-
- if re.search(r"\\$", line):
- state[backslashed] = True
- else:
- state[backslashed] = False
-
- def match(reg, t):
- m = re.match(reg, t)
- if m:
- return m, t[len(m.group(0)):]
- else:
- return None, t
-
- while line:
- if state[triplequoted]:
- m, line = match(r"%s" % state[triplequoted], line)
- if m:
- state[triplequoted] = False
- else:
- m, line = match(r".*?(?=%s|$)" % state[triplequoted], line)
- else:
- m, line = match(r'#', line)
- if m:
- return start_state
-
- m, line = match(r"\"\"\"|\'\'\'", line)
- if m:
- state[triplequoted] = m.group(0)
- continue
-
- m, line = match(r".*?(?=\"\"\"|\'\'\'|#|$)", line)
-
- return start_state
-
- def _indent_line(line, stripspace = ''):
- return re.sub(r"^%s" % stripspace, '', line)
-
- lines = []
- stripspace = None
-
- for line in re.split(r'\r?\n', text):
- if in_multi_line(line):
- lines.append(line)
- else:
- line = line.expandtabs()
- if stripspace is None and re.search(r"^[ \t]*[^# \t]", line):
- stripspace = re.match(r"^([ \t]*)", line).group(1)
- lines.append(_indent_line(line, stripspace))
- return "\n".join(lines)
diff --git a/Darwin/lib/python2.7/site-packages/mako/pyparser.py b/Darwin/lib/python2.7/site-packages/mako/pyparser.py
deleted file mode 100644
index 75301cc..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/pyparser.py
+++ /dev/null
@@ -1,572 +0,0 @@
-# mako/pyparser.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""Handles parsing of Python code.
-
-Parsing to AST is done via _ast on Python > 2.5, otherwise the compiler
-module is used.
-"""
-
-from mako import exceptions, util, compat
-from mako.compat import StringIO, arg_stringname
-import operator
-
-if compat.py3k:
- # words that cannot be assigned to (notably
- # smaller than the total keys in __builtins__)
- reserved = set(['True', 'False', 'None', 'print'])
-
- # the "id" attribute on a function node
- arg_id = operator.attrgetter('arg')
-else:
- # words that cannot be assigned to (notably
- # smaller than the total keys in __builtins__)
- reserved = set(['True', 'False', 'None'])
-
- # the "id" attribute on a function node
- arg_id = operator.attrgetter('id')
-
-
-try:
- import _ast
- util.restore__ast(_ast)
- from mako import _ast_util
-except ImportError:
- _ast = None
- from compiler import parse as compiler_parse
- from compiler import visitor
-
-
-
-def parse(code, mode='exec', **exception_kwargs):
- """Parse an expression into AST"""
-
-
- try:
- if _ast:
- return _ast_util.parse(code, '', mode)
- else:
- if isinstance(code, compat.text_type):
- code = code.encode('ascii', 'backslashreplace')
- return compiler_parse(code, mode)
- except Exception:
- raise exceptions.SyntaxException(
- "(%s) %s (%r)" % (
- compat.exception_as().__class__.__name__,
- compat.exception_as(),
- code[0:50]
- ), **exception_kwargs)
-
-
-if _ast:
- class FindIdentifiers(_ast_util.NodeVisitor):
-
- def __init__(self, listener, **exception_kwargs):
- self.in_function = False
- self.in_assign_targets = False
- self.local_ident_stack = set()
- self.listener = listener
- self.exception_kwargs = exception_kwargs
-
- def _add_declared(self, name):
- if not self.in_function:
- self.listener.declared_identifiers.add(name)
- else:
- self.local_ident_stack.add(name)
-
- def visit_ClassDef(self, node):
- self._add_declared(node.name)
-
- def visit_Assign(self, node):
-
- # flip around the visiting of Assign so the expression gets
- # evaluated first, in the case of a clause like "x=x+5" (x
- # is undeclared)
-
- self.visit(node.value)
- in_a = self.in_assign_targets
- self.in_assign_targets = True
- for n in node.targets:
- self.visit(n)
- self.in_assign_targets = in_a
-
- if compat.py3k:
-
- # ExceptHandler is in Python 2, but this block only works in
- # Python 3 (and is required there)
-
- def visit_ExceptHandler(self, node):
- if node.name is not None:
- self._add_declared(node.name)
- if node.type is not None:
- self.listener.undeclared_identifiers.add(node.type.id)
- for statement in node.body:
- self.visit(statement)
-
- def visit_Lambda(self, node, *args):
- self._visit_function(node, True)
-
- def visit_FunctionDef(self, node):
- self._add_declared(node.name)
- self._visit_function(node, False)
-
- def _expand_tuples(self, args):
- for arg in args:
- if isinstance(arg, _ast.Tuple):
- for n in arg.elts:
- yield n
- else:
- yield arg
-
- def _visit_function(self, node, islambda):
-
- # push function state onto stack. dont log any more
- # identifiers as "declared" until outside of the function,
- # but keep logging identifiers as "undeclared". track
- # argument names in each function header so they arent
- # counted as "undeclared"
-
- inf = self.in_function
- self.in_function = True
-
- local_ident_stack = self.local_ident_stack
- self.local_ident_stack = local_ident_stack.union([
- arg_id(arg) for arg in self._expand_tuples(node.args.args)
- ])
- if islambda:
- self.visit(node.body)
- else:
- for n in node.body:
- self.visit(n)
- self.in_function = inf
- self.local_ident_stack = local_ident_stack
-
- def visit_For(self, node):
-
- # flip around visit
-
- self.visit(node.iter)
- self.visit(node.target)
- for statement in node.body:
- self.visit(statement)
- for statement in node.orelse:
- self.visit(statement)
-
- def visit_Name(self, node):
- if isinstance(node.ctx, _ast.Store):
- # this is eqiuvalent to visit_AssName in
- # compiler
- self._add_declared(node.id)
- elif node.id not in reserved and node.id \
- not in self.listener.declared_identifiers and node.id \
- not in self.local_ident_stack:
- self.listener.undeclared_identifiers.add(node.id)
-
- def visit_Import(self, node):
- for name in node.names:
- if name.asname is not None:
- self._add_declared(name.asname)
- else:
- self._add_declared(name.name.split('.')[0])
-
- def visit_ImportFrom(self, node):
- for name in node.names:
- if name.asname is not None:
- self._add_declared(name.asname)
- else:
- if name.name == '*':
- raise exceptions.CompileException(
- "'import *' is not supported, since all identifier "
- "names must be explicitly declared. Please use the "
- "form 'from import , , "
- "...' instead.", **self.exception_kwargs)
- self._add_declared(name.name)
-
-
- class FindTuple(_ast_util.NodeVisitor):
-
- def __init__(self, listener, code_factory, **exception_kwargs):
- self.listener = listener
- self.exception_kwargs = exception_kwargs
- self.code_factory = code_factory
-
- def visit_Tuple(self, node):
- for n in node.elts:
- p = self.code_factory(n, **self.exception_kwargs)
- self.listener.codeargs.append(p)
- self.listener.args.append(ExpressionGenerator(n).value())
- self.listener.declared_identifiers = \
- self.listener.declared_identifiers.union(
- p.declared_identifiers)
- self.listener.undeclared_identifiers = \
- self.listener.undeclared_identifiers.union(
- p.undeclared_identifiers)
-
-
- class ParseFunc(_ast_util.NodeVisitor):
-
- def __init__(self, listener, **exception_kwargs):
- self.listener = listener
- self.exception_kwargs = exception_kwargs
-
- def visit_FunctionDef(self, node):
- self.listener.funcname = node.name
- argnames = [arg_id(arg) for arg in node.args.args]
- if node.args.vararg:
- argnames.append(arg_stringname(node.args.vararg))
- if node.args.kwarg:
- argnames.append(arg_stringname(node.args.kwarg))
- self.listener.argnames = argnames
- self.listener.defaults = node.args.defaults # ast
- self.listener.varargs = node.args.vararg
- self.listener.kwargs = node.args.kwarg
-
- class ExpressionGenerator(object):
-
- def __init__(self, astnode):
- self.generator = _ast_util.SourceGenerator(' ' * 4)
- self.generator.visit(astnode)
-
- def value(self):
- return ''.join(self.generator.result)
-else:
- class FindIdentifiers(object):
-
- def __init__(self, listener, **exception_kwargs):
- self.in_function = False
- self.local_ident_stack = set()
- self.listener = listener
- self.exception_kwargs = exception_kwargs
-
- def _add_declared(self, name):
- if not self.in_function:
- self.listener.declared_identifiers.add(name)
- else:
- self.local_ident_stack.add(name)
-
- def visitClass(self, node, *args):
- self._add_declared(node.name)
-
- def visitAssName(self, node, *args):
- self._add_declared(node.name)
-
- def visitAssign(self, node, *args):
-
- # flip around the visiting of Assign so the expression gets
- # evaluated first, in the case of a clause like "x=x+5" (x
- # is undeclared)
- self.visit(node.expr, *args)
- for n in node.nodes:
- self.visit(n, *args)
-
- def visitLambda(self, node, *args):
- self._visit_function(node, args)
-
- def visitFunction(self, node, *args):
- self._add_declared(node.name)
- self._visit_function(node, args)
-
- def _expand_tuples(self, args):
- for arg in args:
- if isinstance(arg, tuple):
- for n in arg:
- yield n
- else:
- yield arg
-
- def _visit_function(self, node, args):
-
- # push function state onto stack. dont log any more
- # identifiers as "declared" until outside of the function,
- # but keep logging identifiers as "undeclared". track
- # argument names in each function header so they arent
- # counted as "undeclared"
-
- inf = self.in_function
- self.in_function = True
-
- local_ident_stack = self.local_ident_stack
- self.local_ident_stack = local_ident_stack.union([
- arg for arg in self._expand_tuples(node.argnames)
- ])
-
- for n in node.getChildNodes():
- self.visit(n, *args)
- self.in_function = inf
- self.local_ident_stack = local_ident_stack
-
- def visitFor(self, node, *args):
-
- # flip around visit
-
- self.visit(node.list, *args)
- self.visit(node.assign, *args)
- self.visit(node.body, *args)
-
- def visitName(self, node, *args):
- if node.name not in reserved and node.name \
- not in self.listener.declared_identifiers and node.name \
- not in self.local_ident_stack:
- self.listener.undeclared_identifiers.add(node.name)
-
- def visitImport(self, node, *args):
- for mod, alias in node.names:
- if alias is not None:
- self._add_declared(alias)
- else:
- self._add_declared(mod.split('.')[0])
-
- def visitFrom(self, node, *args):
- for mod, alias in node.names:
- if alias is not None:
- self._add_declared(alias)
- else:
- if mod == '*':
- raise exceptions.CompileException(
- "'import *' is not supported, since all identifier "
- "names must be explicitly declared. Please use the "
- "form 'from import , , "
- "...' instead.", **self.exception_kwargs)
- self._add_declared(mod)
-
- def visit(self, expr):
- visitor.walk(expr, self) # , walker=walker())
-
-
- class FindTuple(object):
-
- def __init__(self, listener, code_factory, **exception_kwargs):
- self.listener = listener
- self.exception_kwargs = exception_kwargs
- self.code_factory = code_factory
-
- def visitTuple(self, node, *args):
- for n in node.nodes:
- p = self.code_factory(n, **self.exception_kwargs)
- self.listener.codeargs.append(p)
- self.listener.args.append(ExpressionGenerator(n).value())
- self.listener.declared_identifiers = \
- self.listener.declared_identifiers.union(
- p.declared_identifiers)
- self.listener.undeclared_identifiers = \
- self.listener.undeclared_identifiers.union(
- p.undeclared_identifiers)
-
- def visit(self, expr):
- visitor.walk(expr, self) # , walker=walker())
-
-
- class ParseFunc(object):
-
- def __init__(self, listener, **exception_kwargs):
- self.listener = listener
- self.exception_kwargs = exception_kwargs
-
- def visitFunction(self, node, *args):
- self.listener.funcname = node.name
- self.listener.argnames = node.argnames
- self.listener.defaults = node.defaults
- self.listener.varargs = node.varargs
- self.listener.kwargs = node.kwargs
-
- def visit(self, expr):
- visitor.walk(expr, self)
-
-
- class ExpressionGenerator(object):
-
- """given an AST node, generates an equivalent literal Python
- expression."""
-
- def __init__(self, astnode):
- self.buf = StringIO()
- visitor.walk(astnode, self) # , walker=walker())
-
- def value(self):
- return self.buf.getvalue()
-
- def operator(self, op, node, *args):
- self.buf.write('(')
- self.visit(node.left, *args)
- self.buf.write(' %s ' % op)
- self.visit(node.right, *args)
- self.buf.write(')')
-
- def booleanop(self, op, node, *args):
- self.visit(node.nodes[0])
- for n in node.nodes[1:]:
- self.buf.write(' ' + op + ' ')
- self.visit(n, *args)
-
- def visitConst(self, node, *args):
- self.buf.write(repr(node.value))
-
- def visitAssName(self, node, *args):
-
- # TODO: figure out OP_ASSIGN, other OP_s
-
- self.buf.write(node.name)
-
- def visitName(self, node, *args):
- self.buf.write(node.name)
-
- def visitMul(self, node, *args):
- self.operator('*', node, *args)
-
- def visitAnd(self, node, *args):
- self.booleanop('and', node, *args)
-
- def visitOr(self, node, *args):
- self.booleanop('or', node, *args)
-
- def visitBitand(self, node, *args):
- self.booleanop('&', node, *args)
-
- def visitBitor(self, node, *args):
- self.booleanop('|', node, *args)
-
- def visitBitxor(self, node, *args):
- self.booleanop('^', node, *args)
-
- def visitAdd(self, node, *args):
- self.operator('+', node, *args)
-
- def visitGetattr(self, node, *args):
- self.visit(node.expr, *args)
- self.buf.write('.%s' % node.attrname)
-
- def visitSub(self, node, *args):
- self.operator('-', node, *args)
-
- def visitNot(self, node, *args):
- self.buf.write('not ')
- self.visit(node.expr)
-
- def visitDiv(self, node, *args):
- self.operator('/', node, *args)
-
- def visitFloorDiv(self, node, *args):
- self.operator('//', node, *args)
-
- def visitSubscript(self, node, *args):
- self.visit(node.expr)
- self.buf.write('[')
- [self.visit(x) for x in node.subs]
- self.buf.write(']')
-
- def visitUnarySub(self, node, *args):
- self.buf.write('-')
- self.visit(node.expr)
-
- def visitUnaryAdd(self, node, *args):
- self.buf.write('-')
- self.visit(node.expr)
-
- def visitSlice(self, node, *args):
- self.visit(node.expr)
- self.buf.write('[')
- if node.lower is not None:
- self.visit(node.lower)
- self.buf.write(':')
- if node.upper is not None:
- self.visit(node.upper)
- self.buf.write(']')
-
- def visitDict(self, node):
- self.buf.write('{')
- c = node.getChildren()
- for i in range(0, len(c), 2):
- self.visit(c[i])
- self.buf.write(': ')
- self.visit(c[i + 1])
- if i < len(c) - 2:
- self.buf.write(', ')
- self.buf.write('}')
-
- def visitTuple(self, node):
- self.buf.write('(')
- c = node.getChildren()
- for i in range(0, len(c)):
- self.visit(c[i])
- if i < len(c) - 1:
- self.buf.write(', ')
- self.buf.write(')')
-
- def visitList(self, node):
- self.buf.write('[')
- c = node.getChildren()
- for i in range(0, len(c)):
- self.visit(c[i])
- if i < len(c) - 1:
- self.buf.write(', ')
- self.buf.write(']')
-
- def visitListComp(self, node):
- self.buf.write('[')
- self.visit(node.expr)
- self.buf.write(' ')
- for n in node.quals:
- self.visit(n)
- self.buf.write(']')
-
- def visitListCompFor(self, node):
- self.buf.write(' for ')
- self.visit(node.assign)
- self.buf.write(' in ')
- self.visit(node.list)
- for n in node.ifs:
- self.visit(n)
-
- def visitListCompIf(self, node):
- self.buf.write(' if ')
- self.visit(node.test)
-
- def visitCompare(self, node):
- self.visit(node.expr)
- for tup in node.ops:
- self.buf.write(tup[0])
- self.visit(tup[1])
-
- def visitCallFunc(self, node, *args):
- self.visit(node.node)
- self.buf.write('(')
- if len(node.args):
- self.visit(node.args[0])
- for a in node.args[1:]:
- self.buf.write(', ')
- self.visit(a)
- self.buf.write(')')
-
- def visitLambda(self, node, *args):
- self.buf.write('lambda ')
-
- argnames = list(node.argnames)
-
- kw = arg = None
- if node.kwargs > 0:
- kw = argnames.pop(-1)
- if node.varargs > 0:
- arg = argnames.pop(-1)
-
- if arg:
- argnames.append("*%s" % arg)
- if kw:
- argnames.append("**%s" % kw)
-
- self.buf.write(", ".join(argnames))
-
- self.buf.write(': ')
- self.visit(node.code)
-
-
- class walker(visitor.ASTVisitor):
-
- def dispatch(self, node, *args):
- print('Node:', str(node))
-
- # print "dir:", dir(node)
-
- return visitor.ASTVisitor.dispatch(self, node, *args)
diff --git a/Darwin/lib/python2.7/site-packages/mako/runtime.py b/Darwin/lib/python2.7/site-packages/mako/runtime.py
deleted file mode 100644
index f94c109..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/runtime.py
+++ /dev/null
@@ -1,882 +0,0 @@
-# mako/runtime.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""provides runtime services for templates, including Context,
-Namespace, and various helper functions."""
-
-from mako import exceptions, util, compat
-from mako.compat import compat_builtins
-import inspect
-import sys
-import collections
-
-
-class Context(object):
- """Provides runtime namespace, output buffer, and various
- callstacks for templates.
-
- See :ref:`runtime_toplevel` for detail on the usage of
- :class:`.Context`.
-
- """
-
- def __init__(self, buffer, **data):
- self._buffer_stack = [buffer]
-
- self._data = data
-
- self._kwargs = data.copy()
- self._with_template = None
- self._outputting_as_unicode = None
- self.namespaces = {}
-
- # "capture" function which proxies to the
- # generic "capture" function
- self._data['capture'] = compat.partial(capture, self)
-
- # "caller" stack used by def calls with content
- self.caller_stack = self._data['caller'] = CallerStack()
-
- def _set_with_template(self, t):
- self._with_template = t
- illegal_names = t.reserved_names.intersection(self._data)
- if illegal_names:
- raise exceptions.NameConflictError(
- "Reserved words passed to render(): %s" %
- ", ".join(illegal_names))
-
- @property
- def lookup(self):
- """Return the :class:`.TemplateLookup` associated
- with this :class:`.Context`.
-
- """
- return self._with_template.lookup
-
- @property
- def kwargs(self):
- """Return the dictionary of top level keyword arguments associated
- with this :class:`.Context`.
-
- This dictionary only includes the top-level arguments passed to
- :meth:`.Template.render`. It does not include names produced within
- the template execution such as local variable names or special names
- such as ``self``, ``next``, etc.
-
- The purpose of this dictionary is primarily for the case that
- a :class:`.Template` accepts arguments via its ``<%page>`` tag,
- which are normally expected to be passed via :meth:`.Template.render`,
- except the template is being called in an inheritance context,
- using the ``body()`` method. :attr:`.Context.kwargs` can then be
- used to propagate these arguments to the inheriting template::
-
- ${next.body(**context.kwargs)}
-
- """
- return self._kwargs.copy()
-
- def push_caller(self, caller):
- """Push a ``caller`` callable onto the callstack for
- this :class:`.Context`."""
-
-
- self.caller_stack.append(caller)
-
- def pop_caller(self):
- """Pop a ``caller`` callable onto the callstack for this
- :class:`.Context`."""
-
- del self.caller_stack[-1]
-
- def keys(self):
- """Return a list of all names established in this :class:`.Context`."""
-
- return list(self._data.keys())
-
- def __getitem__(self, key):
- if key in self._data:
- return self._data[key]
- else:
- return compat_builtins.__dict__[key]
-
- def _push_writer(self):
- """push a capturing buffer onto this Context and return
- the new writer function."""
-
- buf = util.FastEncodingBuffer()
- self._buffer_stack.append(buf)
- return buf.write
-
- def _pop_buffer_and_writer(self):
- """pop the most recent capturing buffer from this Context
- and return the current writer after the pop.
-
- """
-
- buf = self._buffer_stack.pop()
- return buf, self._buffer_stack[-1].write
-
- def _push_buffer(self):
- """push a capturing buffer onto this Context."""
-
- self._push_writer()
-
- def _pop_buffer(self):
- """pop the most recent capturing buffer from this Context."""
-
- return self._buffer_stack.pop()
-
- def get(self, key, default=None):
- """Return a value from this :class:`.Context`."""
-
- return self._data.get(key,
- compat_builtins.__dict__.get(key, default)
- )
-
- def write(self, string):
- """Write a string to this :class:`.Context` object's
- underlying output buffer."""
-
- self._buffer_stack[-1].write(string)
-
- def writer(self):
- """Return the current writer function."""
-
- return self._buffer_stack[-1].write
-
- def _copy(self):
- c = Context.__new__(Context)
- c._buffer_stack = self._buffer_stack
- c._data = self._data.copy()
- c._kwargs = self._kwargs
- c._with_template = self._with_template
- c._outputting_as_unicode = self._outputting_as_unicode
- c.namespaces = self.namespaces
- c.caller_stack = self.caller_stack
- return c
-
- def _locals(self, d):
- """Create a new :class:`.Context` with a copy of this
- :class:`.Context`'s current state,
- updated with the given dictionary.
-
- The :attr:`.Context.kwargs` collection remains
- unaffected.
-
-
- """
-
- if not d:
- return self
- c = self._copy()
- c._data.update(d)
- return c
-
- def _clean_inheritance_tokens(self):
- """create a new copy of this :class:`.Context`. with
- tokens related to inheritance state removed."""
-
- c = self._copy()
- x = c._data
- x.pop('self', None)
- x.pop('parent', None)
- x.pop('next', None)
- return c
-
-class CallerStack(list):
- def __init__(self):
- self.nextcaller = None
-
- def __nonzero__(self):
- return self.__bool__()
-
- def __bool__(self):
- return len(self) and self._get_caller() and True or False
-
- def _get_caller(self):
- # this method can be removed once
- # codegen MAGIC_NUMBER moves past 7
- return self[-1]
-
- def __getattr__(self, key):
- return getattr(self._get_caller(), key)
-
- def _push_frame(self):
- frame = self.nextcaller or None
- self.append(frame)
- self.nextcaller = None
- return frame
-
- def _pop_frame(self):
- self.nextcaller = self.pop()
-
-
-class Undefined(object):
- """Represents an undefined value in a template.
-
- All template modules have a constant value
- ``UNDEFINED`` present which is an instance of this
- object.
-
- """
- def __str__(self):
- raise NameError("Undefined")
-
- def __nonzero__(self):
- return self.__bool__()
-
- def __bool__(self):
- return False
-
-UNDEFINED = Undefined()
-
-class LoopStack(object):
- """a stack for LoopContexts that implements the context manager protocol
- to automatically pop off the top of the stack on context exit
- """
-
- def __init__(self):
- self.stack = []
-
- def _enter(self, iterable):
- self._push(iterable)
- return self._top
-
- def _exit(self):
- self._pop()
- return self._top
-
- @property
- def _top(self):
- if self.stack:
- return self.stack[-1]
- else:
- return self
-
- def _pop(self):
- return self.stack.pop()
-
- def _push(self, iterable):
- new = LoopContext(iterable)
- if self.stack:
- new.parent = self.stack[-1]
- return self.stack.append(new)
-
- def __getattr__(self, key):
- raise exceptions.RuntimeException("No loop context is established")
-
- def __iter__(self):
- return iter(self._top)
-
-
-class LoopContext(object):
- """A magic loop variable.
- Automatically accessible in any ``% for`` block.
-
- See the section :ref:`loop_context` for usage
- notes.
-
- :attr:`parent` -> :class:`.LoopContext` or ``None``
- The parent loop, if one exists.
- :attr:`index` -> `int`
- The 0-based iteration count.
- :attr:`reverse_index` -> `int`
- The number of iterations remaining.
- :attr:`first` -> `bool`
- ``True`` on the first iteration, ``False`` otherwise.
- :attr:`last` -> `bool`
- ``True`` on the last iteration, ``False`` otherwise.
- :attr:`even` -> `bool`
- ``True`` when ``index`` is even.
- :attr:`odd` -> `bool`
- ``True`` when ``index`` is odd.
- """
-
- def __init__(self, iterable):
- self._iterable = iterable
- self.index = 0
- self.parent = None
-
- def __iter__(self):
- for i in self._iterable:
- yield i
- self.index += 1
-
- @util.memoized_instancemethod
- def __len__(self):
- return len(self._iterable)
-
- @property
- def reverse_index(self):
- return len(self) - self.index - 1
-
- @property
- def first(self):
- return self.index == 0
-
- @property
- def last(self):
- return self.index == len(self) - 1
-
- @property
- def even(self):
- return not self.odd
-
- @property
- def odd(self):
- return bool(self.index % 2)
-
- def cycle(self, *values):
- """Cycle through values as the loop progresses.
- """
- if not values:
- raise ValueError("You must provide values to cycle through")
- return values[self.index % len(values)]
-
-
-class _NSAttr(object):
- def __init__(self, parent):
- self.__parent = parent
- def __getattr__(self, key):
- ns = self.__parent
- while ns:
- if hasattr(ns.module, key):
- return getattr(ns.module, key)
- else:
- ns = ns.inherits
- raise AttributeError(key)
-
-class Namespace(object):
- """Provides access to collections of rendering methods, which
- can be local, from other templates, or from imported modules.
-
- To access a particular rendering method referenced by a
- :class:`.Namespace`, use plain attribute access:
-
- .. sourcecode:: mako
-
- ${some_namespace.foo(x, y, z)}
-
- :class:`.Namespace` also contains several built-in attributes
- described here.
-
- """
-
- def __init__(self, name, context,
- callables=None, inherits=None,
- populate_self=True, calling_uri=None):
- self.name = name
- self.context = context
- self.inherits = inherits
- if callables is not None:
- self.callables = dict([(c.__name__, c) for c in callables])
-
- callables = ()
-
- module = None
- """The Python module referenced by this :class:`.Namespace`.
-
- If the namespace references a :class:`.Template`, then
- this module is the equivalent of ``template.module``,
- i.e. the generated module for the template.
-
- """
-
- template = None
- """The :class:`.Template` object referenced by this
- :class:`.Namespace`, if any.
-
- """
-
- context = None
- """The :class:`.Context` object for this :class:`.Namespace`.
-
- Namespaces are often created with copies of contexts that
- contain slightly different data, particularly in inheritance
- scenarios. Using the :class:`.Context` off of a :class:`.Namespace` one
- can traverse an entire chain of templates that inherit from
- one-another.
-
- """
-
- filename = None
- """The path of the filesystem file used for this
- :class:`.Namespace`'s module or template.
-
- If this is a pure module-based
- :class:`.Namespace`, this evaluates to ``module.__file__``. If a
- template-based namespace, it evaluates to the original
- template file location.
-
- """
-
- uri = None
- """The URI for this :class:`.Namespace`'s template.
-
- I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`.
-
- This is the equivalent of :attr:`.Template.uri`.
-
- """
-
- _templateuri = None
-
- @util.memoized_property
- def attr(self):
- """Access module level attributes by name.
-
- This accessor allows templates to supply "scalar"
- attributes which are particularly handy in inheritance
- relationships.
-
- .. seealso::
-
- :ref:`inheritance_attr`
-
- :ref:`namespace_attr_for_includes`
-
- """
- return _NSAttr(self)
-
- def get_namespace(self, uri):
- """Return a :class:`.Namespace` corresponding to the given ``uri``.
-
- If the given ``uri`` is a relative URI (i.e. it does not
- contain a leading slash ``/``), the ``uri`` is adjusted to
- be relative to the ``uri`` of the namespace itself. This
- method is therefore mostly useful off of the built-in
- ``local`` namespace, described in :ref:`namespace_local`.
-
- In
- most cases, a template wouldn't need this function, and
- should instead use the ``<%namespace>`` tag to load
- namespaces. However, since all ``<%namespace>`` tags are
- evaluated before the body of a template ever runs,
- this method can be used to locate namespaces using
- expressions that were generated within the body code of
- the template, or to conditionally use a particular
- namespace.
-
- """
- key = (self, uri)
- if key in self.context.namespaces:
- return self.context.namespaces[key]
- else:
- ns = TemplateNamespace(uri, self.context._copy(),
- templateuri=uri,
- calling_uri=self._templateuri)
- self.context.namespaces[key] = ns
- return ns
-
- def get_template(self, uri):
- """Return a :class:`.Template` from the given ``uri``.
-
- The ``uri`` resolution is relative to the ``uri`` of this :class:`.Namespace`
- object's :class:`.Template`.
-
- """
- return _lookup_template(self.context, uri, self._templateuri)
-
- def get_cached(self, key, **kwargs):
- """Return a value from the :class:`.Cache` referenced by this
- :class:`.Namespace` object's :class:`.Template`.
-
- The advantage to this method versus direct access to the
- :class:`.Cache` is that the configuration parameters
- declared in ``<%page>`` take effect here, thereby calling
- up the same configured backend as that configured
- by ``<%page>``.
-
- """
-
- return self.cache.get(key, **kwargs)
-
- @property
- def cache(self):
- """Return the :class:`.Cache` object referenced
- by this :class:`.Namespace` object's
- :class:`.Template`.
-
- """
- return self.template.cache
-
- def include_file(self, uri, **kwargs):
- """Include a file at the given ``uri``."""
-
- _include_file(self.context, uri, self._templateuri, **kwargs)
-
- def _populate(self, d, l):
- for ident in l:
- if ident == '*':
- for (k, v) in self._get_star():
- d[k] = v
- else:
- d[ident] = getattr(self, ident)
-
- def _get_star(self):
- if self.callables:
- for key in self.callables:
- yield (key, self.callables[key])
-
- def __getattr__(self, key):
- if key in self.callables:
- val = self.callables[key]
- elif self.inherits:
- val = getattr(self.inherits, key)
- else:
- raise AttributeError(
- "Namespace '%s' has no member '%s'" %
- (self.name, key))
- setattr(self, key, val)
- return val
-
-class TemplateNamespace(Namespace):
- """A :class:`.Namespace` specific to a :class:`.Template` instance."""
-
- def __init__(self, name, context, template=None, templateuri=None,
- callables=None, inherits=None,
- populate_self=True, calling_uri=None):
- self.name = name
- self.context = context
- self.inherits = inherits
- if callables is not None:
- self.callables = dict([(c.__name__, c) for c in callables])
-
- if templateuri is not None:
- self.template = _lookup_template(context, templateuri,
- calling_uri)
- self._templateuri = self.template.module._template_uri
- elif template is not None:
- self.template = template
- self._templateuri = template.module._template_uri
- else:
- raise TypeError("'template' argument is required.")
-
- if populate_self:
- lclcallable, lclcontext = \
- _populate_self_namespace(context, self.template,
- self_ns=self)
-
- @property
- def module(self):
- """The Python module referenced by this :class:`.Namespace`.
-
- If the namespace references a :class:`.Template`, then
- this module is the equivalent of ``template.module``,
- i.e. the generated module for the template.
-
- """
- return self.template.module
-
- @property
- def filename(self):
- """The path of the filesystem file used for this
- :class:`.Namespace`'s module or template.
- """
- return self.template.filename
-
- @property
- def uri(self):
- """The URI for this :class:`.Namespace`'s template.
-
- I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`.
-
- This is the equivalent of :attr:`.Template.uri`.
-
- """
- return self.template.uri
-
- def _get_star(self):
- if self.callables:
- for key in self.callables:
- yield (key, self.callables[key])
- def get(key):
- callable_ = self.template._get_def_callable(key)
- return compat.partial(callable_, self.context)
- for k in self.template.module._exports:
- yield (k, get(k))
-
- def __getattr__(self, key):
- if key in self.callables:
- val = self.callables[key]
- elif self.template.has_def(key):
- callable_ = self.template._get_def_callable(key)
- val = compat.partial(callable_, self.context)
- elif self.inherits:
- val = getattr(self.inherits, key)
-
- else:
- raise AttributeError(
- "Namespace '%s' has no member '%s'" %
- (self.name, key))
- setattr(self, key, val)
- return val
-
-class ModuleNamespace(Namespace):
- """A :class:`.Namespace` specific to a Python module instance."""
-
- def __init__(self, name, context, module,
- callables=None, inherits=None,
- populate_self=True, calling_uri=None):
- self.name = name
- self.context = context
- self.inherits = inherits
- if callables is not None:
- self.callables = dict([(c.__name__, c) for c in callables])
-
- mod = __import__(module)
- for token in module.split('.')[1:]:
- mod = getattr(mod, token)
- self.module = mod
-
- @property
- def filename(self):
- """The path of the filesystem file used for this
- :class:`.Namespace`'s module or template.
- """
- return self.module.__file__
-
- def _get_star(self):
- if self.callables:
- for key in self.callables:
- yield (key, self.callables[key])
- for key in dir(self.module):
- if key[0] != '_':
- callable_ = getattr(self.module, key)
- if compat.callable(callable_):
- yield key, compat.partial(callable_, self.context)
-
-
- def __getattr__(self, key):
- if key in self.callables:
- val = self.callables[key]
- elif hasattr(self.module, key):
- callable_ = getattr(self.module, key)
- val = compat.partial(callable_, self.context)
- elif self.inherits:
- val = getattr(self.inherits, key)
- else:
- raise AttributeError(
- "Namespace '%s' has no member '%s'" %
- (self.name, key))
- setattr(self, key, val)
- return val
-
-def supports_caller(func):
- """Apply a caller_stack compatibility decorator to a plain
- Python function.
-
- See the example in :ref:`namespaces_python_modules`.
-
- """
-
- def wrap_stackframe(context, *args, **kwargs):
- context.caller_stack._push_frame()
- try:
- return func(context, *args, **kwargs)
- finally:
- context.caller_stack._pop_frame()
- return wrap_stackframe
-
-def capture(context, callable_, *args, **kwargs):
- """Execute the given template def, capturing the output into
- a buffer.
-
- See the example in :ref:`namespaces_python_modules`.
-
- """
-
- if not compat.callable(callable_):
- raise exceptions.RuntimeException(
- "capture() function expects a callable as "
- "its argument (i.e. capture(func, *args, **kwargs))"
- )
- context._push_buffer()
- try:
- callable_(*args, **kwargs)
- finally:
- buf = context._pop_buffer()
- return buf.getvalue()
-
-def _decorate_toplevel(fn):
- def decorate_render(render_fn):
- def go(context, *args, **kw):
- def y(*args, **kw):
- return render_fn(context, *args, **kw)
- try:
- y.__name__ = render_fn.__name__[7:]
- except TypeError:
- # < Python 2.4
- pass
- return fn(y)(context, *args, **kw)
- return go
- return decorate_render
-
-def _decorate_inline(context, fn):
- def decorate_render(render_fn):
- dec = fn(render_fn)
- def go(*args, **kw):
- return dec(context, *args, **kw)
- return go
- return decorate_render
-
-def _include_file(context, uri, calling_uri, **kwargs):
- """locate the template from the given uri and include it in
- the current output."""
-
- template = _lookup_template(context, uri, calling_uri)
- (callable_, ctx) = _populate_self_namespace(
- context._clean_inheritance_tokens(),
- template)
- callable_(ctx, **_kwargs_for_include(callable_, context._data, **kwargs))
-
-def _inherit_from(context, uri, calling_uri):
- """called by the _inherit method in template modules to set
- up the inheritance chain at the start of a template's
- execution."""
-
- if uri is None:
- return None
- template = _lookup_template(context, uri, calling_uri)
- self_ns = context['self']
- ih = self_ns
- while ih.inherits is not None:
- ih = ih.inherits
- lclcontext = context._locals({'next': ih})
- ih.inherits = TemplateNamespace("self:%s" % template.uri,
- lclcontext,
- template=template,
- populate_self=False)
- context._data['parent'] = lclcontext._data['local'] = ih.inherits
- callable_ = getattr(template.module, '_mako_inherit', None)
- if callable_ is not None:
- ret = callable_(template, lclcontext)
- if ret:
- return ret
-
- gen_ns = getattr(template.module, '_mako_generate_namespaces', None)
- if gen_ns is not None:
- gen_ns(context)
- return (template.callable_, lclcontext)
-
-def _lookup_template(context, uri, relativeto):
- lookup = context._with_template.lookup
- if lookup is None:
- raise exceptions.TemplateLookupException(
- "Template '%s' has no TemplateLookup associated" %
- context._with_template.uri)
- uri = lookup.adjust_uri(uri, relativeto)
- try:
- return lookup.get_template(uri)
- except exceptions.TopLevelLookupException:
- raise exceptions.TemplateLookupException(str(compat.exception_as()))
-
-def _populate_self_namespace(context, template, self_ns=None):
- if self_ns is None:
- self_ns = TemplateNamespace('self:%s' % template.uri,
- context, template=template,
- populate_self=False)
- context._data['self'] = context._data['local'] = self_ns
- if hasattr(template.module, '_mako_inherit'):
- ret = template.module._mako_inherit(template, context)
- if ret:
- return ret
- return (template.callable_, context)
-
-def _render(template, callable_, args, data, as_unicode=False):
- """create a Context and return the string
- output of the given template and template callable."""
-
- if as_unicode:
- buf = util.FastEncodingBuffer(as_unicode=True)
- elif template.bytestring_passthrough:
- buf = compat.StringIO()
- else:
- buf = util.FastEncodingBuffer(
- as_unicode=as_unicode,
- encoding=template.output_encoding,
- errors=template.encoding_errors)
- context = Context(buf, **data)
- context._outputting_as_unicode = as_unicode
- context._set_with_template(template)
-
- _render_context(template, callable_, context, *args,
- **_kwargs_for_callable(callable_, data))
- return context._pop_buffer().getvalue()
-
-def _kwargs_for_callable(callable_, data):
- argspec = compat.inspect_func_args(callable_)
- # for normal pages, **pageargs is usually present
- if argspec[2]:
- return data
-
- # for rendering defs from the top level, figure out the args
- namedargs = argspec[0] + [v for v in argspec[1:3] if v is not None]
- kwargs = {}
- for arg in namedargs:
- if arg != 'context' and arg in data and arg not in kwargs:
- kwargs[arg] = data[arg]
- return kwargs
-
-def _kwargs_for_include(callable_, data, **kwargs):
- argspec = compat.inspect_func_args(callable_)
- namedargs = argspec[0] + [v for v in argspec[1:3] if v is not None]
- for arg in namedargs:
- if arg != 'context' and arg in data and arg not in kwargs:
- kwargs[arg] = data[arg]
- return kwargs
-
-def _render_context(tmpl, callable_, context, *args, **kwargs):
- import mako.template as template
- # create polymorphic 'self' namespace for this
- # template with possibly updated context
- if not isinstance(tmpl, template.DefTemplate):
- # if main render method, call from the base of the inheritance stack
- (inherit, lclcontext) = _populate_self_namespace(context, tmpl)
- _exec_template(inherit, lclcontext, args=args, kwargs=kwargs)
- else:
- # otherwise, call the actual rendering method specified
- (inherit, lclcontext) = _populate_self_namespace(context, tmpl.parent)
- _exec_template(callable_, context, args=args, kwargs=kwargs)
-
-def _exec_template(callable_, context, args=None, kwargs=None):
- """execute a rendering callable given the callable, a
- Context, and optional explicit arguments
-
- the contextual Template will be located if it exists, and
- the error handling options specified on that Template will
- be interpreted here.
- """
- template = context._with_template
- if template is not None and \
- (template.format_exceptions or template.error_handler):
- error = None
- try:
- callable_(context, *args, **kwargs)
- except Exception:
- _render_error(template, context, compat.exception_as())
- except:
- e = sys.exc_info()[0]
- _render_error(template, context, e)
- else:
- callable_(context, *args, **kwargs)
-
-def _render_error(template, context, error):
- if template.error_handler:
- result = template.error_handler(context, error)
- if not result:
- raise error
- else:
- error_template = exceptions.html_error_template()
- if context._outputting_as_unicode:
- context._buffer_stack[:] = [util.FastEncodingBuffer(as_unicode=True)]
- else:
- context._buffer_stack[:] = [util.FastEncodingBuffer(
- error_template.output_encoding,
- error_template.encoding_errors)]
-
- context._set_with_template(error_template)
- error_template.render_context(context, error=error)
diff --git a/Darwin/lib/python2.7/site-packages/mako/template.py b/Darwin/lib/python2.7/site-packages/mako/template.py
deleted file mode 100644
index 3a7b7f0..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/template.py
+++ /dev/null
@@ -1,686 +0,0 @@
-# mako/template.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-"""Provides the Template class, a facade for parsing, generating and executing
-template strings, as well as template runtime operations."""
-
-from mako.lexer import Lexer
-from mako import runtime, util, exceptions, codegen, cache, compat
-import os
-import re
-import shutil
-import stat
-import sys
-import tempfile
-import types
-import weakref
-
-
-class Template(object):
- """Represents a compiled template.
-
- :class:`.Template` includes a reference to the original
- template source (via the :attr:`.source` attribute)
- as well as the source code of the
- generated Python module (i.e. the :attr:`.code` attribute),
- as well as a reference to an actual Python module.
-
- :class:`.Template` is constructed using either a literal string
- representing the template text, or a filename representing a filesystem
- path to a source file.
-
- :param text: textual template source. This argument is mutually
- exclusive versus the ``filename`` parameter.
-
- :param filename: filename of the source template. This argument is
- mutually exclusive versus the ``text`` parameter.
-
- :param buffer_filters: string list of filters to be applied
- to the output of ``%def``\ s which are buffered, cached, or otherwise
- filtered, after all filters
- defined with the ``%def`` itself have been applied. Allows the
- creation of default expression filters that let the output
- of return-valued ``%def``\ s "opt out" of that filtering via
- passing special attributes or objects.
-
- :param bytestring_passthrough: When ``True``, and ``output_encoding`` is
- set to ``None``, and :meth:`.Template.render` is used to render,
- the `StringIO` or `cStringIO` buffer will be used instead of the
- default "fast" buffer. This allows raw bytestrings in the
- output stream, such as in expressions, to pass straight
- through to the buffer. This flag is forced
- to ``True`` if ``disable_unicode`` is also configured.
-
- .. versionadded:: 0.4
- Added to provide the same behavior as that of the previous series.
-
- :param cache_args: Dictionary of cache configuration arguments that
- will be passed to the :class:`.CacheImpl`. See :ref:`caching_toplevel`.
-
- :param cache_dir:
-
- .. deprecated:: 0.6
- Use the ``'dir'`` argument in the ``cache_args`` dictionary.
- See :ref:`caching_toplevel`.
-
- :param cache_enabled: Boolean flag which enables caching of this
- template. See :ref:`caching_toplevel`.
-
- :param cache_impl: String name of a :class:`.CacheImpl` caching
- implementation to use. Defaults to ``'beaker'``.
-
- :param cache_type:
-
- .. deprecated:: 0.6
- Use the ``'type'`` argument in the ``cache_args`` dictionary.
- See :ref:`caching_toplevel`.
-
- :param cache_url:
-
- .. deprecated:: 0.6
- Use the ``'url'`` argument in the ``cache_args`` dictionary.
- See :ref:`caching_toplevel`.
-
- :param default_filters: List of string filter names that will
- be applied to all expressions. See :ref:`filtering_default_filters`.
-
- :param disable_unicode: Disables all awareness of Python Unicode
- objects. See :ref:`unicode_disabled`.
-
- :param enable_loop: When ``True``, enable the ``loop`` context variable.
- This can be set to ``False`` to support templates that may
- be making usage of the name "``loop``". Individual templates can
- re-enable the "loop" context by placing the directive
- ``enable_loop="True"`` inside the ``<%page>`` tag -- see
- :ref:`migrating_loop`.
-
- :param encoding_errors: Error parameter passed to ``encode()`` when
- string encoding is performed. See :ref:`usage_unicode`.
-
- :param error_handler: Python callable which is called whenever
- compile or runtime exceptions occur. The callable is passed
- the current context as well as the exception. If the
- callable returns ``True``, the exception is considered to
- be handled, else it is re-raised after the function
- completes. Is used to provide custom error-rendering
- functions.
-
- :param format_exceptions: if ``True``, exceptions which occur during
- the render phase of this template will be caught and
- formatted into an HTML error page, which then becomes the
- rendered result of the :meth:`.render` call. Otherwise,
- runtime exceptions are propagated outwards.
-
- :param imports: String list of Python statements, typically individual
- "import" lines, which will be placed into the module level
- preamble of all generated Python modules. See the example
- in :ref:`filtering_default_filters`.
-
- :param future_imports: String list of names to import from `__future__`.
- These will be concatenated into a comma-separated string and inserted
- into the beginning of the template, e.g. ``futures_imports=['FOO',
- 'BAR']`` results in ``from __future__ import FOO, BAR``. If you're
- interested in using features like the new division operator, you must
- use future_imports to convey that to the renderer, as otherwise the
- import will not appear as the first executed statement in the generated
- code and will therefore not have the desired effect.
-
- :param input_encoding: Encoding of the template's source code. Can
- be used in lieu of the coding comment. See
- :ref:`usage_unicode` as well as :ref:`unicode_toplevel` for
- details on source encoding.
-
- :param lookup: a :class:`.TemplateLookup` instance that will be used
- for all file lookups via the ``<%namespace>``,
- ``<%include>``, and ``<%inherit>`` tags. See
- :ref:`usage_templatelookup`.
-
- :param module_directory: Filesystem location where generated
- Python module files will be placed.
-
- :param module_filename: Overrides the filename of the generated
- Python module file. For advanced usage only.
-
- :param module_writer: A callable which overrides how the Python
- module is written entirely. The callable is passed the
- encoded source content of the module and the destination
- path to be written to. The default behavior of module writing
- uses a tempfile in conjunction with a file move in order
- to make the operation atomic. So a user-defined module
- writing function that mimics the default behavior would be:
-
- .. sourcecode:: python
-
- import tempfile
- import os
- import shutil
-
- def module_writer(source, outputpath):
- (dest, name) = \\
- tempfile.mkstemp(
- dir=os.path.dirname(outputpath)
- )
-
- os.write(dest, source)
- os.close(dest)
- shutil.move(name, outputpath)
-
- from mako.template import Template
- mytemplate = Template(
- filename="index.html",
- module_directory="/path/to/modules",
- module_writer=module_writer
- )
-
- The function is provided for unusual configurations where
- certain platform-specific permissions or other special
- steps are needed.
-
- :param output_encoding: The encoding to use when :meth:`.render`
- is called.
- See :ref:`usage_unicode` as well as :ref:`unicode_toplevel`.
-
- :param preprocessor: Python callable which will be passed
- the full template source before it is parsed. The return
- result of the callable will be used as the template source
- code.
-
- :param lexer_cls: A :class:`.Lexer` class used to parse
- the template. The :class:`.Lexer` class is used by
- default.
-
- .. versionadded:: 0.7.4
-
- :param strict_undefined: Replaces the automatic usage of
- ``UNDEFINED`` for any undeclared variables not located in
- the :class:`.Context` with an immediate raise of
- ``NameError``. The advantage is immediate reporting of
- missing variables which include the name.
-
- .. versionadded:: 0.3.6
-
- :param uri: string URI or other identifier for this template.
- If not provided, the ``uri`` is generated from the filesystem
- path, or from the in-memory identity of a non-file-based
- template. The primary usage of the ``uri`` is to provide a key
- within :class:`.TemplateLookup`, as well as to generate the
- file path of the generated Python module file, if
- ``module_directory`` is specified.
-
- """
-
- lexer_cls = Lexer
-
- def __init__(self,
- text=None,
- filename=None,
- uri=None,
- format_exceptions=False,
- error_handler=None,
- lookup=None,
- output_encoding=None,
- encoding_errors='strict',
- module_directory=None,
- cache_args=None,
- cache_impl='beaker',
- cache_enabled=True,
- cache_type=None,
- cache_dir=None,
- cache_url=None,
- module_filename=None,
- input_encoding=None,
- disable_unicode=False,
- module_writer=None,
- bytestring_passthrough=False,
- default_filters=None,
- buffer_filters=(),
- strict_undefined=False,
- imports=None,
- future_imports=None,
- enable_loop=True,
- preprocessor=None,
- lexer_cls=None):
- if uri:
- self.module_id = re.sub(r'\W', "_", uri)
- self.uri = uri
- elif filename:
- self.module_id = re.sub(r'\W', "_", filename)
- drive, path = os.path.splitdrive(filename)
- path = os.path.normpath(path).replace(os.path.sep, "/")
- self.uri = path
- else:
- self.module_id = "memory:" + hex(id(self))
- self.uri = self.module_id
-
- u_norm = self.uri
- if u_norm.startswith("/"):
- u_norm = u_norm[1:]
- u_norm = os.path.normpath(u_norm)
- if u_norm.startswith(".."):
- raise exceptions.TemplateLookupException(
- "Template uri \"%s\" is invalid - "
- "it cannot be relative outside "
- "of the root path." % self.uri)
-
- self.input_encoding = input_encoding
- self.output_encoding = output_encoding
- self.encoding_errors = encoding_errors
- self.disable_unicode = disable_unicode
- self.bytestring_passthrough = bytestring_passthrough or disable_unicode
- self.enable_loop = enable_loop
- self.strict_undefined = strict_undefined
- self.module_writer = module_writer
-
- if compat.py3k and disable_unicode:
- raise exceptions.UnsupportedError(
- "Mako for Python 3 does not "
- "support disabling Unicode")
- elif output_encoding and disable_unicode:
- raise exceptions.UnsupportedError(
- "output_encoding must be set to "
- "None when disable_unicode is used.")
- if default_filters is None:
- if compat.py3k or self.disable_unicode:
- self.default_filters = ['str']
- else:
- self.default_filters = ['unicode']
- else:
- self.default_filters = default_filters
- self.buffer_filters = buffer_filters
-
- self.imports = imports
- self.future_imports = future_imports
- self.preprocessor = preprocessor
-
- if lexer_cls is not None:
- self.lexer_cls = lexer_cls
-
- # if plain text, compile code in memory only
- if text is not None:
- (code, module) = _compile_text(self, text, filename)
- self._code = code
- self._source = text
- ModuleInfo(module, None, self, filename, code, text)
- elif filename is not None:
- # if template filename and a module directory, load
- # a filesystem-based module file, generating if needed
- if module_filename is not None:
- path = module_filename
- elif module_directory is not None:
- path = os.path.abspath(
- os.path.join(
- os.path.normpath(module_directory),
- u_norm + ".py"
- )
- )
- else:
- path = None
- module = self._compile_from_file(path, filename)
- else:
- raise exceptions.RuntimeException(
- "Template requires text or filename")
-
- self.module = module
- self.filename = filename
- self.callable_ = self.module.render_body
- self.format_exceptions = format_exceptions
- self.error_handler = error_handler
- self.lookup = lookup
-
- self.module_directory = module_directory
-
- self._setup_cache_args(
- cache_impl, cache_enabled, cache_args,
- cache_type, cache_dir, cache_url
- )
-
-
- @util.memoized_property
- def reserved_names(self):
- if self.enable_loop:
- return codegen.RESERVED_NAMES
- else:
- return codegen.RESERVED_NAMES.difference(['loop'])
-
- def _setup_cache_args(self,
- cache_impl, cache_enabled, cache_args,
- cache_type, cache_dir, cache_url):
- self.cache_impl = cache_impl
- self.cache_enabled = cache_enabled
- if cache_args:
- self.cache_args = cache_args
- else:
- self.cache_args = {}
-
- # transfer deprecated cache_* args
- if cache_type:
- self.cache_args['type'] = cache_type
- if cache_dir:
- self.cache_args['dir'] = cache_dir
- if cache_url:
- self.cache_args['url'] = cache_url
-
- def _compile_from_file(self, path, filename):
- if path is not None:
- util.verify_directory(os.path.dirname(path))
- filemtime = os.stat(filename)[stat.ST_MTIME]
- if not os.path.exists(path) or \
- os.stat(path)[stat.ST_MTIME] < filemtime:
- data = util.read_file(filename)
- _compile_module_file(
- self,
- data,
- filename,
- path,
- self.module_writer)
- module = compat.load_module(self.module_id, path)
- del sys.modules[self.module_id]
- if module._magic_number != codegen.MAGIC_NUMBER:
- data = util.read_file(filename)
- _compile_module_file(
- self,
- data,
- filename,
- path,
- self.module_writer)
- module = compat.load_module(self.module_id, path)
- del sys.modules[self.module_id]
- ModuleInfo(module, path, self, filename, None, None)
- else:
- # template filename and no module directory, compile code
- # in memory
- data = util.read_file(filename)
- code, module = _compile_text(
- self,
- data,
- filename)
- self._source = None
- self._code = code
- ModuleInfo(module, None, self, filename, code, None)
- return module
-
- @property
- def source(self):
- """Return the template source code for this :class:`.Template`."""
-
- return _get_module_info_from_callable(self.callable_).source
-
- @property
- def code(self):
- """Return the module source code for this :class:`.Template`."""
-
- return _get_module_info_from_callable(self.callable_).code
-
- @util.memoized_property
- def cache(self):
- return cache.Cache(self)
-
- @property
- def cache_dir(self):
- return self.cache_args['dir']
- @property
- def cache_url(self):
- return self.cache_args['url']
- @property
- def cache_type(self):
- return self.cache_args['type']
-
- def render(self, *args, **data):
- """Render the output of this template as a string.
-
- If the template specifies an output encoding, the string
- will be encoded accordingly, else the output is raw (raw
- output uses `cStringIO` and can't handle multibyte
- characters). A :class:`.Context` object is created corresponding
- to the given data. Arguments that are explicitly declared
- by this template's internal rendering method are also
- pulled from the given ``*args``, ``**data`` members.
-
- """
- return runtime._render(self, self.callable_, args, data)
-
- def render_unicode(self, *args, **data):
- """Render the output of this template as a unicode object."""
-
- return runtime._render(self,
- self.callable_,
- args,
- data,
- as_unicode=True)
-
- def render_context(self, context, *args, **kwargs):
- """Render this :class:`.Template` with the given context.
-
- The data is written to the context's buffer.
-
- """
- if getattr(context, '_with_template', None) is None:
- context._set_with_template(self)
- runtime._render_context(self,
- self.callable_,
- context,
- *args,
- **kwargs)
-
- def has_def(self, name):
- return hasattr(self.module, "render_%s" % name)
-
- def get_def(self, name):
- """Return a def of this template as a :class:`.DefTemplate`."""
-
- return DefTemplate(self, getattr(self.module, "render_%s" % name))
-
- def _get_def_callable(self, name):
- return getattr(self.module, "render_%s" % name)
-
- @property
- def last_modified(self):
- return self.module._modified_time
-
-class ModuleTemplate(Template):
- """A Template which is constructed given an existing Python module.
-
- e.g.::
-
- t = Template("this is a template")
- f = file("mymodule.py", "w")
- f.write(t.code)
- f.close()
-
- import mymodule
-
- t = ModuleTemplate(mymodule)
- print t.render()
-
- """
-
- def __init__(self, module,
- module_filename=None,
- template=None,
- template_filename=None,
- module_source=None,
- template_source=None,
- output_encoding=None,
- encoding_errors='strict',
- disable_unicode=False,
- bytestring_passthrough=False,
- format_exceptions=False,
- error_handler=None,
- lookup=None,
- cache_args=None,
- cache_impl='beaker',
- cache_enabled=True,
- cache_type=None,
- cache_dir=None,
- cache_url=None,
- ):
- self.module_id = re.sub(r'\W', "_", module._template_uri)
- self.uri = module._template_uri
- self.input_encoding = module._source_encoding
- self.output_encoding = output_encoding
- self.encoding_errors = encoding_errors
- self.disable_unicode = disable_unicode
- self.bytestring_passthrough = bytestring_passthrough or disable_unicode
- self.enable_loop = module._enable_loop
-
- if compat.py3k and disable_unicode:
- raise exceptions.UnsupportedError(
- "Mako for Python 3 does not "
- "support disabling Unicode")
- elif output_encoding and disable_unicode:
- raise exceptions.UnsupportedError(
- "output_encoding must be set to "
- "None when disable_unicode is used.")
-
- self.module = module
- self.filename = template_filename
- ModuleInfo(module,
- module_filename,
- self,
- template_filename,
- module_source,
- template_source)
-
- self.callable_ = self.module.render_body
- self.format_exceptions = format_exceptions
- self.error_handler = error_handler
- self.lookup = lookup
- self._setup_cache_args(
- cache_impl, cache_enabled, cache_args,
- cache_type, cache_dir, cache_url
- )
-
-class DefTemplate(Template):
- """A :class:`.Template` which represents a callable def in a parent
- template."""
-
- def __init__(self, parent, callable_):
- self.parent = parent
- self.callable_ = callable_
- self.output_encoding = parent.output_encoding
- self.module = parent.module
- self.encoding_errors = parent.encoding_errors
- self.format_exceptions = parent.format_exceptions
- self.error_handler = parent.error_handler
- self.enable_loop = parent.enable_loop
- self.lookup = parent.lookup
- self.bytestring_passthrough = parent.bytestring_passthrough
-
- def get_def(self, name):
- return self.parent.get_def(name)
-
-class ModuleInfo(object):
- """Stores information about a module currently loaded into
- memory, provides reverse lookups of template source, module
- source code based on a module's identifier.
-
- """
- _modules = weakref.WeakValueDictionary()
-
- def __init__(self,
- module,
- module_filename,
- template,
- template_filename,
- module_source,
- template_source):
- self.module = module
- self.module_filename = module_filename
- self.template_filename = template_filename
- self.module_source = module_source
- self.template_source = template_source
- self._modules[module.__name__] = template._mmarker = self
- if module_filename:
- self._modules[module_filename] = self
-
- @property
- def code(self):
- if self.module_source is not None:
- return self.module_source
- else:
- return util.read_python_file(self.module_filename)
-
- @property
- def source(self):
- if self.template_source is not None:
- if self.module._source_encoding and \
- not isinstance(self.template_source, compat.text_type):
- return self.template_source.decode(
- self.module._source_encoding)
- else:
- return self.template_source
- else:
- data = util.read_file(self.template_filename)
- if self.module._source_encoding:
- return data.decode(self.module._source_encoding)
- else:
- return data
-
-def _compile(template, text, filename, generate_magic_comment):
- lexer = template.lexer_cls(text,
- filename,
- disable_unicode=template.disable_unicode,
- input_encoding=template.input_encoding,
- preprocessor=template.preprocessor)
- node = lexer.parse()
- source = codegen.compile(node,
- template.uri,
- filename,
- default_filters=template.default_filters,
- buffer_filters=template.buffer_filters,
- imports=template.imports,
- future_imports=template.future_imports,
- source_encoding=lexer.encoding,
- generate_magic_comment=generate_magic_comment,
- disable_unicode=template.disable_unicode,
- strict_undefined=template.strict_undefined,
- enable_loop=template.enable_loop,
- reserved_names=template.reserved_names)
- return source, lexer
-
-def _compile_text(template, text, filename):
- identifier = template.module_id
- source, lexer = _compile(template, text, filename,
- generate_magic_comment=template.disable_unicode)
-
- cid = identifier
- if not compat.py3k and isinstance(cid, compat.text_type):
- cid = cid.encode()
- module = types.ModuleType(cid)
- code = compile(source, cid, 'exec')
-
- # this exec() works for 2.4->3.3.
- exec(code, module.__dict__, module.__dict__)
- return (source, module)
-
-def _compile_module_file(template, text, filename, outputpath, module_writer):
- source, lexer = _compile(template, text, filename,
- generate_magic_comment=True)
-
- if isinstance(source, compat.text_type):
- source = source.encode(lexer.encoding or 'ascii')
-
- if module_writer:
- module_writer(source, outputpath)
- else:
- # make tempfiles in the same location as the ultimate
- # location. this ensures they're on the same filesystem,
- # avoiding synchronization issues.
- (dest, name) = tempfile.mkstemp(dir=os.path.dirname(outputpath))
-
- os.write(dest, source)
- os.close(dest)
- shutil.move(name, outputpath)
-
-def _get_module_info_from_callable(callable_):
- if compat.py3k:
- return _get_module_info(callable_.__globals__['__name__'])
- else:
- return _get_module_info(callable_.func_globals['__name__'])
-
-def _get_module_info(filename):
- return ModuleInfo._modules[filename]
-
diff --git a/Darwin/lib/python2.7/site-packages/mako/util.py b/Darwin/lib/python2.7/site-packages/mako/util.py
deleted file mode 100644
index 0a9e14e..0000000
--- a/Darwin/lib/python2.7/site-packages/mako/util.py
+++ /dev/null
@@ -1,365 +0,0 @@
-# mako/util.py
-# Copyright (C) 2006-2013 the Mako authors and contributors
-#
-# This module is part of Mako and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-import re
-import collections
-import codecs
-import os
-from mako import compat
-import operator
-
-def function_named(fn, name):
- """Return a function with a given __name__.
-
- Will assign to __name__ and return the original function if possible on
- the Python implementation, otherwise a new function will be constructed.
-
- """
- fn.__name__ = name
- return fn
-
-
-class PluginLoader(object):
- def __init__(self, group):
- self.group = group
- self.impls = {}
-
- def load(self, name):
- if name in self.impls:
- return self.impls[name]()
- else:
- import pkg_resources
- for impl in pkg_resources.iter_entry_points(
- self.group,
- name):
- self.impls[name] = impl.load
- return impl.load()
- else:
- from mako import exceptions
- raise exceptions.RuntimeException(
- "Can't load plugin %s %s" %
- (self.group, name))
-
- def register(self, name, modulepath, objname):
- def load():
- mod = __import__(modulepath)
- for token in modulepath.split(".")[1:]:
- mod = getattr(mod, token)
- return getattr(mod, objname)
- self.impls[name] = load
-
-def verify_directory(dir):
- """create and/or verify a filesystem directory."""
-
- tries = 0
-
- while not os.path.exists(dir):
- try:
- tries += 1
- os.makedirs(dir, compat.octal("0775"))
- except:
- if tries > 5:
- raise
-
-def to_list(x, default=None):
- if x is None:
- return default
- if not isinstance(x, (list, tuple)):
- return [x]
- else:
- return x
-
-
-class memoized_property(object):
- """A read-only @property that is only evaluated once."""
- def __init__(self, fget, doc=None):
- self.fget = fget
- self.__doc__ = doc or fget.__doc__
- self.__name__ = fget.__name__
-
- def __get__(self, obj, cls):
- if obj is None:
- return self
- obj.__dict__[self.__name__] = result = self.fget(obj)
- return result
-
-class memoized_instancemethod(object):
- """Decorate a method memoize its return value.
-
- Best applied to no-arg methods: memoization is not sensitive to
- argument values, and will always return the same value even when
- called with different arguments.
-
- """
- def __init__(self, fget, doc=None):
- self.fget = fget
- self.__doc__ = doc or fget.__doc__
- self.__name__ = fget.__name__
-
- def __get__(self, obj, cls):
- if obj is None:
- return self
- def oneshot(*args, **kw):
- result = self.fget(obj, *args, **kw)
- memo = lambda *a, **kw: result
- memo.__name__ = self.__name__
- memo.__doc__ = self.__doc__
- obj.__dict__[self.__name__] = memo
- return result
- oneshot.__name__ = self.__name__
- oneshot.__doc__ = self.__doc__
- return oneshot
-
-class SetLikeDict(dict):
- """a dictionary that has some setlike methods on it"""
- def union(self, other):
- """produce a 'union' of this dict and another (at the key level).
-
- values in the second dict take precedence over that of the first"""
- x = SetLikeDict(**self)
- x.update(other)
- return x
-
-class FastEncodingBuffer(object):
- """a very rudimentary buffer that is faster than StringIO,
- but doesn't crash on unicode data like cStringIO."""
-
- def __init__(self, encoding=None, errors='strict', as_unicode=False):
- self.data = collections.deque()
- self.encoding = encoding
- if as_unicode:
- self.delim = compat.u('')
- else:
- self.delim = ''
- self.as_unicode = as_unicode
- self.errors = errors
- self.write = self.data.append
-
- def truncate(self):
- self.data = collections.deque()
- self.write = self.data.append
-
- def getvalue(self):
- if self.encoding:
- return self.delim.join(self.data).encode(self.encoding,
- self.errors)
- else:
- return self.delim.join(self.data)
-
-class LRUCache(dict):
- """A dictionary-like object that stores a limited number of items,
- discarding lesser used items periodically.
-
- this is a rewrite of LRUCache from Myghty to use a periodic timestamp-based
- paradigm so that synchronization is not really needed. the size management
- is inexact.
- """
-
- class _Item(object):
- def __init__(self, key, value):
- self.key = key
- self.value = value
- self.timestamp = compat.time_func()
- def __repr__(self):
- return repr(self.value)
-
- def __init__(self, capacity, threshold=.5):
- self.capacity = capacity
- self.threshold = threshold
-
- def __getitem__(self, key):
- item = dict.__getitem__(self, key)
- item.timestamp = compat.time_func()
- return item.value
-
- def values(self):
- return [i.value for i in dict.values(self)]
-
- def setdefault(self, key, value):
- if key in self:
- return self[key]
- else:
- self[key] = value
- return value
-
- def __setitem__(self, key, value):
- item = dict.get(self, key)
- if item is None:
- item = self._Item(key, value)
- dict.__setitem__(self, key, item)
- else:
- item.value = value
- self._manage_size()
-
- def _manage_size(self):
- while len(self) > self.capacity + self.capacity * self.threshold:
- bytime = sorted(dict.values(self),
- key=operator.attrgetter('timestamp'), reverse=True)
- for item in bytime[self.capacity:]:
- try:
- del self[item.key]
- except KeyError:
- # if we couldn't find a key, most likely some other thread
- # broke in on us. loop around and try again
- break
-
-# Regexp to match python magic encoding line
-_PYTHON_MAGIC_COMMENT_re = re.compile(
- r'[ \t\f]* \# .* coding[=:][ \t]*([-\w.]+)',
- re.VERBOSE)
-
-def parse_encoding(fp):
- """Deduce the encoding of a Python source file (binary mode) from magic
- comment.
-
- It does this in the same way as the `Python interpreter`__
-
- .. __: http://docs.python.org/ref/encodings.html
-
- The ``fp`` argument should be a seekable file object in binary mode.
- """
- pos = fp.tell()
- fp.seek(0)
- try:
- line1 = fp.readline()
- has_bom = line1.startswith(codecs.BOM_UTF8)
- if has_bom:
- line1 = line1[len(codecs.BOM_UTF8):]
-
- m = _PYTHON_MAGIC_COMMENT_re.match(line1.decode('ascii', 'ignore'))
- if not m:
- try:
- import parser
- parser.suite(line1.decode('ascii', 'ignore'))
- except (ImportError, SyntaxError):
- # Either it's a real syntax error, in which case the source
- # is not valid python source, or line2 is a continuation of
- # line1, in which case we don't want to scan line2 for a magic
- # comment.
- pass
- else:
- line2 = fp.readline()
- m = _PYTHON_MAGIC_COMMENT_re.match(
- line2.decode('ascii', 'ignore'))
-
- if has_bom:
- if m:
- raise SyntaxError("python refuses to compile code with both a UTF8" \
- " byte-order-mark and a magic encoding comment")
- return 'utf_8'
- elif m:
- return m.group(1)
- else:
- return None
- finally:
- fp.seek(pos)
-
-def sorted_dict_repr(d):
- """repr() a dictionary with the keys in order.
-
- Used by the lexer unit test to compare parse trees based on strings.
-
- """
- keys = list(d.keys())
- keys.sort()
- return "{" + ", ".join(["%r: %r" % (k, d[k]) for k in keys]) + "}"
-
-def restore__ast(_ast):
- """Attempt to restore the required classes to the _ast module if it
- appears to be missing them
- """
- if hasattr(_ast, 'AST'):
- return
- _ast.PyCF_ONLY_AST = 2 << 9
- m = compile("""\
-def foo(): pass
-class Bar(object): pass
-if False: pass
-baz = 'mako'
-1 + 2 - 3 * 4 / 5
-6 // 7 % 8 << 9 >> 10
-11 & 12 ^ 13 | 14
-15 and 16 or 17
--baz + (not +18) - ~17
-baz and 'foo' or 'bar'
-(mako is baz == baz) is not baz != mako
-mako > baz < mako >= baz <= mako
-mako in baz not in mako""", '', 'exec', _ast.PyCF_ONLY_AST)
- _ast.Module = type(m)
-
- for cls in _ast.Module.__mro__:
- if cls.__name__ == 'mod':
- _ast.mod = cls
- elif cls.__name__ == 'AST':
- _ast.AST = cls
-
- _ast.FunctionDef = type(m.body[0])
- _ast.ClassDef = type(m.body[1])
- _ast.If = type(m.body[2])
-
- _ast.Name = type(m.body[3].targets[0])
- _ast.Store = type(m.body[3].targets[0].ctx)
- _ast.Str = type(m.body[3].value)
-
- _ast.Sub = type(m.body[4].value.op)
- _ast.Add = type(m.body[4].value.left.op)
- _ast.Div = type(m.body[4].value.right.op)
- _ast.Mult = type(m.body[4].value.right.left.op)
-
- _ast.RShift = type(m.body[5].value.op)
- _ast.LShift = type(m.body[5].value.left.op)
- _ast.Mod = type(m.body[5].value.left.left.op)
- _ast.FloorDiv = type(m.body[5].value.left.left.left.op)
-
- _ast.BitOr = type(m.body[6].value.op)
- _ast.BitXor = type(m.body[6].value.left.op)
- _ast.BitAnd = type(m.body[6].value.left.left.op)
-
- _ast.Or = type(m.body[7].value.op)
- _ast.And = type(m.body[7].value.values[0].op)
-
- _ast.Invert = type(m.body[8].value.right.op)
- _ast.Not = type(m.body[8].value.left.right.op)
- _ast.UAdd = type(m.body[8].value.left.right.operand.op)
- _ast.USub = type(m.body[8].value.left.left.op)
-
- _ast.Or = type(m.body[9].value.op)
- _ast.And = type(m.body[9].value.values[0].op)
-
- _ast.IsNot = type(m.body[10].value.ops[0])
- _ast.NotEq = type(m.body[10].value.ops[1])
- _ast.Is = type(m.body[10].value.left.ops[0])
- _ast.Eq = type(m.body[10].value.left.ops[1])
-
- _ast.Gt = type(m.body[11].value.ops[0])
- _ast.Lt = type(m.body[11].value.ops[1])
- _ast.GtE = type(m.body[11].value.ops[2])
- _ast.LtE = type(m.body[11].value.ops[3])
-
- _ast.In = type(m.body[12].value.ops[0])
- _ast.NotIn = type(m.body[12].value.ops[1])
-
-
-
-def read_file(path, mode='rb'):
- fp = open(path, mode)
- try:
- data = fp.read()
- return data
- finally:
- fp.close()
-
-def read_python_file(path):
- fp = open(path, "rb")
- try:
- encoding = parse_encoding(fp)
- data = fp.read()
- if encoding:
- data = data.decode(encoding)
- return data
- finally:
- fp.close()
-
diff --git a/Darwin/lib/python2.7/site-packages/markupsafe/__init__.py b/Darwin/lib/python2.7/site-packages/markupsafe/__init__.py
deleted file mode 100644
index 2755401..0000000
--- a/Darwin/lib/python2.7/site-packages/markupsafe/__init__.py
+++ /dev/null
@@ -1,298 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- markupsafe
- ~~~~~~~~~~
-
- Implements a Markup string.
-
- :copyright: (c) 2010 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-import re
-import string
-from collections import Mapping
-from markupsafe._compat import text_type, string_types, int_types, \
- unichr, iteritems, PY2
-
-
-__all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']
-
-
-_striptags_re = re.compile(r'(|<[^>]*>)')
-_entity_re = re.compile(r'&([^;]+);')
-
-
-class Markup(text_type):
- r"""Marks a string as being safe for inclusion in HTML/XML output without
- needing to be escaped. This implements the `__html__` interface a couple
- of frameworks and web applications use. :class:`Markup` is a direct
- subclass of `unicode` and provides all the methods of `unicode` just that
- it escapes arguments passed and always returns `Markup`.
-
- The `escape` function returns markup objects so that double escaping can't
- happen.
-
- The constructor of the :class:`Markup` class can be used for three
- different things: When passed an unicode object it's assumed to be safe,
- when passed an object with an HTML representation (has an `__html__`
- method) that representation is used, otherwise the object passed is
- converted into a unicode string and then assumed to be safe:
-
- >>> Markup("Hello World!")
- Markup(u'Hello World!')
- >>> class Foo(object):
- ... def __html__(self):
- ... return 'foo'
- ...
- >>> Markup(Foo())
- Markup(u'foo')
-
- If you want object passed being always treated as unsafe you can use the
- :meth:`escape` classmethod to create a :class:`Markup` object:
-
- >>> Markup.escape("Hello World!")
- Markup(u'Hello <em>World</em>!')
-
- Operations on a markup string are markup aware which means that all
- arguments are passed through the :func:`escape` function:
-
- >>> em = Markup("%s")
- >>> em % "foo & bar"
- Markup(u'foo & bar')
- >>> strong = Markup("%(text)s")
- >>> strong % {'text': ''}
- Markup(u'<blink>hacker here</blink>')
- >>> Markup("Hello ") + ""
- Markup(u'Hello <foo>')
- """
- __slots__ = ()
-
- def __new__(cls, base=u'', encoding=None, errors='strict'):
- if hasattr(base, '__html__'):
- base = base.__html__()
- if encoding is None:
- return text_type.__new__(cls, base)
- return text_type.__new__(cls, base, encoding, errors)
-
- def __html__(self):
- return self
-
- def __add__(self, other):
- if isinstance(other, string_types) or hasattr(other, '__html__'):
- return self.__class__(super(Markup, self).__add__(self.escape(other)))
- return NotImplemented
-
- def __radd__(self, other):
- if hasattr(other, '__html__') or isinstance(other, string_types):
- return self.escape(other).__add__(self)
- return NotImplemented
-
- def __mul__(self, num):
- if isinstance(num, int_types):
- return self.__class__(text_type.__mul__(self, num))
- return NotImplemented
- __rmul__ = __mul__
-
- def __mod__(self, arg):
- if isinstance(arg, tuple):
- arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
- else:
- arg = _MarkupEscapeHelper(arg, self.escape)
- return self.__class__(text_type.__mod__(self, arg))
-
- def __repr__(self):
- return '%s(%s)' % (
- self.__class__.__name__,
- text_type.__repr__(self)
- )
-
- def join(self, seq):
- return self.__class__(text_type.join(self, map(self.escape, seq)))
- join.__doc__ = text_type.join.__doc__
-
- def split(self, *args, **kwargs):
- return list(map(self.__class__, text_type.split(self, *args, **kwargs)))
- split.__doc__ = text_type.split.__doc__
-
- def rsplit(self, *args, **kwargs):
- return list(map(self.__class__, text_type.rsplit(self, *args, **kwargs)))
- rsplit.__doc__ = text_type.rsplit.__doc__
-
- def splitlines(self, *args, **kwargs):
- return list(map(self.__class__, text_type.splitlines(
- self, *args, **kwargs)))
- splitlines.__doc__ = text_type.splitlines.__doc__
-
- def unescape(self):
- r"""Unescape markup again into an text_type string. This also resolves
- known HTML4 and XHTML entities:
-
- >>> Markup("Main » About").unescape()
- u'Main \xbb About'
- """
- from markupsafe._constants import HTML_ENTITIES
- def handle_match(m):
- name = m.group(1)
- if name in HTML_ENTITIES:
- return unichr(HTML_ENTITIES[name])
- try:
- if name[:2] in ('#x', '#X'):
- return unichr(int(name[2:], 16))
- elif name.startswith('#'):
- return unichr(int(name[1:]))
- except ValueError:
- pass
- return u''
- return _entity_re.sub(handle_match, text_type(self))
-
- def striptags(self):
- r"""Unescape markup into an text_type string and strip all tags. This
- also resolves known HTML4 and XHTML entities. Whitespace is
- normalized to one:
-
- >>> Markup("Main » About").striptags()
- u'Main \xbb About'
- """
- stripped = u' '.join(_striptags_re.sub('', self).split())
- return Markup(stripped).unescape()
-
- @classmethod
- def escape(cls, s):
- """Escape the string. Works like :func:`escape` with the difference
- that for subclasses of :class:`Markup` this function would return the
- correct subclass.
- """
- rv = escape(s)
- if rv.__class__ is not cls:
- return cls(rv)
- return rv
-
- def make_simple_escaping_wrapper(name):
- orig = getattr(text_type, name)
- def func(self, *args, **kwargs):
- args = _escape_argspec(list(args), enumerate(args), self.escape)
- _escape_argspec(kwargs, iteritems(kwargs), self.escape)
- return self.__class__(orig(self, *args, **kwargs))
- func.__name__ = orig.__name__
- func.__doc__ = orig.__doc__
- return func
-
- for method in '__getitem__', 'capitalize', \
- 'title', 'lower', 'upper', 'replace', 'ljust', \
- 'rjust', 'lstrip', 'rstrip', 'center', 'strip', \
- 'translate', 'expandtabs', 'swapcase', 'zfill':
- locals()[method] = make_simple_escaping_wrapper(method)
-
- # new in python 2.5
- if hasattr(text_type, 'partition'):
- def partition(self, sep):
- return tuple(map(self.__class__,
- text_type.partition(self, self.escape(sep))))
- def rpartition(self, sep):
- return tuple(map(self.__class__,
- text_type.rpartition(self, self.escape(sep))))
-
- # new in python 2.6
- if hasattr(text_type, 'format'):
- def format(*args, **kwargs):
- self, args = args[0], args[1:]
- formatter = EscapeFormatter(self.escape)
- kwargs = _MagicFormatMapping(args, kwargs)
- return self.__class__(formatter.vformat(self, args, kwargs))
-
- def __html_format__(self, format_spec):
- if format_spec:
- raise ValueError('Unsupported format specification '
- 'for Markup.')
- return self
-
- # not in python 3
- if hasattr(text_type, '__getslice__'):
- __getslice__ = make_simple_escaping_wrapper('__getslice__')
-
- del method, make_simple_escaping_wrapper
-
-
-class _MagicFormatMapping(Mapping):
- """This class implements a dummy wrapper to fix a bug in the Python
- standard library for string formatting.
-
- See http://bugs.python.org/issue13598 for information about why
- this is necessary.
- """
-
- def __init__(self, args, kwargs):
- self._args = args
- self._kwargs = kwargs
- self._last_index = 0
-
- def __getitem__(self, key):
- if key == '':
- idx = self._last_index
- self._last_index += 1
- try:
- return self._args[idx]
- except LookupError:
- pass
- key = str(idx)
- return self._kwargs[key]
-
- def __iter__(self):
- return iter(self._kwargs)
-
- def __len__(self):
- return len(self._kwargs)
-
-
-if hasattr(text_type, 'format'):
- class EscapeFormatter(string.Formatter):
-
- def __init__(self, escape):
- self.escape = escape
-
- def format_field(self, value, format_spec):
- if hasattr(value, '__html_format__'):
- rv = value.__html_format__(format_spec)
- elif hasattr(value, '__html__'):
- if format_spec:
- raise ValueError('No format specification allowed '
- 'when formatting an object with '
- 'its __html__ method.')
- rv = value.__html__()
- else:
- rv = string.Formatter.format_field(self, value, format_spec)
- return text_type(self.escape(rv))
-
-
-def _escape_argspec(obj, iterable, escape):
- """Helper for various string-wrapped functions."""
- for key, value in iterable:
- if hasattr(value, '__html__') or isinstance(value, string_types):
- obj[key] = escape(value)
- return obj
-
-
-class _MarkupEscapeHelper(object):
- """Helper for Markup.__mod__"""
-
- def __init__(self, obj, escape):
- self.obj = obj
- self.escape = escape
-
- __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x], s.escape)
- __unicode__ = __str__ = lambda s: text_type(s.escape(s.obj))
- __repr__ = lambda s: str(s.escape(repr(s.obj)))
- __int__ = lambda s: int(s.obj)
- __float__ = lambda s: float(s.obj)
-
-
-# we have to import it down here as the speedups and native
-# modules imports the markup type which is define above.
-try:
- from markupsafe._speedups import escape, escape_silent, soft_unicode
-except ImportError:
- from markupsafe._native import escape, escape_silent, soft_unicode
-
-if not PY2:
- soft_str = soft_unicode
- __all__.append('soft_str')
diff --git a/Darwin/lib/python2.7/site-packages/markupsafe/_compat.py b/Darwin/lib/python2.7/site-packages/markupsafe/_compat.py
deleted file mode 100644
index 62e5632..0000000
--- a/Darwin/lib/python2.7/site-packages/markupsafe/_compat.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- markupsafe._compat
- ~~~~~~~~~~~~~~~~~~
-
- Compatibility module for different Python versions.
-
- :copyright: (c) 2013 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-import sys
-
-PY2 = sys.version_info[0] == 2
-
-if not PY2:
- text_type = str
- string_types = (str,)
- unichr = chr
- int_types = (int,)
- iteritems = lambda x: iter(x.items())
-else:
- text_type = unicode
- string_types = (str, unicode)
- unichr = unichr
- int_types = (int, long)
- iteritems = lambda x: x.iteritems()
diff --git a/Darwin/lib/python2.7/site-packages/markupsafe/_constants.py b/Darwin/lib/python2.7/site-packages/markupsafe/_constants.py
deleted file mode 100644
index 919bf03..0000000
--- a/Darwin/lib/python2.7/site-packages/markupsafe/_constants.py
+++ /dev/null
@@ -1,267 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- markupsafe._constants
- ~~~~~~~~~~~~~~~~~~~~~
-
- Highlevel implementation of the Markup string.
-
- :copyright: (c) 2010 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-
-
-HTML_ENTITIES = {
- 'AElig': 198,
- 'Aacute': 193,
- 'Acirc': 194,
- 'Agrave': 192,
- 'Alpha': 913,
- 'Aring': 197,
- 'Atilde': 195,
- 'Auml': 196,
- 'Beta': 914,
- 'Ccedil': 199,
- 'Chi': 935,
- 'Dagger': 8225,
- 'Delta': 916,
- 'ETH': 208,
- 'Eacute': 201,
- 'Ecirc': 202,
- 'Egrave': 200,
- 'Epsilon': 917,
- 'Eta': 919,
- 'Euml': 203,
- 'Gamma': 915,
- 'Iacute': 205,
- 'Icirc': 206,
- 'Igrave': 204,
- 'Iota': 921,
- 'Iuml': 207,
- 'Kappa': 922,
- 'Lambda': 923,
- 'Mu': 924,
- 'Ntilde': 209,
- 'Nu': 925,
- 'OElig': 338,
- 'Oacute': 211,
- 'Ocirc': 212,
- 'Ograve': 210,
- 'Omega': 937,
- 'Omicron': 927,
- 'Oslash': 216,
- 'Otilde': 213,
- 'Ouml': 214,
- 'Phi': 934,
- 'Pi': 928,
- 'Prime': 8243,
- 'Psi': 936,
- 'Rho': 929,
- 'Scaron': 352,
- 'Sigma': 931,
- 'THORN': 222,
- 'Tau': 932,
- 'Theta': 920,
- 'Uacute': 218,
- 'Ucirc': 219,
- 'Ugrave': 217,
- 'Upsilon': 933,
- 'Uuml': 220,
- 'Xi': 926,
- 'Yacute': 221,
- 'Yuml': 376,
- 'Zeta': 918,
- 'aacute': 225,
- 'acirc': 226,
- 'acute': 180,
- 'aelig': 230,
- 'agrave': 224,
- 'alefsym': 8501,
- 'alpha': 945,
- 'amp': 38,
- 'and': 8743,
- 'ang': 8736,
- 'apos': 39,
- 'aring': 229,
- 'asymp': 8776,
- 'atilde': 227,
- 'auml': 228,
- 'bdquo': 8222,
- 'beta': 946,
- 'brvbar': 166,
- 'bull': 8226,
- 'cap': 8745,
- 'ccedil': 231,
- 'cedil': 184,
- 'cent': 162,
- 'chi': 967,
- 'circ': 710,
- 'clubs': 9827,
- 'cong': 8773,
- 'copy': 169,
- 'crarr': 8629,
- 'cup': 8746,
- 'curren': 164,
- 'dArr': 8659,
- 'dagger': 8224,
- 'darr': 8595,
- 'deg': 176,
- 'delta': 948,
- 'diams': 9830,
- 'divide': 247,
- 'eacute': 233,
- 'ecirc': 234,
- 'egrave': 232,
- 'empty': 8709,
- 'emsp': 8195,
- 'ensp': 8194,
- 'epsilon': 949,
- 'equiv': 8801,
- 'eta': 951,
- 'eth': 240,
- 'euml': 235,
- 'euro': 8364,
- 'exist': 8707,
- 'fnof': 402,
- 'forall': 8704,
- 'frac12': 189,
- 'frac14': 188,
- 'frac34': 190,
- 'frasl': 8260,
- 'gamma': 947,
- 'ge': 8805,
- 'gt': 62,
- 'hArr': 8660,
- 'harr': 8596,
- 'hearts': 9829,
- 'hellip': 8230,
- 'iacute': 237,
- 'icirc': 238,
- 'iexcl': 161,
- 'igrave': 236,
- 'image': 8465,
- 'infin': 8734,
- 'int': 8747,
- 'iota': 953,
- 'iquest': 191,
- 'isin': 8712,
- 'iuml': 239,
- 'kappa': 954,
- 'lArr': 8656,
- 'lambda': 955,
- 'lang': 9001,
- 'laquo': 171,
- 'larr': 8592,
- 'lceil': 8968,
- 'ldquo': 8220,
- 'le': 8804,
- 'lfloor': 8970,
- 'lowast': 8727,
- 'loz': 9674,
- 'lrm': 8206,
- 'lsaquo': 8249,
- 'lsquo': 8216,
- 'lt': 60,
- 'macr': 175,
- 'mdash': 8212,
- 'micro': 181,
- 'middot': 183,
- 'minus': 8722,
- 'mu': 956,
- 'nabla': 8711,
- 'nbsp': 160,
- 'ndash': 8211,
- 'ne': 8800,
- 'ni': 8715,
- 'not': 172,
- 'notin': 8713,
- 'nsub': 8836,
- 'ntilde': 241,
- 'nu': 957,
- 'oacute': 243,
- 'ocirc': 244,
- 'oelig': 339,
- 'ograve': 242,
- 'oline': 8254,
- 'omega': 969,
- 'omicron': 959,
- 'oplus': 8853,
- 'or': 8744,
- 'ordf': 170,
- 'ordm': 186,
- 'oslash': 248,
- 'otilde': 245,
- 'otimes': 8855,
- 'ouml': 246,
- 'para': 182,
- 'part': 8706,
- 'permil': 8240,
- 'perp': 8869,
- 'phi': 966,
- 'pi': 960,
- 'piv': 982,
- 'plusmn': 177,
- 'pound': 163,
- 'prime': 8242,
- 'prod': 8719,
- 'prop': 8733,
- 'psi': 968,
- 'quot': 34,
- 'rArr': 8658,
- 'radic': 8730,
- 'rang': 9002,
- 'raquo': 187,
- 'rarr': 8594,
- 'rceil': 8969,
- 'rdquo': 8221,
- 'real': 8476,
- 'reg': 174,
- 'rfloor': 8971,
- 'rho': 961,
- 'rlm': 8207,
- 'rsaquo': 8250,
- 'rsquo': 8217,
- 'sbquo': 8218,
- 'scaron': 353,
- 'sdot': 8901,
- 'sect': 167,
- 'shy': 173,
- 'sigma': 963,
- 'sigmaf': 962,
- 'sim': 8764,
- 'spades': 9824,
- 'sub': 8834,
- 'sube': 8838,
- 'sum': 8721,
- 'sup': 8835,
- 'sup1': 185,
- 'sup2': 178,
- 'sup3': 179,
- 'supe': 8839,
- 'szlig': 223,
- 'tau': 964,
- 'there4': 8756,
- 'theta': 952,
- 'thetasym': 977,
- 'thinsp': 8201,
- 'thorn': 254,
- 'tilde': 732,
- 'times': 215,
- 'trade': 8482,
- 'uArr': 8657,
- 'uacute': 250,
- 'uarr': 8593,
- 'ucirc': 251,
- 'ugrave': 249,
- 'uml': 168,
- 'upsih': 978,
- 'upsilon': 965,
- 'uuml': 252,
- 'weierp': 8472,
- 'xi': 958,
- 'yacute': 253,
- 'yen': 165,
- 'yuml': 255,
- 'zeta': 950,
- 'zwj': 8205,
- 'zwnj': 8204
-}
diff --git a/Darwin/lib/python2.7/site-packages/markupsafe/_native.py b/Darwin/lib/python2.7/site-packages/markupsafe/_native.py
deleted file mode 100644
index 5e83f10..0000000
--- a/Darwin/lib/python2.7/site-packages/markupsafe/_native.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- markupsafe._native
- ~~~~~~~~~~~~~~~~~~
-
- Native Python implementation the C module is not compiled.
-
- :copyright: (c) 2010 by Armin Ronacher.
- :license: BSD, see LICENSE for more details.
-"""
-from markupsafe import Markup
-from markupsafe._compat import text_type
-
-
-def escape(s):
- """Convert the characters &, <, >, ' and " in string s to HTML-safe
- sequences. Use this if you need to display text that might contain
- such characters in HTML. Marks return value as markup string.
- """
- if hasattr(s, '__html__'):
- return s.__html__()
- return Markup(text_type(s)
- .replace('&', '&')
- .replace('>', '>')
- .replace('<', '<')
- .replace("'", ''')
- .replace('"', '"')
- )
-
-
-def escape_silent(s):
- """Like :func:`escape` but converts `None` into an empty
- markup string.
- """
- if s is None:
- return Markup()
- return escape(s)
-
-
-def soft_unicode(s):
- """Make a string unicode if it isn't already. That way a markup
- string is not converted back to unicode.
- """
- if not isinstance(s, text_type):
- s = text_type(s)
- return s
diff --git a/Darwin/lib/python2.7/site-packages/markupsafe/_speedups.c b/Darwin/lib/python2.7/site-packages/markupsafe/_speedups.c
deleted file mode 100644
index f349feb..0000000
--- a/Darwin/lib/python2.7/site-packages/markupsafe/_speedups.c
+++ /dev/null
@@ -1,239 +0,0 @@
-/**
- * markupsafe._speedups
- * ~~~~~~~~~~~~~~~~~~~~
- *
- * This module implements functions for automatic escaping in C for better
- * performance.
- *
- * :copyright: (c) 2010 by Armin Ronacher.
- * :license: BSD.
- */
-
-#include
-
-#define ESCAPED_CHARS_TABLE_SIZE 63
-#define UNICHR(x) (PyUnicode_AS_UNICODE((PyUnicodeObject*)PyUnicode_DecodeASCII(x, strlen(x), NULL)));
-
-#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
-typedef int Py_ssize_t;
-#define PY_SSIZE_T_MAX INT_MAX
-#define PY_SSIZE_T_MIN INT_MIN
-#endif
-
-
-static PyObject* markup;
-static Py_ssize_t escaped_chars_delta_len[ESCAPED_CHARS_TABLE_SIZE];
-static Py_UNICODE *escaped_chars_repl[ESCAPED_CHARS_TABLE_SIZE];
-
-static int
-init_constants(void)
-{
- PyObject *module;
- /* happing of characters to replace */
- escaped_chars_repl['"'] = UNICHR(""");
- escaped_chars_repl['\''] = UNICHR("'");
- escaped_chars_repl['&'] = UNICHR("&");
- escaped_chars_repl['<'] = UNICHR("<");
- escaped_chars_repl['>'] = UNICHR(">");
-
- /* lengths of those characters when replaced - 1 */
- memset(escaped_chars_delta_len, 0, sizeof (escaped_chars_delta_len));
- escaped_chars_delta_len['"'] = escaped_chars_delta_len['\''] = \
- escaped_chars_delta_len['&'] = 4;
- escaped_chars_delta_len['<'] = escaped_chars_delta_len['>'] = 3;
-
- /* import markup type so that we can mark the return value */
- module = PyImport_ImportModule("markupsafe");
- if (!module)
- return 0;
- markup = PyObject_GetAttrString(module, "Markup");
- Py_DECREF(module);
-
- return 1;
-}
-
-static PyObject*
-escape_unicode(PyUnicodeObject *in)
-{
- PyUnicodeObject *out;
- Py_UNICODE *inp = PyUnicode_AS_UNICODE(in);
- const Py_UNICODE *inp_end = PyUnicode_AS_UNICODE(in) + PyUnicode_GET_SIZE(in);
- Py_UNICODE *next_escp;
- Py_UNICODE *outp;
- Py_ssize_t delta=0, erepl=0, delta_len=0;
-
- /* First we need to figure out how long the escaped string will be */
- while (*(inp) || inp < inp_end) {
- if (*inp < ESCAPED_CHARS_TABLE_SIZE) {
- delta += escaped_chars_delta_len[*inp];
- erepl += !!escaped_chars_delta_len[*inp];
- }
- ++inp;
- }
-
- /* Do we need to escape anything at all? */
- if (!erepl) {
- Py_INCREF(in);
- return (PyObject*)in;
- }
-
- out = (PyUnicodeObject*)PyUnicode_FromUnicode(NULL, PyUnicode_GET_SIZE(in) + delta);
- if (!out)
- return NULL;
-
- outp = PyUnicode_AS_UNICODE(out);
- inp = PyUnicode_AS_UNICODE(in);
- while (erepl-- > 0) {
- /* look for the next substitution */
- next_escp = inp;
- while (next_escp < inp_end) {
- if (*next_escp < ESCAPED_CHARS_TABLE_SIZE &&
- (delta_len = escaped_chars_delta_len[*next_escp])) {
- ++delta_len;
- break;
- }
- ++next_escp;
- }
-
- if (next_escp > inp) {
- /* copy unescaped chars between inp and next_escp */
- Py_UNICODE_COPY(outp, inp, next_escp-inp);
- outp += next_escp - inp;
- }
-
- /* escape 'next_escp' */
- Py_UNICODE_COPY(outp, escaped_chars_repl[*next_escp], delta_len);
- outp += delta_len;
-
- inp = next_escp + 1;
- }
- if (inp < inp_end)
- Py_UNICODE_COPY(outp, inp, PyUnicode_GET_SIZE(in) - (inp - PyUnicode_AS_UNICODE(in)));
-
- return (PyObject*)out;
-}
-
-
-static PyObject*
-escape(PyObject *self, PyObject *text)
-{
- PyObject *s = NULL, *rv = NULL, *html;
-
- /* we don't have to escape integers, bools or floats */
- if (PyLong_CheckExact(text) ||
-#if PY_MAJOR_VERSION < 3
- PyInt_CheckExact(text) ||
-#endif
- PyFloat_CheckExact(text) || PyBool_Check(text) ||
- text == Py_None)
- return PyObject_CallFunctionObjArgs(markup, text, NULL);
-
- /* if the object has an __html__ method that performs the escaping */
- html = PyObject_GetAttrString(text, "__html__");
- if (html) {
- rv = PyObject_CallObject(html, NULL);
- Py_DECREF(html);
- return rv;
- }
-
- /* otherwise make the object unicode if it isn't, then escape */
- PyErr_Clear();
- if (!PyUnicode_Check(text)) {
-#if PY_MAJOR_VERSION < 3
- PyObject *unicode = PyObject_Unicode(text);
-#else
- PyObject *unicode = PyObject_Str(text);
-#endif
- if (!unicode)
- return NULL;
- s = escape_unicode((PyUnicodeObject*)unicode);
- Py_DECREF(unicode);
- }
- else
- s = escape_unicode((PyUnicodeObject*)text);
-
- /* convert the unicode string into a markup object. */
- rv = PyObject_CallFunctionObjArgs(markup, (PyObject*)s, NULL);
- Py_DECREF(s);
- return rv;
-}
-
-
-static PyObject*
-escape_silent(PyObject *self, PyObject *text)
-{
- if (text != Py_None)
- return escape(self, text);
- return PyObject_CallFunctionObjArgs(markup, NULL);
-}
-
-
-static PyObject*
-soft_unicode(PyObject *self, PyObject *s)
-{
- if (!PyUnicode_Check(s))
-#if PY_MAJOR_VERSION < 3
- return PyObject_Unicode(s);
-#else
- return PyObject_Str(s);
-#endif
- Py_INCREF(s);
- return s;
-}
-
-
-static PyMethodDef module_methods[] = {
- {"escape", (PyCFunction)escape, METH_O,
- "escape(s) -> markup\n\n"
- "Convert the characters &, <, >, ', and \" in string s to HTML-safe\n"
- "sequences. Use this if you need to display text that might contain\n"
- "such characters in HTML. Marks return value as markup string."},
- {"escape_silent", (PyCFunction)escape_silent, METH_O,
- "escape_silent(s) -> markup\n\n"
- "Like escape but converts None to an empty string."},
- {"soft_unicode", (PyCFunction)soft_unicode, METH_O,
- "soft_unicode(object) -> string\n\n"
- "Make a string unicode if it isn't already. That way a markup\n"
- "string is not converted back to unicode."},
- {NULL, NULL, 0, NULL} /* Sentinel */
-};
-
-
-#if PY_MAJOR_VERSION < 3
-
-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
-#define PyMODINIT_FUNC void
-#endif
-PyMODINIT_FUNC
-init_speedups(void)
-{
- if (!init_constants())
- return;
-
- Py_InitModule3("markupsafe._speedups", module_methods, "");
-}
-
-#else /* Python 3.x module initialization */
-
-static struct PyModuleDef module_definition = {
- PyModuleDef_HEAD_INIT,
- "markupsafe._speedups",
- NULL,
- -1,
- module_methods,
- NULL,
- NULL,
- NULL,
- NULL
-};
-
-PyMODINIT_FUNC
-PyInit__speedups(void)
-{
- if (!init_constants())
- return NULL;
-
- return PyModule_Create(&module_definition);
-}
-
-#endif
diff --git a/Darwin/lib/python2.7/site-packages/markupsafe/_speedups.so b/Darwin/lib/python2.7/site-packages/markupsafe/_speedups.so
deleted file mode 100755
index fce7a7c..0000000
Binary files a/Darwin/lib/python2.7/site-packages/markupsafe/_speedups.so and /dev/null differ
diff --git a/Darwin/lib/python2.7/site-packages/markupsafe/tests.py b/Darwin/lib/python2.7/site-packages/markupsafe/tests.py
deleted file mode 100644
index 6369936..0000000
--- a/Darwin/lib/python2.7/site-packages/markupsafe/tests.py
+++ /dev/null
@@ -1,179 +0,0 @@
-# -*- coding: utf-8 -*-
-import gc
-import sys
-import unittest
-from markupsafe import Markup, escape, escape_silent
-from markupsafe._compat import text_type
-
-
-class MarkupTestCase(unittest.TestCase):
-
- def test_adding(self):
- # adding two strings should escape the unsafe one
- unsafe = ''
- safe = Markup('username')
- assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)
-
- def test_string_interpolation(self):
- # string interpolations are safe to use too
- assert Markup('%s') % '' == \
- '<bad user>'
- assert Markup('%(username)s') % {
- 'username': ''
- } == '<bad user>'
-
- assert Markup('%i') % 3.14 == '3'
- assert Markup('%.2f') % 3.14 == '3.14'
-
- def test_type_behavior(self):
- # an escaped object is markup too
- assert type(Markup('foo') + 'bar') is Markup
-
- # and it implements __html__ by returning itself
- x = Markup("foo")
- assert x.__html__() is x
-
- def test_html_interop(self):
- # it also knows how to treat __html__ objects
- class Foo(object):
- def __html__(self):
- return 'awesome'
- def __unicode__(self):
- return 'awesome'
- __str__ = __unicode__
- assert Markup(Foo()) == 'awesome'
- assert Markup('%s') % Foo() == \
- 'awesome'
-
- def test_tuple_interpol(self):
- self.assertEqual(Markup('%s:%s') % (
- '',
- '',
- ), Markup(u'<foo>:<bar>'))
-
- def test_dict_interpol(self):
- self.assertEqual(Markup('%(foo)s') % {
- 'foo': '',
- }, Markup(u'<foo>'))
- self.assertEqual(Markup('%(foo)s:%(bar)s') % {
- 'foo': '',
- 'bar': '',
- }, Markup(u'<foo>:<bar>'))
-
- def test_escaping(self):
- # escaping and unescaping
- assert escape('"<>&\'') == '"<>&''
- assert Markup("Foo & Bar").striptags() == "Foo & Bar"
- assert Markup("<test>").unescape() == ""
-
- def test_formatting(self):
- for actual, expected in (
- (Markup('%i') % 3.14, '3'),
- (Markup('%.2f') % 3.14159, '3.14'),
- (Markup('%s %s %s') % ('<', 123, '>'), '< 123 >'),
- (Markup('{awesome}').format(awesome=''),
- '<awesome>'),
- (Markup('{0[1][bar]}').format([0, {'bar': ''}]),
- '<bar/>'),
- (Markup('{0[1][bar]}').format([0, {'bar': Markup('')}]),
- '')):
- assert actual == expected, "%r should be %r!" % (actual, expected)
-
- # This is new in 2.7
- if sys.version_info >= (2, 7):
- def test_formatting_empty(self):
- formatted = Markup('{}').format(0)
- assert formatted == Markup('0')
-
- def test_custom_formatting(self):
- class HasHTMLOnly(object):
- def __html__(self):
- return Markup('')
-
- class HasHTMLAndFormat(object):
- def __html__(self):
- return Markup('')
- def __html_format__(self, spec):
- return Markup('')
-
- assert Markup('{0}').format(HasHTMLOnly()) == Markup('')
- assert Markup('{0}').format(HasHTMLAndFormat()) == Markup('')
-
- def test_complex_custom_formatting(self):
- class User(object):
- def __init__(self, id, username):
- self.id = id
- self.username = username
- def __html_format__(self, format_spec):
- if format_spec == 'link':
- return Markup('{1}').format(
- self.id,
- self.__html__(),
- )
- elif format_spec:
- raise ValueError('Invalid format spec')
- return self.__html__()
- def __html__(self):
- return Markup('{0}').format(self.username)
-
- user = User(1, 'foo')
- assert Markup('User: {0:link}').format(user) == \
- Markup('
User: foo')
-
- def test_all_set(self):
- import markupsafe as markup
- for item in markup.__all__:
- getattr(markup, item)
-
- def test_escape_silent(self):
- assert escape_silent(None) == Markup()
- assert escape(None) == Markup(None)
- assert escape_silent('') == Markup(u'<foo>')
-
- def test_splitting(self):
- self.assertEqual(Markup('a b').split(), [
- Markup('a'),
- Markup('b')
- ])
- self.assertEqual(Markup('a b').rsplit(), [
- Markup('a'),
- Markup('b')
- ])
- self.assertEqual(Markup('a\nb').splitlines(), [
- Markup('a'),
- Markup('b')
- ])
-
- def test_mul(self):
- self.assertEqual(Markup('a') * 3, Markup('aaa'))
-
-
-class MarkupLeakTestCase(unittest.TestCase):
-
- def test_markup_leaks(self):
- counts = set()
- for count in range(20):
- for item in range(1000):
- escape("foo")
- escape("")
- escape(u"foo")
- escape(u"")
- counts.add(len(gc.get_objects()))
- assert len(counts) == 1, 'ouch, c extension seems to leak objects'
-
-
-def suite():
- suite = unittest.TestSuite()
- suite.addTest(unittest.makeSuite(MarkupTestCase))
-
- # this test only tests the c extension
- if not hasattr(escape, 'func_code'):
- suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
-
- return suite
-
-
-if __name__ == '__main__':
- unittest.main(defaultTest='suite')
-
-# vim:sts=4:sw=4:et:
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/dependency_links.txt b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/not-zip-safe b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/not-zip-safe
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/not-zip-safe
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treeadapters/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treeadapters/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/__init__.py
deleted file mode 100644
index 743c874..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/__init__.py
+++ /dev/null
@@ -1,66 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-__version__ = "1.0.3"
-from sys import version_info
-
-
-def detect(aBuf):
- if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or
- (version_info >= (3, 0) and not isinstance(aBuf, bytes))):
- raise ValueError('Expected a bytes object, not a unicode object')
-
- from . import universaldetector
- u = universaldetector.UniversalDetector()
- u.reset()
- u.feed(aBuf)
- u.close()
- return u.result
-
-def _description_of(path):
- """Return a string describing the probable encoding of a file."""
- from charade.universaldetector import UniversalDetector
-
- u = UniversalDetector()
- for line in open(path, 'rb'):
- u.feed(line)
- u.close()
- result = u.result
- if result['encoding']:
- return '%s: %s with confidence %s' % (path,
- result['encoding'],
- result['confidence'])
- else:
- return '%s: no result' % path
-
-
-def charade_cli():
- """
- Script which takes one or more file paths and reports on their detected
- encodings
-
- Example::
-
- % chardetect.py somefile someotherfile
- somefile: windows-1252 with confidence 0.5
- someotherfile: ascii with confidence 1.0
-
- """
- from sys import argv
- for path in argv[1:]:
- print(_description_of(path))
-
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/__main__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/__main__.py
deleted file mode 100644
index 0fc37c3..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/__main__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-'''
-support ';python -m charade [file2] ...' package execution syntax (2.7+)
-'''
-
-from charade import charade_cli
-
-charade_cli()
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/jpcntx.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/jpcntx.py
deleted file mode 100644
index 0463442..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/jpcntx.py
+++ /dev/null
@@ -1,219 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .compat import wrap_ord
-
-NUM_OF_CATEGORY = 6
-DONT_KNOW = -1
-ENOUGH_REL_THRESHOLD = 100
-MAX_REL_THRESHOLD = 1000
-MINIMUM_DATA_THRESHOLD = 4
-
-# This is hiragana 2-char sequence table, the number in each cell represents its frequency category
-jp2CharContext = (
-(0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1),
-(2,4,0,4,0,3,0,4,0,3,4,4,4,2,4,3,3,4,3,2,3,3,4,2,3,3,3,2,4,1,4,3,3,1,5,4,3,4,3,4,3,5,3,0,3,5,4,2,0,3,1,0,3,3,0,3,3,0,1,1,0,4,3,0,3,3,0,4,0,2,0,3,5,5,5,5,4,0,4,1,0,3,4),
-(0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2),
-(0,4,0,5,0,5,0,4,0,4,5,4,4,3,5,3,5,1,5,3,4,3,4,4,3,4,3,3,4,3,5,4,4,3,5,5,3,5,5,5,3,5,5,3,4,5,5,3,1,3,2,0,3,4,0,4,2,0,4,2,1,5,3,2,3,5,0,4,0,2,0,5,4,4,5,4,5,0,4,0,0,4,4),
-(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
-(0,3,0,4,0,3,0,3,0,4,5,4,3,3,3,3,4,3,5,4,4,3,5,4,4,3,4,3,4,4,4,4,5,3,4,4,3,4,5,5,4,5,5,1,4,5,4,3,0,3,3,1,3,3,0,4,4,0,3,3,1,5,3,3,3,5,0,4,0,3,0,4,4,3,4,3,3,0,4,1,1,3,4),
-(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
-(0,4,0,3,0,3,0,4,0,3,4,4,3,2,2,1,2,1,3,1,3,3,3,3,3,4,3,1,3,3,5,3,3,0,4,3,0,5,4,3,3,5,4,4,3,4,4,5,0,1,2,0,1,2,0,2,2,0,1,0,0,5,2,2,1,4,0,3,0,1,0,4,4,3,5,4,3,0,2,1,0,4,3),
-(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
-(0,3,0,5,0,4,0,2,1,4,4,2,4,1,4,2,4,2,4,3,3,3,4,3,3,3,3,1,4,2,3,3,3,1,4,4,1,1,1,4,3,3,2,0,2,4,3,2,0,3,3,0,3,1,1,0,0,0,3,3,0,4,2,2,3,4,0,4,0,3,0,4,4,5,3,4,4,0,3,0,0,1,4),
-(1,4,0,4,0,4,0,4,0,3,5,4,4,3,4,3,5,4,3,3,4,3,5,4,4,4,4,3,4,2,4,3,3,1,5,4,3,2,4,5,4,5,5,4,4,5,4,4,0,3,2,2,3,3,0,4,3,1,3,2,1,4,3,3,4,5,0,3,0,2,0,4,5,5,4,5,4,0,4,0,0,5,4),
-(0,5,0,5,0,4,0,3,0,4,4,3,4,3,3,3,4,0,4,4,4,3,4,3,4,3,3,1,4,2,4,3,4,0,5,4,1,4,5,4,4,5,3,2,4,3,4,3,2,4,1,3,3,3,2,3,2,0,4,3,3,4,3,3,3,4,0,4,0,3,0,4,5,4,4,4,3,0,4,1,0,1,3),
-(0,3,1,4,0,3,0,2,0,3,4,4,3,1,4,2,3,3,4,3,4,3,4,3,4,4,3,2,3,1,5,4,4,1,4,4,3,5,4,4,3,5,5,4,3,4,4,3,1,2,3,1,2,2,0,3,2,0,3,1,0,5,3,3,3,4,3,3,3,3,4,4,4,4,5,4,2,0,3,3,2,4,3),
-(0,2,0,3,0,1,0,1,0,0,3,2,0,0,2,0,1,0,2,1,3,3,3,1,2,3,1,0,1,0,4,2,1,1,3,3,0,4,3,3,1,4,3,3,0,3,3,2,0,0,0,0,1,0,0,2,0,0,0,0,0,4,1,0,2,3,2,2,2,1,3,3,3,4,4,3,2,0,3,1,0,3,3),
-(0,4,0,4,0,3,0,3,0,4,4,4,3,3,3,3,3,3,4,3,4,2,4,3,4,3,3,2,4,3,4,5,4,1,4,5,3,5,4,5,3,5,4,0,3,5,5,3,1,3,3,2,2,3,0,3,4,1,3,3,2,4,3,3,3,4,0,4,0,3,0,4,5,4,4,5,3,0,4,1,0,3,4),
-(0,2,0,3,0,3,0,0,0,2,2,2,1,0,1,0,0,0,3,0,3,0,3,0,1,3,1,0,3,1,3,3,3,1,3,3,3,0,1,3,1,3,4,0,0,3,1,1,0,3,2,0,0,0,0,1,3,0,1,0,0,3,3,2,0,3,0,0,0,0,0,3,4,3,4,3,3,0,3,0,0,2,3),
-(2,3,0,3,0,2,0,1,0,3,3,4,3,1,3,1,1,1,3,1,4,3,4,3,3,3,0,0,3,1,5,4,3,1,4,3,2,5,5,4,4,4,4,3,3,4,4,4,0,2,1,1,3,2,0,1,2,0,0,1,0,4,1,3,3,3,0,3,0,1,0,4,4,4,5,5,3,0,2,0,0,4,4),
-(0,2,0,1,0,3,1,3,0,2,3,3,3,0,3,1,0,0,3,0,3,2,3,1,3,2,1,1,0,0,4,2,1,0,2,3,1,4,3,2,0,4,4,3,1,3,1,3,0,1,0,0,1,0,0,0,1,0,0,0,0,4,1,1,1,2,0,3,0,0,0,3,4,2,4,3,2,0,1,0,0,3,3),
-(0,1,0,4,0,5,0,4,0,2,4,4,2,3,3,2,3,3,5,3,3,3,4,3,4,2,3,0,4,3,3,3,4,1,4,3,2,1,5,5,3,4,5,1,3,5,4,2,0,3,3,0,1,3,0,4,2,0,1,3,1,4,3,3,3,3,0,3,0,1,0,3,4,4,4,5,5,0,3,0,1,4,5),
-(0,2,0,3,0,3,0,0,0,2,3,1,3,0,4,0,1,1,3,0,3,4,3,2,3,1,0,3,3,2,3,1,3,0,2,3,0,2,1,4,1,2,2,0,0,3,3,0,0,2,0,0,0,1,0,0,0,0,2,2,0,3,2,1,3,3,0,2,0,2,0,0,3,3,1,2,4,0,3,0,2,2,3),
-(2,4,0,5,0,4,0,4,0,2,4,4,4,3,4,3,3,3,1,2,4,3,4,3,4,4,5,0,3,3,3,3,2,0,4,3,1,4,3,4,1,4,4,3,3,4,4,3,1,2,3,0,4,2,0,4,1,0,3,3,0,4,3,3,3,4,0,4,0,2,0,3,5,3,4,5,2,0,3,0,0,4,5),
-(0,3,0,4,0,1,0,1,0,1,3,2,2,1,3,0,3,0,2,0,2,0,3,0,2,0,0,0,1,0,1,1,0,0,3,1,0,0,0,4,0,3,1,0,2,1,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,2,2,3,1,0,3,0,0,0,1,4,4,4,3,0,0,4,0,0,1,4),
-(1,4,1,5,0,3,0,3,0,4,5,4,4,3,5,3,3,4,4,3,4,1,3,3,3,3,2,1,4,1,5,4,3,1,4,4,3,5,4,4,3,5,4,3,3,4,4,4,0,3,3,1,2,3,0,3,1,0,3,3,0,5,4,4,4,4,4,4,3,3,5,4,4,3,3,5,4,0,3,2,0,4,4),
-(0,2,0,3,0,1,0,0,0,1,3,3,3,2,4,1,3,0,3,1,3,0,2,2,1,1,0,0,2,0,4,3,1,0,4,3,0,4,4,4,1,4,3,1,1,3,3,1,0,2,0,0,1,3,0,0,0,0,2,0,0,4,3,2,4,3,5,4,3,3,3,4,3,3,4,3,3,0,2,1,0,3,3),
-(0,2,0,4,0,3,0,2,0,2,5,5,3,4,4,4,4,1,4,3,3,0,4,3,4,3,1,3,3,2,4,3,0,3,4,3,0,3,4,4,2,4,4,0,4,5,3,3,2,2,1,1,1,2,0,1,5,0,3,3,2,4,3,3,3,4,0,3,0,2,0,4,4,3,5,5,0,0,3,0,2,3,3),
-(0,3,0,4,0,3,0,1,0,3,4,3,3,1,3,3,3,0,3,1,3,0,4,3,3,1,1,0,3,0,3,3,0,0,4,4,0,1,5,4,3,3,5,0,3,3,4,3,0,2,0,1,1,1,0,1,3,0,1,2,1,3,3,2,3,3,0,3,0,1,0,1,3,3,4,4,1,0,1,2,2,1,3),
-(0,1,0,4,0,4,0,3,0,1,3,3,3,2,3,1,1,0,3,0,3,3,4,3,2,4,2,0,1,0,4,3,2,0,4,3,0,5,3,3,2,4,4,4,3,3,3,4,0,1,3,0,0,1,0,0,1,0,0,0,0,4,2,3,3,3,0,3,0,0,0,4,4,4,5,3,2,0,3,3,0,3,5),
-(0,2,0,3,0,0,0,3,0,1,3,0,2,0,0,0,1,0,3,1,1,3,3,0,0,3,0,0,3,0,2,3,1,0,3,1,0,3,3,2,0,4,2,2,0,2,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,2,1,2,0,1,0,1,0,0,0,1,3,1,2,0,0,0,1,0,0,1,4),
-(0,3,0,3,0,5,0,1,0,2,4,3,1,3,3,2,1,1,5,2,1,0,5,1,2,0,0,0,3,3,2,2,3,2,4,3,0,0,3,3,1,3,3,0,2,5,3,4,0,3,3,0,1,2,0,2,2,0,3,2,0,2,2,3,3,3,0,2,0,1,0,3,4,4,2,5,4,0,3,0,0,3,5),
-(0,3,0,3,0,3,0,1,0,3,3,3,3,0,3,0,2,0,2,1,1,0,2,0,1,0,0,0,2,1,0,0,1,0,3,2,0,0,3,3,1,2,3,1,0,3,3,0,0,1,0,0,0,0,0,2,0,0,0,0,0,2,3,1,2,3,0,3,0,1,0,3,2,1,0,4,3,0,1,1,0,3,3),
-(0,4,0,5,0,3,0,3,0,4,5,5,4,3,5,3,4,3,5,3,3,2,5,3,4,4,4,3,4,3,4,5,5,3,4,4,3,4,4,5,4,4,4,3,4,5,5,4,2,3,4,2,3,4,0,3,3,1,4,3,2,4,3,3,5,5,0,3,0,3,0,5,5,5,5,4,4,0,4,0,1,4,4),
-(0,4,0,4,0,3,0,3,0,3,5,4,4,2,3,2,5,1,3,2,5,1,4,2,3,2,3,3,4,3,3,3,3,2,5,4,1,3,3,5,3,4,4,0,4,4,3,1,1,3,1,0,2,3,0,2,3,0,3,0,0,4,3,1,3,4,0,3,0,2,0,4,4,4,3,4,5,0,4,0,0,3,4),
-(0,3,0,3,0,3,1,2,0,3,4,4,3,3,3,0,2,2,4,3,3,1,3,3,3,1,1,0,3,1,4,3,2,3,4,4,2,4,4,4,3,4,4,3,2,4,4,3,1,3,3,1,3,3,0,4,1,0,2,2,1,4,3,2,3,3,5,4,3,3,5,4,4,3,3,0,4,0,3,2,2,4,4),
-(0,2,0,1,0,0,0,0,0,1,2,1,3,0,0,0,0,0,2,0,1,2,1,0,0,1,0,0,0,0,3,0,0,1,0,1,1,3,1,0,0,0,1,1,0,1,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,1,2,2,0,3,4,0,0,0,1,1,0,0,1,0,0,0,0,0,1,1),
-(0,1,0,0,0,1,0,0,0,0,4,0,4,1,4,0,3,0,4,0,3,0,4,0,3,0,3,0,4,1,5,1,4,0,0,3,0,5,0,5,2,0,1,0,0,0,2,1,4,0,1,3,0,0,3,0,0,3,1,1,4,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0),
-(1,4,0,5,0,3,0,2,0,3,5,4,4,3,4,3,5,3,4,3,3,0,4,3,3,3,3,3,3,2,4,4,3,1,3,4,4,5,4,4,3,4,4,1,3,5,4,3,3,3,1,2,2,3,3,1,3,1,3,3,3,5,3,3,4,5,0,3,0,3,0,3,4,3,4,4,3,0,3,0,2,4,3),
-(0,1,0,4,0,0,0,0,0,1,4,0,4,1,4,2,4,0,3,0,1,0,1,0,0,0,0,0,2,0,3,1,1,1,0,3,0,0,0,1,2,1,0,0,1,1,1,1,0,1,0,0,0,1,0,0,3,0,0,0,0,3,2,0,2,2,0,1,0,0,0,2,3,2,3,3,0,0,0,0,2,1,0),
-(0,5,1,5,0,3,0,3,0,5,4,4,5,1,5,3,3,0,4,3,4,3,5,3,4,3,3,2,4,3,4,3,3,0,3,3,1,4,4,3,4,4,4,3,4,5,5,3,2,3,1,1,3,3,1,3,1,1,3,3,2,4,5,3,3,5,0,4,0,3,0,4,4,3,5,3,3,0,3,4,0,4,3),
-(0,5,0,5,0,3,0,2,0,4,4,3,5,2,4,3,3,3,4,4,4,3,5,3,5,3,3,1,4,0,4,3,3,0,3,3,0,4,4,4,4,5,4,3,3,5,5,3,2,3,1,2,3,2,0,1,0,0,3,2,2,4,4,3,1,5,0,4,0,3,0,4,3,1,3,2,1,0,3,3,0,3,3),
-(0,4,0,5,0,5,0,4,0,4,5,5,5,3,4,3,3,2,5,4,4,3,5,3,5,3,4,0,4,3,4,4,3,2,4,4,3,4,5,4,4,5,5,0,3,5,5,4,1,3,3,2,3,3,1,3,1,0,4,3,1,4,4,3,4,5,0,4,0,2,0,4,3,4,4,3,3,0,4,0,0,5,5),
-(0,4,0,4,0,5,0,1,1,3,3,4,4,3,4,1,3,0,5,1,3,0,3,1,3,1,1,0,3,0,3,3,4,0,4,3,0,4,4,4,3,4,4,0,3,5,4,1,0,3,0,0,2,3,0,3,1,0,3,1,0,3,2,1,3,5,0,3,0,1,0,3,2,3,3,4,4,0,2,2,0,4,4),
-(2,4,0,5,0,4,0,3,0,4,5,5,4,3,5,3,5,3,5,3,5,2,5,3,4,3,3,4,3,4,5,3,2,1,5,4,3,2,3,4,5,3,4,1,2,5,4,3,0,3,3,0,3,2,0,2,3,0,4,1,0,3,4,3,3,5,0,3,0,1,0,4,5,5,5,4,3,0,4,2,0,3,5),
-(0,5,0,4,0,4,0,2,0,5,4,3,4,3,4,3,3,3,4,3,4,2,5,3,5,3,4,1,4,3,4,4,4,0,3,5,0,4,4,4,4,5,3,1,3,4,5,3,3,3,3,3,3,3,0,2,2,0,3,3,2,4,3,3,3,5,3,4,1,3,3,5,3,2,0,0,0,0,4,3,1,3,3),
-(0,1,0,3,0,3,0,1,0,1,3,3,3,2,3,3,3,0,3,0,0,0,3,1,3,0,0,0,2,2,2,3,0,0,3,2,0,1,2,4,1,3,3,0,0,3,3,3,0,1,0,0,2,1,0,0,3,0,3,1,0,3,0,0,1,3,0,2,0,1,0,3,3,1,3,3,0,0,1,1,0,3,3),
-(0,2,0,3,0,2,1,4,0,2,2,3,1,1,3,1,1,0,2,0,3,1,2,3,1,3,0,0,1,0,4,3,2,3,3,3,1,4,2,3,3,3,3,1,0,3,1,4,0,1,1,0,1,2,0,1,1,0,1,1,0,3,1,3,2,2,0,1,0,0,0,2,3,3,3,1,0,0,0,0,0,2,3),
-(0,5,0,4,0,5,0,2,0,4,5,5,3,3,4,3,3,1,5,4,4,2,4,4,4,3,4,2,4,3,5,5,4,3,3,4,3,3,5,5,4,5,5,1,3,4,5,3,1,4,3,1,3,3,0,3,3,1,4,3,1,4,5,3,3,5,0,4,0,3,0,5,3,3,1,4,3,0,4,0,1,5,3),
-(0,5,0,5,0,4,0,2,0,4,4,3,4,3,3,3,3,3,5,4,4,4,4,4,4,5,3,3,5,2,4,4,4,3,4,4,3,3,4,4,5,5,3,3,4,3,4,3,3,4,3,3,3,3,1,2,2,1,4,3,3,5,4,4,3,4,0,4,0,3,0,4,4,4,4,4,1,0,4,2,0,2,4),
-(0,4,0,4,0,3,0,1,0,3,5,2,3,0,3,0,2,1,4,2,3,3,4,1,4,3,3,2,4,1,3,3,3,0,3,3,0,0,3,3,3,5,3,3,3,3,3,2,0,2,0,0,2,0,0,2,0,0,1,0,0,3,1,2,2,3,0,3,0,2,0,4,4,3,3,4,1,0,3,0,0,2,4),
-(0,0,0,4,0,0,0,0,0,0,1,0,1,0,2,0,0,0,0,0,1,0,2,0,1,0,0,0,0,0,3,1,3,0,3,2,0,0,0,1,0,3,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,4,0,2,0,0,0,0,0,0,2),
-(0,2,1,3,0,2,0,2,0,3,3,3,3,1,3,1,3,3,3,3,3,3,4,2,2,1,2,1,4,0,4,3,1,3,3,3,2,4,3,5,4,3,3,3,3,3,3,3,0,1,3,0,2,0,0,1,0,0,1,0,0,4,2,0,2,3,0,3,3,0,3,3,4,2,3,1,4,0,1,2,0,2,3),
-(0,3,0,3,0,1,0,3,0,2,3,3,3,0,3,1,2,0,3,3,2,3,3,2,3,2,3,1,3,0,4,3,2,0,3,3,1,4,3,3,2,3,4,3,1,3,3,1,1,0,1,1,0,1,0,1,0,1,0,0,0,4,1,1,0,3,0,3,1,0,2,3,3,3,3,3,1,0,0,2,0,3,3),
-(0,0,0,0,0,0,0,0,0,0,3,0,2,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,3,0,3,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,2,0,2,3,0,0,0,0,0,0,0,0,3),
-(0,2,0,3,1,3,0,3,0,2,3,3,3,1,3,1,3,1,3,1,3,3,3,1,3,0,2,3,1,1,4,3,3,2,3,3,1,2,2,4,1,3,3,0,1,4,2,3,0,1,3,0,3,0,0,1,3,0,2,0,0,3,3,2,1,3,0,3,0,2,0,3,4,4,4,3,1,0,3,0,0,3,3),
-(0,2,0,1,0,2,0,0,0,1,3,2,2,1,3,0,1,1,3,0,3,2,3,1,2,0,2,0,1,1,3,3,3,0,3,3,1,1,2,3,2,3,3,1,2,3,2,0,0,1,0,0,0,0,0,0,3,0,1,0,0,2,1,2,1,3,0,3,0,0,0,3,4,4,4,3,2,0,2,0,0,2,4),
-(0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,3,1,0,0,0,0,0,0,0,3),
-(0,3,0,3,0,2,0,3,0,3,3,3,2,3,2,2,2,0,3,1,3,3,3,2,3,3,0,0,3,0,3,2,2,0,2,3,1,4,3,4,3,3,2,3,1,5,4,4,0,3,1,2,1,3,0,3,1,1,2,0,2,3,1,3,1,3,0,3,0,1,0,3,3,4,4,2,1,0,2,1,0,2,4),
-(0,1,0,3,0,1,0,2,0,1,4,2,5,1,4,0,2,0,2,1,3,1,4,0,2,1,0,0,2,1,4,1,1,0,3,3,0,5,1,3,2,3,3,1,0,3,2,3,0,1,0,0,0,0,0,0,1,0,0,0,0,4,0,1,0,3,0,2,0,1,0,3,3,3,4,3,3,0,0,0,0,2,3),
-(0,0,0,1,0,0,0,0,0,0,2,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,1,0,0,1,0,0,0,0,0,3),
-(0,1,0,3,0,4,0,3,0,2,4,3,1,0,3,2,2,1,3,1,2,2,3,1,1,1,2,1,3,0,1,2,0,1,3,2,1,3,0,5,5,1,0,0,1,3,2,1,0,3,0,0,1,0,0,0,0,0,3,4,0,1,1,1,3,2,0,2,0,1,0,2,3,3,1,2,3,0,1,0,1,0,4),
-(0,0,0,1,0,3,0,3,0,2,2,1,0,0,4,0,3,0,3,1,3,0,3,0,3,0,1,0,3,0,3,1,3,0,3,3,0,0,1,2,1,1,1,0,1,2,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,2,2,1,2,0,0,2,0,0,0,0,2,3,3,3,3,0,0,0,0,1,4),
-(0,0,0,3,0,3,0,0,0,0,3,1,1,0,3,0,1,0,2,0,1,0,0,0,0,0,0,0,1,0,3,0,2,0,2,3,0,0,2,2,3,1,2,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,2,0,0,0,0,2,3),
-(2,4,0,5,0,5,0,4,0,3,4,3,3,3,4,3,3,3,4,3,4,4,5,4,5,5,5,2,3,0,5,5,4,1,5,4,3,1,5,4,3,4,4,3,3,4,3,3,0,3,2,0,2,3,0,3,0,0,3,3,0,5,3,2,3,3,0,3,0,3,0,3,4,5,4,5,3,0,4,3,0,3,4),
-(0,3,0,3,0,3,0,3,0,3,3,4,3,2,3,2,3,0,4,3,3,3,3,3,3,3,3,0,3,2,4,3,3,1,3,4,3,4,4,4,3,4,4,3,2,4,4,1,0,2,0,0,1,1,0,2,0,0,3,1,0,5,3,2,1,3,0,3,0,1,2,4,3,2,4,3,3,0,3,2,0,4,4),
-(0,3,0,3,0,1,0,0,0,1,4,3,3,2,3,1,3,1,4,2,3,2,4,2,3,4,3,0,2,2,3,3,3,0,3,3,3,0,3,4,1,3,3,0,3,4,3,3,0,1,1,0,1,0,0,0,4,0,3,0,0,3,1,2,1,3,0,4,0,1,0,4,3,3,4,3,3,0,2,0,0,3,3),
-(0,3,0,4,0,1,0,3,0,3,4,3,3,0,3,3,3,1,3,1,3,3,4,3,3,3,0,0,3,1,5,3,3,1,3,3,2,5,4,3,3,4,5,3,2,5,3,4,0,1,0,0,0,0,0,2,0,0,1,1,0,4,2,2,1,3,0,3,0,2,0,4,4,3,5,3,2,0,1,1,0,3,4),
-(0,5,0,4,0,5,0,2,0,4,4,3,3,2,3,3,3,1,4,3,4,1,5,3,4,3,4,0,4,2,4,3,4,1,5,4,0,4,4,4,4,5,4,1,3,5,4,2,1,4,1,1,3,2,0,3,1,0,3,2,1,4,3,3,3,4,0,4,0,3,0,4,4,4,3,3,3,0,4,2,0,3,4),
-(1,4,0,4,0,3,0,1,0,3,3,3,1,1,3,3,2,2,3,3,1,0,3,2,2,1,2,0,3,1,2,1,2,0,3,2,0,2,2,3,3,4,3,0,3,3,1,2,0,1,1,3,1,2,0,0,3,0,1,1,0,3,2,2,3,3,0,3,0,0,0,2,3,3,4,3,3,0,1,0,0,1,4),
-(0,4,0,4,0,4,0,0,0,3,4,4,3,1,4,2,3,2,3,3,3,1,4,3,4,0,3,0,4,2,3,3,2,2,5,4,2,1,3,4,3,4,3,1,3,3,4,2,0,2,1,0,3,3,0,0,2,0,3,1,0,4,4,3,4,3,0,4,0,1,0,2,4,4,4,4,4,0,3,2,0,3,3),
-(0,0,0,1,0,4,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,3,2,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,2),
-(0,2,0,3,0,4,0,4,0,1,3,3,3,0,4,0,2,1,2,1,1,1,2,0,3,1,1,0,1,0,3,1,0,0,3,3,2,0,1,1,0,0,0,0,0,1,0,2,0,2,2,0,3,1,0,0,1,0,1,1,0,1,2,0,3,0,0,0,0,1,0,0,3,3,4,3,1,0,1,0,3,0,2),
-(0,0,0,3,0,5,0,0,0,0,1,0,2,0,3,1,0,1,3,0,0,0,2,0,0,0,1,0,0,0,1,1,0,0,4,0,0,0,2,3,0,1,4,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,3,0,0,0,0,0,3),
-(0,2,0,5,0,5,0,1,0,2,4,3,3,2,5,1,3,2,3,3,3,0,4,1,2,0,3,0,4,0,2,2,1,1,5,3,0,0,1,4,2,3,2,0,3,3,3,2,0,2,4,1,1,2,0,1,1,0,3,1,0,1,3,1,2,3,0,2,0,0,0,1,3,5,4,4,4,0,3,0,0,1,3),
-(0,4,0,5,0,4,0,4,0,4,5,4,3,3,4,3,3,3,4,3,4,4,5,3,4,5,4,2,4,2,3,4,3,1,4,4,1,3,5,4,4,5,5,4,4,5,5,5,2,3,3,1,4,3,1,3,3,0,3,3,1,4,3,4,4,4,0,3,0,4,0,3,3,4,4,5,0,0,4,3,0,4,5),
-(0,4,0,4,0,3,0,3,0,3,4,4,4,3,3,2,4,3,4,3,4,3,5,3,4,3,2,1,4,2,4,4,3,1,3,4,2,4,5,5,3,4,5,4,1,5,4,3,0,3,2,2,3,2,1,3,1,0,3,3,3,5,3,3,3,5,4,4,2,3,3,4,3,3,3,2,1,0,3,2,1,4,3),
-(0,4,0,5,0,4,0,3,0,3,5,5,3,2,4,3,4,0,5,4,4,1,4,4,4,3,3,3,4,3,5,5,2,3,3,4,1,2,5,5,3,5,5,2,3,5,5,4,0,3,2,0,3,3,1,1,5,1,4,1,0,4,3,2,3,5,0,4,0,3,0,5,4,3,4,3,0,0,4,1,0,4,4),
-(1,3,0,4,0,2,0,2,0,2,5,5,3,3,3,3,3,0,4,2,3,4,4,4,3,4,0,0,3,4,5,4,3,3,3,3,2,5,5,4,5,5,5,4,3,5,5,5,1,3,1,0,1,0,0,3,2,0,4,2,0,5,2,3,2,4,1,3,0,3,0,4,5,4,5,4,3,0,4,2,0,5,4),
-(0,3,0,4,0,5,0,3,0,3,4,4,3,2,3,2,3,3,3,3,3,2,4,3,3,2,2,0,3,3,3,3,3,1,3,3,3,0,4,4,3,4,4,1,1,4,4,2,0,3,1,0,1,1,0,4,1,0,2,3,1,3,3,1,3,4,0,3,0,1,0,3,1,3,0,0,1,0,2,0,0,4,4),
-(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),
-(0,3,0,3,0,2,0,3,0,1,5,4,3,3,3,1,4,2,1,2,3,4,4,2,4,4,5,0,3,1,4,3,4,0,4,3,3,3,2,3,2,5,3,4,3,2,2,3,0,0,3,0,2,1,0,1,2,0,0,0,0,2,1,1,3,1,0,2,0,4,0,3,4,4,4,5,2,0,2,0,0,1,3),
-(0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,1,0,0,1,1,0,0,0,4,2,1,1,0,1,0,3,2,0,0,3,1,1,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,1,0,0,0,2,0,0,0,1,4,0,4,2,1,0,0,0,0,0,1),
-(0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,3,1,0,0,0,2,0,2,1,0,0,1,2,1,0,1,1,0,0,3,0,0,0,0,0,0,0,0,0,0,0,1,3,1,0,0,0,0,0,1,0,0,2,1,0,0,0,0,0,0,0,0,2),
-(0,4,0,4,0,4,0,3,0,4,4,3,4,2,4,3,2,0,4,4,4,3,5,3,5,3,3,2,4,2,4,3,4,3,1,4,0,2,3,4,4,4,3,3,3,4,4,4,3,4,1,3,4,3,2,1,2,1,3,3,3,4,4,3,3,5,0,4,0,3,0,4,3,3,3,2,1,0,3,0,0,3,3),
-(0,4,0,3,0,3,0,3,0,3,5,5,3,3,3,3,4,3,4,3,3,3,4,4,4,3,3,3,3,4,3,5,3,3,1,3,2,4,5,5,5,5,4,3,4,5,5,3,2,2,3,3,3,3,2,3,3,1,2,3,2,4,3,3,3,4,0,4,0,2,0,4,3,2,2,1,2,0,3,0,0,4,1),
-)
-
-class JapaneseContextAnalysis:
- def __init__(self):
- self.reset()
-
- def reset(self):
- self._mTotalRel = 0 # total sequence received
- # category counters, each interger counts sequence in its category
- self._mRelSample = [0] * NUM_OF_CATEGORY
- # if last byte in current buffer is not the last byte of a character,
- # we need to know how many bytes to skip in next buffer
- self._mNeedToSkipCharNum = 0
- self._mLastCharOrder = -1 # The order of previous char
- # If this flag is set to True, detection is done and conclusion has
- # been made
- self._mDone = False
-
- def feed(self, aBuf, aLen):
- if self._mDone:
- return
-
- # The buffer we got is byte oriented, and a character may span in more than one
- # buffers. In case the last one or two byte in last buffer is not
- # complete, we record how many byte needed to complete that character
- # and skip these bytes here. We can choose to record those bytes as
- # well and analyse the character once it is complete, but since a
- # character will not make much difference, by simply skipping
- # this character will simply our logic and improve performance.
- i = self._mNeedToSkipCharNum
- while i < aLen:
- order, charLen = self.get_order(aBuf[i:i + 2])
- i += charLen
- if i > aLen:
- self._mNeedToSkipCharNum = i - aLen
- self._mLastCharOrder = -1
- else:
- if (order != -1) and (self._mLastCharOrder != -1):
- self._mTotalRel += 1
- if self._mTotalRel > MAX_REL_THRESHOLD:
- self._mDone = True
- break
- self._mRelSample[jp2CharContext[self._mLastCharOrder][order]] += 1
- self._mLastCharOrder = order
-
- def got_enough_data(self):
- return self._mTotalRel > ENOUGH_REL_THRESHOLD
-
- def get_confidence(self):
- # This is just one way to calculate confidence. It works well for me.
- if self._mTotalRel > MINIMUM_DATA_THRESHOLD:
- return float(self._mTotalRel - self._mRelSample[0]) / self._mTotalRel
- else:
- return DONT_KNOW
-
- def get_order(self, aBuf):
- return -1, 1
-
-class SJISContextAnalysis(JapaneseContextAnalysis):
- def get_order(self, aBuf):
- if not aBuf:
- return -1, 1
- # find out current char's byte length
- first_char = wrap_ord(aBuf[0])
- if ((0x81 <= first_char <= 0x9F) or (0xE0 <= first_char <= 0xFC)):
- charLen = 2
- else:
- charLen = 1
-
- # return its order if it is hiragana
- if len(aBuf) > 1:
- second_char = wrap_ord(aBuf[1])
- if (first_char == 202) and (0x9F <= second_char <= 0xF1):
- return second_char - 0x9F, charLen
-
- return -1, charLen
-
-class EUCJPContextAnalysis(JapaneseContextAnalysis):
- def get_order(self, aBuf):
- if not aBuf:
- return -1, 1
- # find out current char's byte length
- first_char = wrap_ord(aBuf[0])
- if (first_char == 0x8E) or (0xA1 <= first_char <= 0xFE):
- charLen = 2
- elif first_char == 0x8F:
- charLen = 3
- else:
- charLen = 1
-
- # return its order if it is hiragana
- if len(aBuf) > 1:
- second_char = wrap_ord(aBuf[1])
- if (first_char == 0xA4) and (0xA1 <= second_char <= 0xF3):
- return second_char - 0xA1, charLen
-
- return -1, charLen
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/latin1prober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/latin1prober.py
deleted file mode 100644
index 5e2c9f9..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/latin1prober.py
+++ /dev/null
@@ -1,139 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Universal charset detector code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-# Shy Shalom - original C code
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .charsetprober import CharSetProber
-from .constants import eNotMe
-from .compat import wrap_ord
-
-FREQ_CAT_NUM = 4
-
-UDF = 0 # undefined
-OTH = 1 # other
-ASC = 2 # ascii capital letter
-ASS = 3 # ascii small letter
-ACV = 4 # accent capital vowel
-ACO = 5 # accent capital other
-ASV = 6 # accent small vowel
-ASO = 7 # accent small other
-CLASS_NUM = 8 # total classes
-
-Latin1_CharToClass = (
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 00 - 07
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 08 - 0F
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 10 - 17
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 18 - 1F
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 20 - 27
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 28 - 2F
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 30 - 37
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 38 - 3F
- OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 40 - 47
- ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 48 - 4F
- ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 50 - 57
- ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, # 58 - 5F
- OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 60 - 67
- ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 68 - 6F
- ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 70 - 77
- ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, # 78 - 7F
- OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, # 80 - 87
- OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, # 88 - 8F
- UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 90 - 97
- OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, # 98 - 9F
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A0 - A7
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A8 - AF
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B0 - B7
- OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B8 - BF
- ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, # C0 - C7
- ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, # C8 - CF
- ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, # D0 - D7
- ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, # D8 - DF
- ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, # E0 - E7
- ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, # E8 - EF
- ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, # F0 - F7
- ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, # F8 - FF
-)
-
-# 0 : illegal
-# 1 : very unlikely
-# 2 : normal
-# 3 : very likely
-Latin1ClassModel = (
- # UDF OTH ASC ASS ACV ACO ASV ASO
- 0, 0, 0, 0, 0, 0, 0, 0, # UDF
- 0, 3, 3, 3, 3, 3, 3, 3, # OTH
- 0, 3, 3, 3, 3, 3, 3, 3, # ASC
- 0, 3, 3, 3, 1, 1, 3, 3, # ASS
- 0, 3, 3, 3, 1, 2, 1, 2, # ACV
- 0, 3, 3, 3, 3, 3, 3, 3, # ACO
- 0, 3, 1, 3, 1, 1, 1, 3, # ASV
- 0, 3, 1, 3, 1, 1, 3, 3, # ASO
-)
-
-
-class Latin1Prober(CharSetProber):
- def __init__(self):
- CharSetProber.__init__(self)
- self.reset()
-
- def reset(self):
- self._mLastCharClass = OTH
- self._mFreqCounter = [0] * FREQ_CAT_NUM
- CharSetProber.reset(self)
-
- def get_charset_name(self):
- return "windows-1252"
-
- def feed(self, aBuf):
- aBuf = self.filter_with_english_letters(aBuf)
- for c in aBuf:
- charClass = Latin1_CharToClass[wrap_ord(c)]
- freq = Latin1ClassModel[(self._mLastCharClass * CLASS_NUM)
- + charClass]
- if freq == 0:
- self._mState = eNotMe
- break
- self._mFreqCounter[freq] += 1
- self._mLastCharClass = charClass
-
- return self.get_state()
-
- def get_confidence(self):
- if self.get_state() == eNotMe:
- return 0.01
-
- total = sum(self._mFreqCounter)
- if total < 0.01:
- confidence = 0.0
- else:
- confidence = ((float(self._mFreqCounter[3]) / total)
- - (self._mFreqCounter[1] * 20.0 / total))
- if confidence < 0.0:
- confidence = 0.0
- # lower the confidence of latin1 so that other more accurate
- # detector can take priority.
- confidence = confidence * 0.5
- return confidence
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/universaldetector.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/universaldetector.py
deleted file mode 100644
index 7ccea84..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/universaldetector.py
+++ /dev/null
@@ -1,168 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Universal charset detector code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-# Shy Shalom - original C code
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from . import constants
-import sys
-import codecs
-from .latin1prober import Latin1Prober # windows-1252
-from .mbcsgroupprober import MBCSGroupProber # multi-byte character sets
-from .sbcsgroupprober import SBCSGroupProber # single-byte character sets
-from .escprober import EscCharSetProber # ISO-2122, etc.
-import re
-
-MINIMUM_THRESHOLD = 0.20
-ePureAscii = 0
-eEscAscii = 1
-eHighbyte = 2
-
-
-class UniversalDetector:
- def __init__(self):
- self._highBitDetector = re.compile(b'[\x80-\xFF]')
- self._escDetector = re.compile(b'(\033|~{)')
- self._mEscCharSetProber = None
- self._mCharSetProbers = []
- self.reset()
-
- def reset(self):
- self.result = {'encoding': None, 'confidence': 0.0}
- self.done = False
- self._mStart = True
- self._mGotData = False
- self._mInputState = ePureAscii
- self._mLastChar = b''
- if self._mEscCharSetProber:
- self._mEscCharSetProber.reset()
- for prober in self._mCharSetProbers:
- prober.reset()
-
- def feed(self, aBuf):
- if self.done:
- return
-
- aLen = len(aBuf)
- if not aLen:
- return
-
- if not self._mGotData:
- # If the data starts with BOM, we know it is UTF
- if aBuf[:3] == codecs.BOM:
- # EF BB BF UTF-8 with BOM
- self.result = {'encoding': "UTF-8", 'confidence': 1.0}
- elif aBuf[:4] in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
- # FF FE 00 00 UTF-32, little-endian BOM
- # 00 00 FE FF UTF-32, big-endian BOM
- self.result = {'encoding': "UTF-32", 'confidence': 1.0}
- elif aBuf[:4] == b'\xFE\xFF\x00\x00':
- # FE FF 00 00 UCS-4, unusual octet order BOM (3412)
- self.result = {
- 'encoding': "X-ISO-10646-UCS-4-3412",
- 'confidence': 1.0
- }
- elif aBuf[:4] == b'\x00\x00\xFF\xFE':
- # 00 00 FF FE UCS-4, unusual octet order BOM (2143)
- self.result = {
- 'encoding': "X-ISO-10646-UCS-4-2143",
- 'confidence': 1.0
- }
- elif aBuf[:2] == codecs.BOM_LE or aBuf[:2] == codecs.BOM_BE:
- # FF FE UTF-16, little endian BOM
- # FE FF UTF-16, big endian BOM
- self.result = {'encoding': "UTF-16", 'confidence': 1.0}
-
- self._mGotData = True
- if self.result['encoding'] and (self.result['confidence'] > 0.0):
- self.done = True
- return
-
- if self._mInputState == ePureAscii:
- if self._highBitDetector.search(aBuf):
- self._mInputState = eHighbyte
- elif ((self._mInputState == ePureAscii) and
- self._escDetector.search(self._mLastChar + aBuf)):
- self._mInputState = eEscAscii
-
- self._mLastChar = aBuf[-1:]
-
- if self._mInputState == eEscAscii:
- if not self._mEscCharSetProber:
- self._mEscCharSetProber = EscCharSetProber()
- if self._mEscCharSetProber.feed(aBuf) == constants.eFoundIt:
- self.result = {
- 'encoding': self._mEscCharSetProber.get_charset_name(),
- 'confidence': self._mEscCharSetProber.get_confidence()
- }
- self.done = True
- elif self._mInputState == eHighbyte:
- if not self._mCharSetProbers:
- self._mCharSetProbers = [MBCSGroupProber(), SBCSGroupProber(),
- Latin1Prober()]
- for prober in self._mCharSetProbers:
- if prober.feed(aBuf) == constants.eFoundIt:
- self.result = {'encoding': prober.get_charset_name(),
- 'confidence': prober.get_confidence()}
- self.done = True
- break
-
- def close(self):
- if self.done:
- return
- if not self._mGotData:
- if constants._debug:
- sys.stderr.write('no data received!\n')
- return
- self.done = True
-
- if self._mInputState == ePureAscii:
- self.result = {'encoding': 'ascii', 'confidence': 1.0}
- return self.result
-
- if self._mInputState == eHighbyte:
- proberConfidence = None
- maxProberConfidence = 0.0
- maxProber = None
- for prober in self._mCharSetProbers:
- if not prober:
- continue
- proberConfidence = prober.get_confidence()
- if proberConfidence > maxProberConfidence:
- maxProberConfidence = proberConfidence
- maxProber = prober
- if maxProber and (maxProberConfidence > MINIMUM_THRESHOLD):
- self.result = {'encoding': maxProber.get_charset_name(),
- 'confidence': maxProber.get_confidence()}
- return self.result
-
- if constants._debug:
- sys.stderr.write('no probers hit minimum threshhold\n')
- for prober in self._mCharSetProbers[0].mProbers:
- if not prober:
- continue
- sys.stderr.write('%s confidence = %s\n' %
- (prober.get_charset_name(),
- prober.get_confidence()))
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/big5freq.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/big5freq.py
deleted file mode 100644
index 65bffc0..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/big5freq.py
+++ /dev/null
@@ -1,925 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# Big5 frequency table
-# by Taiwan's Mandarin Promotion Council
-#
-#
-# 128 --> 0.42261
-# 256 --> 0.57851
-# 512 --> 0.74851
-# 1024 --> 0.89384
-# 2048 --> 0.97583
-#
-# Ideal Distribution Ratio = 0.74851/(1-0.74851) =2.98
-# Random Distribution Ration = 512/(5401-512)=0.105
-#
-# Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR
-
-BIG5_TYPICAL_DISTRIBUTION_RATIO = 0.75
-
-#Char to FreqOrder table
-BIG5_TABLE_SIZE = 5376
-
-Big5CharToFreqOrder = (
- 1,1801,1506, 255,1431, 198, 9, 82, 6,5008, 177, 202,3681,1256,2821, 110, # 16
-3814, 33,3274, 261, 76, 44,2114, 16,2946,2187,1176, 659,3971, 26,3451,2653, # 32
-1198,3972,3350,4202, 410,2215, 302, 590, 361,1964, 8, 204, 58,4510,5009,1932, # 48
- 63,5010,5011, 317,1614, 75, 222, 159,4203,2417,1480,5012,3555,3091, 224,2822, # 64
-3682, 3, 10,3973,1471, 29,2787,1135,2866,1940, 873, 130,3275,1123, 312,5013, # 80
-4511,2052, 507, 252, 682,5014, 142,1915, 124, 206,2947, 34,3556,3204, 64, 604, # 96
-5015,2501,1977,1978, 155,1991, 645, 641,1606,5016,3452, 337, 72, 406,5017, 80, # 112
- 630, 238,3205,1509, 263, 939,1092,2654, 756,1440,1094,3453, 449, 69,2987, 591, # 128
- 179,2096, 471, 115,2035,1844, 60, 50,2988, 134, 806,1869, 734,2036,3454, 180, # 144
- 995,1607, 156, 537,2907, 688,5018, 319,1305, 779,2145, 514,2379, 298,4512, 359, # 160
-2502, 90,2716,1338, 663, 11, 906,1099,2553, 20,2441, 182, 532,1716,5019, 732, # 176
-1376,4204,1311,1420,3206, 25,2317,1056, 113, 399, 382,1950, 242,3455,2474, 529, # 192
-3276, 475,1447,3683,5020, 117, 21, 656, 810,1297,2300,2334,3557,5021, 126,4205, # 208
- 706, 456, 150, 613,4513, 71,1118,2037,4206, 145,3092, 85, 835, 486,2115,1246, # 224
-1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,5022,2128,2359, 347,3815, 221, # 240
-3558,3135,5023,1956,1153,4207, 83, 296,1199,3093, 192, 624, 93,5024, 822,1898, # 256
-2823,3136, 795,2065, 991,1554,1542,1592, 27, 43,2867, 859, 139,1456, 860,4514, # 272
- 437, 712,3974, 164,2397,3137, 695, 211,3037,2097, 195,3975,1608,3559,3560,3684, # 288
-3976, 234, 811,2989,2098,3977,2233,1441,3561,1615,2380, 668,2077,1638, 305, 228, # 304
-1664,4515, 467, 415,5025, 262,2099,1593, 239, 108, 300, 200,1033, 512,1247,2078, # 320
-5026,5027,2176,3207,3685,2682, 593, 845,1062,3277, 88,1723,2038,3978,1951, 212, # 336
- 266, 152, 149, 468,1899,4208,4516, 77, 187,5028,3038, 37, 5,2990,5029,3979, # 352
-5030,5031, 39,2524,4517,2908,3208,2079, 55, 148, 74,4518, 545, 483,1474,1029, # 368
-1665, 217,1870,1531,3138,1104,2655,4209, 24, 172,3562, 900,3980,3563,3564,4519, # 384
- 32,1408,2824,1312, 329, 487,2360,2251,2717, 784,2683, 4,3039,3351,1427,1789, # 400
- 188, 109, 499,5032,3686,1717,1790, 888,1217,3040,4520,5033,3565,5034,3352,1520, # 416
-3687,3981, 196,1034, 775,5035,5036, 929,1816, 249, 439, 38,5037,1063,5038, 794, # 432
-3982,1435,2301, 46, 178,3278,2066,5039,2381,5040, 214,1709,4521, 804, 35, 707, # 448
- 324,3688,1601,2554, 140, 459,4210,5041,5042,1365, 839, 272, 978,2262,2580,3456, # 464
-2129,1363,3689,1423, 697, 100,3094, 48, 70,1231, 495,3139,2196,5043,1294,5044, # 480
-2080, 462, 586,1042,3279, 853, 256, 988, 185,2382,3457,1698, 434,1084,5045,3458, # 496
- 314,2625,2788,4522,2335,2336, 569,2285, 637,1817,2525, 757,1162,1879,1616,3459, # 512
- 287,1577,2116, 768,4523,1671,2868,3566,2526,1321,3816, 909,2418,5046,4211, 933, # 528
-3817,4212,2053,2361,1222,4524, 765,2419,1322, 786,4525,5047,1920,1462,1677,2909, # 544
-1699,5048,4526,1424,2442,3140,3690,2600,3353,1775,1941,3460,3983,4213, 309,1369, # 560
-1130,2825, 364,2234,1653,1299,3984,3567,3985,3986,2656, 525,1085,3041, 902,2001, # 576
-1475, 964,4527, 421,1845,1415,1057,2286, 940,1364,3141, 376,4528,4529,1381, 7, # 592
-2527, 983,2383, 336,1710,2684,1846, 321,3461, 559,1131,3042,2752,1809,1132,1313, # 608
- 265,1481,1858,5049, 352,1203,2826,3280, 167,1089, 420,2827, 776, 792,1724,3568, # 624
-4214,2443,3281,5050,4215,5051, 446, 229, 333,2753, 901,3818,1200,1557,4530,2657, # 640
-1921, 395,2754,2685,3819,4216,1836, 125, 916,3209,2626,4531,5052,5053,3820,5054, # 656
-5055,5056,4532,3142,3691,1133,2555,1757,3462,1510,2318,1409,3569,5057,2146, 438, # 672
-2601,2910,2384,3354,1068, 958,3043, 461, 311,2869,2686,4217,1916,3210,4218,1979, # 688
- 383, 750,2755,2627,4219, 274, 539, 385,1278,1442,5058,1154,1965, 384, 561, 210, # 704
- 98,1295,2556,3570,5059,1711,2420,1482,3463,3987,2911,1257, 129,5060,3821, 642, # 720
- 523,2789,2790,2658,5061, 141,2235,1333, 68, 176, 441, 876, 907,4220, 603,2602, # 736
- 710, 171,3464, 404, 549, 18,3143,2398,1410,3692,1666,5062,3571,4533,2912,4534, # 752
-5063,2991, 368,5064, 146, 366, 99, 871,3693,1543, 748, 807,1586,1185, 22,2263, # 768
- 379,3822,3211,5065,3212, 505,1942,2628,1992,1382,2319,5066, 380,2362, 218, 702, # 784
-1818,1248,3465,3044,3572,3355,3282,5067,2992,3694, 930,3283,3823,5068, 59,5069, # 800
- 585, 601,4221, 497,3466,1112,1314,4535,1802,5070,1223,1472,2177,5071, 749,1837, # 816
- 690,1900,3824,1773,3988,1476, 429,1043,1791,2236,2117, 917,4222, 447,1086,1629, # 832
-5072, 556,5073,5074,2021,1654, 844,1090, 105, 550, 966,1758,2828,1008,1783, 686, # 848
-1095,5075,2287, 793,1602,5076,3573,2603,4536,4223,2948,2302,4537,3825, 980,2503, # 864
- 544, 353, 527,4538, 908,2687,2913,5077, 381,2629,1943,1348,5078,1341,1252, 560, # 880
-3095,5079,3467,2870,5080,2054, 973, 886,2081, 143,4539,5081,5082, 157,3989, 496, # 896
-4224, 57, 840, 540,2039,4540,4541,3468,2118,1445, 970,2264,1748,1966,2082,4225, # 912
-3144,1234,1776,3284,2829,3695, 773,1206,2130,1066,2040,1326,3990,1738,1725,4226, # 928
- 279,3145, 51,1544,2604, 423,1578,2131,2067, 173,4542,1880,5083,5084,1583, 264, # 944
- 610,3696,4543,2444, 280, 154,5085,5086,5087,1739, 338,1282,3096, 693,2871,1411, # 960
-1074,3826,2445,5088,4544,5089,5090,1240, 952,2399,5091,2914,1538,2688, 685,1483, # 976
-4227,2475,1436, 953,4228,2055,4545, 671,2400, 79,4229,2446,3285, 608, 567,2689, # 992
-3469,4230,4231,1691, 393,1261,1792,2401,5092,4546,5093,5094,5095,5096,1383,1672, # 1008
-3827,3213,1464, 522,1119, 661,1150, 216, 675,4547,3991,1432,3574, 609,4548,2690, # 1024
-2402,5097,5098,5099,4232,3045, 0,5100,2476, 315, 231,2447, 301,3356,4549,2385, # 1040
-5101, 233,4233,3697,1819,4550,4551,5102, 96,1777,1315,2083,5103, 257,5104,1810, # 1056
-3698,2718,1139,1820,4234,2022,1124,2164,2791,1778,2659,5105,3097, 363,1655,3214, # 1072
-5106,2993,5107,5108,5109,3992,1567,3993, 718, 103,3215, 849,1443, 341,3357,2949, # 1088
-1484,5110,1712, 127, 67, 339,4235,2403, 679,1412, 821,5111,5112, 834, 738, 351, # 1104
-2994,2147, 846, 235,1497,1881, 418,1993,3828,2719, 186,1100,2148,2756,3575,1545, # 1120
-1355,2950,2872,1377, 583,3994,4236,2581,2995,5113,1298,3699,1078,2557,3700,2363, # 1136
- 78,3829,3830, 267,1289,2100,2002,1594,4237, 348, 369,1274,2197,2178,1838,4552, # 1152
-1821,2830,3701,2757,2288,2003,4553,2951,2758, 144,3358, 882,4554,3995,2759,3470, # 1168
-4555,2915,5114,4238,1726, 320,5115,3996,3046, 788,2996,5116,2831,1774,1327,2873, # 1184
-3997,2832,5117,1306,4556,2004,1700,3831,3576,2364,2660, 787,2023, 506, 824,3702, # 1200
- 534, 323,4557,1044,3359,2024,1901, 946,3471,5118,1779,1500,1678,5119,1882,4558, # 1216
- 165, 243,4559,3703,2528, 123, 683,4239, 764,4560, 36,3998,1793, 589,2916, 816, # 1232
- 626,1667,3047,2237,1639,1555,1622,3832,3999,5120,4000,2874,1370,1228,1933, 891, # 1248
-2084,2917, 304,4240,5121, 292,2997,2720,3577, 691,2101,4241,1115,4561, 118, 662, # 1264
-5122, 611,1156, 854,2386,1316,2875, 2, 386, 515,2918,5123,5124,3286, 868,2238, # 1280
-1486, 855,2661, 785,2216,3048,5125,1040,3216,3578,5126,3146, 448,5127,1525,5128, # 1296
-2165,4562,5129,3833,5130,4242,2833,3579,3147, 503, 818,4001,3148,1568, 814, 676, # 1312
-1444, 306,1749,5131,3834,1416,1030, 197,1428, 805,2834,1501,4563,5132,5133,5134, # 1328
-1994,5135,4564,5136,5137,2198, 13,2792,3704,2998,3149,1229,1917,5138,3835,2132, # 1344
-5139,4243,4565,2404,3580,5140,2217,1511,1727,1120,5141,5142, 646,3836,2448, 307, # 1360
-5143,5144,1595,3217,5145,5146,5147,3705,1113,1356,4002,1465,2529,2530,5148, 519, # 1376
-5149, 128,2133, 92,2289,1980,5150,4003,1512, 342,3150,2199,5151,2793,2218,1981, # 1392
-3360,4244, 290,1656,1317, 789, 827,2365,5152,3837,4566, 562, 581,4004,5153, 401, # 1408
-4567,2252, 94,4568,5154,1399,2794,5155,1463,2025,4569,3218,1944,5156, 828,1105, # 1424
-4245,1262,1394,5157,4246, 605,4570,5158,1784,2876,5159,2835, 819,2102, 578,2200, # 1440
-2952,5160,1502, 436,3287,4247,3288,2836,4005,2919,3472,3473,5161,2721,2320,5162, # 1456
-5163,2337,2068, 23,4571, 193, 826,3838,2103, 699,1630,4248,3098, 390,1794,1064, # 1472
-3581,5164,1579,3099,3100,1400,5165,4249,1839,1640,2877,5166,4572,4573, 137,4250, # 1488
- 598,3101,1967, 780, 104, 974,2953,5167, 278, 899, 253, 402, 572, 504, 493,1339, # 1504
-5168,4006,1275,4574,2582,2558,5169,3706,3049,3102,2253, 565,1334,2722, 863, 41, # 1520
-5170,5171,4575,5172,1657,2338, 19, 463,2760,4251, 606,5173,2999,3289,1087,2085, # 1536
-1323,2662,3000,5174,1631,1623,1750,4252,2691,5175,2878, 791,2723,2663,2339, 232, # 1552
-2421,5176,3001,1498,5177,2664,2630, 755,1366,3707,3290,3151,2026,1609, 119,1918, # 1568
-3474, 862,1026,4253,5178,4007,3839,4576,4008,4577,2265,1952,2477,5179,1125, 817, # 1584
-4254,4255,4009,1513,1766,2041,1487,4256,3050,3291,2837,3840,3152,5180,5181,1507, # 1600
-5182,2692, 733, 40,1632,1106,2879, 345,4257, 841,2531, 230,4578,3002,1847,3292, # 1616
-3475,5183,1263, 986,3476,5184, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562, # 1632
-4010,4011,2954, 967,2761,2665,1349, 592,2134,1692,3361,3003,1995,4258,1679,4012, # 1648
-1902,2188,5185, 739,3708,2724,1296,1290,5186,4259,2201,2202,1922,1563,2605,2559, # 1664
-1871,2762,3004,5187, 435,5188, 343,1108, 596, 17,1751,4579,2239,3477,3709,5189, # 1680
-4580, 294,3582,2955,1693, 477, 979, 281,2042,3583, 643,2043,3710,2631,2795,2266, # 1696
-1031,2340,2135,2303,3584,4581, 367,1249,2560,5190,3585,5191,4582,1283,3362,2005, # 1712
- 240,1762,3363,4583,4584, 836,1069,3153, 474,5192,2149,2532, 268,3586,5193,3219, # 1728
-1521,1284,5194,1658,1546,4260,5195,3587,3588,5196,4261,3364,2693,1685,4262, 961, # 1744
-1673,2632, 190,2006,2203,3841,4585,4586,5197, 570,2504,3711,1490,5198,4587,2633, # 1760
-3293,1957,4588, 584,1514, 396,1045,1945,5199,4589,1968,2449,5200,5201,4590,4013, # 1776
- 619,5202,3154,3294, 215,2007,2796,2561,3220,4591,3221,4592, 763,4263,3842,4593, # 1792
-5203,5204,1958,1767,2956,3365,3712,1174, 452,1477,4594,3366,3155,5205,2838,1253, # 1808
-2387,2189,1091,2290,4264, 492,5206, 638,1169,1825,2136,1752,4014, 648, 926,1021, # 1824
-1324,4595, 520,4596, 997, 847,1007, 892,4597,3843,2267,1872,3713,2405,1785,4598, # 1840
-1953,2957,3103,3222,1728,4265,2044,3714,4599,2008,1701,3156,1551, 30,2268,4266, # 1856
-5207,2027,4600,3589,5208, 501,5209,4267, 594,3478,2166,1822,3590,3479,3591,3223, # 1872
- 829,2839,4268,5210,1680,3157,1225,4269,5211,3295,4601,4270,3158,2341,5212,4602, # 1888
-4271,5213,4015,4016,5214,1848,2388,2606,3367,5215,4603, 374,4017, 652,4272,4273, # 1904
- 375,1140, 798,5216,5217,5218,2366,4604,2269, 546,1659, 138,3051,2450,4605,5219, # 1920
-2254, 612,1849, 910, 796,3844,1740,1371, 825,3845,3846,5220,2920,2562,5221, 692, # 1936
- 444,3052,2634, 801,4606,4274,5222,1491, 244,1053,3053,4275,4276, 340,5223,4018, # 1952
-1041,3005, 293,1168, 87,1357,5224,1539, 959,5225,2240, 721, 694,4277,3847, 219, # 1968
-1478, 644,1417,3368,2666,1413,1401,1335,1389,4019,5226,5227,3006,2367,3159,1826, # 1984
- 730,1515, 184,2840, 66,4607,5228,1660,2958, 246,3369, 378,1457, 226,3480, 975, # 2000
-4020,2959,1264,3592, 674, 696,5229, 163,5230,1141,2422,2167, 713,3593,3370,4608, # 2016
-4021,5231,5232,1186, 15,5233,1079,1070,5234,1522,3224,3594, 276,1050,2725, 758, # 2032
-1126, 653,2960,3296,5235,2342, 889,3595,4022,3104,3007, 903,1250,4609,4023,3481, # 2048
-3596,1342,1681,1718, 766,3297, 286, 89,2961,3715,5236,1713,5237,2607,3371,3008, # 2064
-5238,2962,2219,3225,2880,5239,4610,2505,2533, 181, 387,1075,4024, 731,2190,3372, # 2080
-5240,3298, 310, 313,3482,2304, 770,4278, 54,3054, 189,4611,3105,3848,4025,5241, # 2096
-1230,1617,1850, 355,3597,4279,4612,3373, 111,4280,3716,1350,3160,3483,3055,4281, # 2112
-2150,3299,3598,5242,2797,4026,4027,3009, 722,2009,5243,1071, 247,1207,2343,2478, # 2128
-1378,4613,2010, 864,1437,1214,4614, 373,3849,1142,2220, 667,4615, 442,2763,2563, # 2144
-3850,4028,1969,4282,3300,1840, 837, 170,1107, 934,1336,1883,5244,5245,2119,4283, # 2160
-2841, 743,1569,5246,4616,4284, 582,2389,1418,3484,5247,1803,5248, 357,1395,1729, # 2176
-3717,3301,2423,1564,2241,5249,3106,3851,1633,4617,1114,2086,4285,1532,5250, 482, # 2192
-2451,4618,5251,5252,1492, 833,1466,5253,2726,3599,1641,2842,5254,1526,1272,3718, # 2208
-4286,1686,1795, 416,2564,1903,1954,1804,5255,3852,2798,3853,1159,2321,5256,2881, # 2224
-4619,1610,1584,3056,2424,2764, 443,3302,1163,3161,5257,5258,4029,5259,4287,2506, # 2240
-3057,4620,4030,3162,2104,1647,3600,2011,1873,4288,5260,4289, 431,3485,5261, 250, # 2256
- 97, 81,4290,5262,1648,1851,1558, 160, 848,5263, 866, 740,1694,5264,2204,2843, # 2272
-3226,4291,4621,3719,1687, 950,2479, 426, 469,3227,3720,3721,4031,5265,5266,1188, # 2288
- 424,1996, 861,3601,4292,3854,2205,2694, 168,1235,3602,4293,5267,2087,1674,4622, # 2304
-3374,3303, 220,2565,1009,5268,3855, 670,3010, 332,1208, 717,5269,5270,3603,2452, # 2320
-4032,3375,5271, 513,5272,1209,2882,3376,3163,4623,1080,5273,5274,5275,5276,2534, # 2336
-3722,3604, 815,1587,4033,4034,5277,3605,3486,3856,1254,4624,1328,3058,1390,4035, # 2352
-1741,4036,3857,4037,5278, 236,3858,2453,3304,5279,5280,3723,3859,1273,3860,4625, # 2368
-5281, 308,5282,4626, 245,4627,1852,2480,1307,2583, 430, 715,2137,2454,5283, 270, # 2384
- 199,2883,4038,5284,3606,2727,1753, 761,1754, 725,1661,1841,4628,3487,3724,5285, # 2400
-5286, 587, 14,3305, 227,2608, 326, 480,2270, 943,2765,3607, 291, 650,1884,5287, # 2416
-1702,1226, 102,1547, 62,3488, 904,4629,3489,1164,4294,5288,5289,1224,1548,2766, # 2432
- 391, 498,1493,5290,1386,1419,5291,2056,1177,4630, 813, 880,1081,2368, 566,1145, # 2448
-4631,2291,1001,1035,2566,2609,2242, 394,1286,5292,5293,2069,5294, 86,1494,1730, # 2464
-4039, 491,1588, 745, 897,2963, 843,3377,4040,2767,2884,3306,1768, 998,2221,2070, # 2480
- 397,1827,1195,1970,3725,3011,3378, 284,5295,3861,2507,2138,2120,1904,5296,4041, # 2496
-2151,4042,4295,1036,3490,1905, 114,2567,4296, 209,1527,5297,5298,2964,2844,2635, # 2512
-2390,2728,3164, 812,2568,5299,3307,5300,1559, 737,1885,3726,1210, 885, 28,2695, # 2528
-3608,3862,5301,4297,1004,1780,4632,5302, 346,1982,2222,2696,4633,3863,1742, 797, # 2544
-1642,4043,1934,1072,1384,2152, 896,4044,3308,3727,3228,2885,3609,5303,2569,1959, # 2560
-4634,2455,1786,5304,5305,5306,4045,4298,1005,1308,3728,4299,2729,4635,4636,1528, # 2576
-2610, 161,1178,4300,1983, 987,4637,1101,4301, 631,4046,1157,3229,2425,1343,1241, # 2592
-1016,2243,2570, 372, 877,2344,2508,1160, 555,1935, 911,4047,5307, 466,1170, 169, # 2608
-1051,2921,2697,3729,2481,3012,1182,2012,2571,1251,2636,5308, 992,2345,3491,1540, # 2624
-2730,1201,2071,2406,1997,2482,5309,4638, 528,1923,2191,1503,1874,1570,2369,3379, # 2640
-3309,5310, 557,1073,5311,1828,3492,2088,2271,3165,3059,3107, 767,3108,2799,4639, # 2656
-1006,4302,4640,2346,1267,2179,3730,3230, 778,4048,3231,2731,1597,2667,5312,4641, # 2672
-5313,3493,5314,5315,5316,3310,2698,1433,3311, 131, 95,1504,4049, 723,4303,3166, # 2688
-1842,3610,2768,2192,4050,2028,2105,3731,5317,3013,4051,1218,5318,3380,3232,4052, # 2704
-4304,2584, 248,1634,3864, 912,5319,2845,3732,3060,3865, 654, 53,5320,3014,5321, # 2720
-1688,4642, 777,3494,1032,4053,1425,5322, 191, 820,2121,2846, 971,4643, 931,3233, # 2736
- 135, 664, 783,3866,1998, 772,2922,1936,4054,3867,4644,2923,3234, 282,2732, 640, # 2752
-1372,3495,1127, 922, 325,3381,5323,5324, 711,2045,5325,5326,4055,2223,2800,1937, # 2768
-4056,3382,2224,2255,3868,2305,5327,4645,3869,1258,3312,4057,3235,2139,2965,4058, # 2784
-4059,5328,2225, 258,3236,4646, 101,1227,5329,3313,1755,5330,1391,3314,5331,2924, # 2800
-2057, 893,5332,5333,5334,1402,4305,2347,5335,5336,3237,3611,5337,5338, 878,1325, # 2816
-1781,2801,4647, 259,1385,2585, 744,1183,2272,4648,5339,4060,2509,5340, 684,1024, # 2832
-4306,5341, 472,3612,3496,1165,3315,4061,4062, 322,2153, 881, 455,1695,1152,1340, # 2848
- 660, 554,2154,4649,1058,4650,4307, 830,1065,3383,4063,4651,1924,5342,1703,1919, # 2864
-5343, 932,2273, 122,5344,4652, 947, 677,5345,3870,2637, 297,1906,1925,2274,4653, # 2880
-2322,3316,5346,5347,4308,5348,4309, 84,4310, 112, 989,5349, 547,1059,4064, 701, # 2896
-3613,1019,5350,4311,5351,3497, 942, 639, 457,2306,2456, 993,2966, 407, 851, 494, # 2912
-4654,3384, 927,5352,1237,5353,2426,3385, 573,4312, 680, 921,2925,1279,1875, 285, # 2928
- 790,1448,1984, 719,2168,5354,5355,4655,4065,4066,1649,5356,1541, 563,5357,1077, # 2944
-5358,3386,3061,3498, 511,3015,4067,4068,3733,4069,1268,2572,3387,3238,4656,4657, # 2960
-5359, 535,1048,1276,1189,2926,2029,3167,1438,1373,2847,2967,1134,2013,5360,4313, # 2976
-1238,2586,3109,1259,5361, 700,5362,2968,3168,3734,4314,5363,4315,1146,1876,1907, # 2992
-4658,2611,4070, 781,2427, 132,1589, 203, 147, 273,2802,2407, 898,1787,2155,4071, # 3008
-4072,5364,3871,2803,5365,5366,4659,4660,5367,3239,5368,1635,3872, 965,5369,1805, # 3024
-2699,1516,3614,1121,1082,1329,3317,4073,1449,3873, 65,1128,2848,2927,2769,1590, # 3040
-3874,5370,5371, 12,2668, 45, 976,2587,3169,4661, 517,2535,1013,1037,3240,5372, # 3056
-3875,2849,5373,3876,5374,3499,5375,2612, 614,1999,2323,3877,3110,2733,2638,5376, # 3072
-2588,4316, 599,1269,5377,1811,3735,5378,2700,3111, 759,1060, 489,1806,3388,3318, # 3088
-1358,5379,5380,2391,1387,1215,2639,2256, 490,5381,5382,4317,1759,2392,2348,5383, # 3104
-4662,3878,1908,4074,2640,1807,3241,4663,3500,3319,2770,2349, 874,5384,5385,3501, # 3120
-3736,1859, 91,2928,3737,3062,3879,4664,5386,3170,4075,2669,5387,3502,1202,1403, # 3136
-3880,2969,2536,1517,2510,4665,3503,2511,5388,4666,5389,2701,1886,1495,1731,4076, # 3152
-2370,4667,5390,2030,5391,5392,4077,2702,1216, 237,2589,4318,2324,4078,3881,4668, # 3168
-4669,2703,3615,3504, 445,4670,5393,5394,5395,5396,2771, 61,4079,3738,1823,4080, # 3184
-5397, 687,2046, 935, 925, 405,2670, 703,1096,1860,2734,4671,4081,1877,1367,2704, # 3200
-3389, 918,2106,1782,2483, 334,3320,1611,1093,4672, 564,3171,3505,3739,3390, 945, # 3216
-2641,2058,4673,5398,1926, 872,4319,5399,3506,2705,3112, 349,4320,3740,4082,4674, # 3232
-3882,4321,3741,2156,4083,4675,4676,4322,4677,2408,2047, 782,4084, 400, 251,4323, # 3248
-1624,5400,5401, 277,3742, 299,1265, 476,1191,3883,2122,4324,4325,1109, 205,5402, # 3264
-2590,1000,2157,3616,1861,5403,5404,5405,4678,5406,4679,2573, 107,2484,2158,4085, # 3280
-3507,3172,5407,1533, 541,1301, 158, 753,4326,2886,3617,5408,1696, 370,1088,4327, # 3296
-4680,3618, 579, 327, 440, 162,2244, 269,1938,1374,3508, 968,3063, 56,1396,3113, # 3312
-2107,3321,3391,5409,1927,2159,4681,3016,5410,3619,5411,5412,3743,4682,2485,5413, # 3328
-2804,5414,1650,4683,5415,2613,5416,5417,4086,2671,3392,1149,3393,4087,3884,4088, # 3344
-5418,1076, 49,5419, 951,3242,3322,3323, 450,2850, 920,5420,1812,2805,2371,4328, # 3360
-1909,1138,2372,3885,3509,5421,3243,4684,1910,1147,1518,2428,4685,3886,5422,4686, # 3376
-2393,2614, 260,1796,3244,5423,5424,3887,3324, 708,5425,3620,1704,5426,3621,1351, # 3392
-1618,3394,3017,1887, 944,4329,3395,4330,3064,3396,4331,5427,3744, 422, 413,1714, # 3408
-3325, 500,2059,2350,4332,2486,5428,1344,1911, 954,5429,1668,5430,5431,4089,2409, # 3424
-4333,3622,3888,4334,5432,2307,1318,2512,3114, 133,3115,2887,4687, 629, 31,2851, # 3440
-2706,3889,4688, 850, 949,4689,4090,2970,1732,2089,4335,1496,1853,5433,4091, 620, # 3456
-3245, 981,1242,3745,3397,1619,3746,1643,3326,2140,2457,1971,1719,3510,2169,5434, # 3472
-3246,5435,5436,3398,1829,5437,1277,4690,1565,2048,5438,1636,3623,3116,5439, 869, # 3488
-2852, 655,3890,3891,3117,4092,3018,3892,1310,3624,4691,5440,5441,5442,1733, 558, # 3504
-4692,3747, 335,1549,3065,1756,4336,3748,1946,3511,1830,1291,1192, 470,2735,2108, # 3520
-2806, 913,1054,4093,5443,1027,5444,3066,4094,4693, 982,2672,3399,3173,3512,3247, # 3536
-3248,1947,2807,5445, 571,4694,5446,1831,5447,3625,2591,1523,2429,5448,2090, 984, # 3552
-4695,3749,1960,5449,3750, 852, 923,2808,3513,3751, 969,1519, 999,2049,2325,1705, # 3568
-5450,3118, 615,1662, 151, 597,4095,2410,2326,1049, 275,4696,3752,4337, 568,3753, # 3584
-3626,2487,4338,3754,5451,2430,2275, 409,3249,5452,1566,2888,3514,1002, 769,2853, # 3600
- 194,2091,3174,3755,2226,3327,4339, 628,1505,5453,5454,1763,2180,3019,4096, 521, # 3616
-1161,2592,1788,2206,2411,4697,4097,1625,4340,4341, 412, 42,3119, 464,5455,2642, # 3632
-4698,3400,1760,1571,2889,3515,2537,1219,2207,3893,2643,2141,2373,4699,4700,3328, # 3648
-1651,3401,3627,5456,5457,3628,2488,3516,5458,3756,5459,5460,2276,2092, 460,5461, # 3664
-4701,5462,3020, 962, 588,3629, 289,3250,2644,1116, 52,5463,3067,1797,5464,5465, # 3680
-5466,1467,5467,1598,1143,3757,4342,1985,1734,1067,4702,1280,3402, 465,4703,1572, # 3696
- 510,5468,1928,2245,1813,1644,3630,5469,4704,3758,5470,5471,2673,1573,1534,5472, # 3712
-5473, 536,1808,1761,3517,3894,3175,2645,5474,5475,5476,4705,3518,2929,1912,2809, # 3728
-5477,3329,1122, 377,3251,5478, 360,5479,5480,4343,1529, 551,5481,2060,3759,1769, # 3744
-2431,5482,2930,4344,3330,3120,2327,2109,2031,4706,1404, 136,1468,1479, 672,1171, # 3760
-3252,2308, 271,3176,5483,2772,5484,2050, 678,2736, 865,1948,4707,5485,2014,4098, # 3776
-2971,5486,2737,2227,1397,3068,3760,4708,4709,1735,2931,3403,3631,5487,3895, 509, # 3792
-2854,2458,2890,3896,5488,5489,3177,3178,4710,4345,2538,4711,2309,1166,1010, 552, # 3808
- 681,1888,5490,5491,2972,2973,4099,1287,1596,1862,3179, 358, 453, 736, 175, 478, # 3824
-1117, 905,1167,1097,5492,1854,1530,5493,1706,5494,2181,3519,2292,3761,3520,3632, # 3840
-4346,2093,4347,5495,3404,1193,2489,4348,1458,2193,2208,1863,1889,1421,3331,2932, # 3856
-3069,2182,3521, 595,2123,5496,4100,5497,5498,4349,1707,2646, 223,3762,1359, 751, # 3872
-3121, 183,3522,5499,2810,3021, 419,2374, 633, 704,3897,2394, 241,5500,5501,5502, # 3888
- 838,3022,3763,2277,2773,2459,3898,1939,2051,4101,1309,3122,2246,1181,5503,1136, # 3904
-2209,3899,2375,1446,4350,2310,4712,5504,5505,4351,1055,2615, 484,3764,5506,4102, # 3920
- 625,4352,2278,3405,1499,4353,4103,5507,4104,4354,3253,2279,2280,3523,5508,5509, # 3936
-2774, 808,2616,3765,3406,4105,4355,3123,2539, 526,3407,3900,4356, 955,5510,1620, # 3952
-4357,2647,2432,5511,1429,3766,1669,1832, 994, 928,5512,3633,1260,5513,5514,5515, # 3968
-1949,2293, 741,2933,1626,4358,2738,2460, 867,1184, 362,3408,1392,5516,5517,4106, # 3984
-4359,1770,1736,3254,2934,4713,4714,1929,2707,1459,1158,5518,3070,3409,2891,1292, # 4000
-1930,2513,2855,3767,1986,1187,2072,2015,2617,4360,5519,2574,2514,2170,3768,2490, # 4016
-3332,5520,3769,4715,5521,5522, 666,1003,3023,1022,3634,4361,5523,4716,1814,2257, # 4032
- 574,3901,1603, 295,1535, 705,3902,4362, 283, 858, 417,5524,5525,3255,4717,4718, # 4048
-3071,1220,1890,1046,2281,2461,4107,1393,1599, 689,2575, 388,4363,5526,2491, 802, # 4064
-5527,2811,3903,2061,1405,2258,5528,4719,3904,2110,1052,1345,3256,1585,5529, 809, # 4080
-5530,5531,5532, 575,2739,3524, 956,1552,1469,1144,2328,5533,2329,1560,2462,3635, # 4096
-3257,4108, 616,2210,4364,3180,2183,2294,5534,1833,5535,3525,4720,5536,1319,3770, # 4112
-3771,1211,3636,1023,3258,1293,2812,5537,5538,5539,3905, 607,2311,3906, 762,2892, # 4128
-1439,4365,1360,4721,1485,3072,5540,4722,1038,4366,1450,2062,2648,4367,1379,4723, # 4144
-2593,5541,5542,4368,1352,1414,2330,2935,1172,5543,5544,3907,3908,4724,1798,1451, # 4160
-5545,5546,5547,5548,2936,4109,4110,2492,2351, 411,4111,4112,3637,3333,3124,4725, # 4176
-1561,2674,1452,4113,1375,5549,5550, 47,2974, 316,5551,1406,1591,2937,3181,5552, # 4192
-1025,2142,3125,3182, 354,2740, 884,2228,4369,2412, 508,3772, 726,3638, 996,2433, # 4208
-3639, 729,5553, 392,2194,1453,4114,4726,3773,5554,5555,2463,3640,2618,1675,2813, # 4224
- 919,2352,2975,2353,1270,4727,4115, 73,5556,5557, 647,5558,3259,2856,2259,1550, # 4240
-1346,3024,5559,1332, 883,3526,5560,5561,5562,5563,3334,2775,5564,1212, 831,1347, # 4256
-4370,4728,2331,3909,1864,3073, 720,3910,4729,4730,3911,5565,4371,5566,5567,4731, # 4272
-5568,5569,1799,4732,3774,2619,4733,3641,1645,2376,4734,5570,2938, 669,2211,2675, # 4288
-2434,5571,2893,5572,5573,1028,3260,5574,4372,2413,5575,2260,1353,5576,5577,4735, # 4304
-3183, 518,5578,4116,5579,4373,1961,5580,2143,4374,5581,5582,3025,2354,2355,3912, # 4320
- 516,1834,1454,4117,2708,4375,4736,2229,2620,1972,1129,3642,5583,2776,5584,2976, # 4336
-1422, 577,1470,3026,1524,3410,5585,5586, 432,4376,3074,3527,5587,2594,1455,2515, # 4352
-2230,1973,1175,5588,1020,2741,4118,3528,4737,5589,2742,5590,1743,1361,3075,3529, # 4368
-2649,4119,4377,4738,2295, 895, 924,4378,2171, 331,2247,3076, 166,1627,3077,1098, # 4384
-5591,1232,2894,2231,3411,4739, 657, 403,1196,2377, 542,3775,3412,1600,4379,3530, # 4400
-5592,4740,2777,3261, 576, 530,1362,4741,4742,2540,2676,3776,4120,5593, 842,3913, # 4416
-5594,2814,2032,1014,4121, 213,2709,3413, 665, 621,4380,5595,3777,2939,2435,5596, # 4432
-2436,3335,3643,3414,4743,4381,2541,4382,4744,3644,1682,4383,3531,1380,5597, 724, # 4448
-2282, 600,1670,5598,1337,1233,4745,3126,2248,5599,1621,4746,5600, 651,4384,5601, # 4464
-1612,4385,2621,5602,2857,5603,2743,2312,3078,5604, 716,2464,3079, 174,1255,2710, # 4480
-4122,3645, 548,1320,1398, 728,4123,1574,5605,1891,1197,3080,4124,5606,3081,3082, # 4496
-3778,3646,3779, 747,5607, 635,4386,4747,5608,5609,5610,4387,5611,5612,4748,5613, # 4512
-3415,4749,2437, 451,5614,3780,2542,2073,4388,2744,4389,4125,5615,1764,4750,5616, # 4528
-4390, 350,4751,2283,2395,2493,5617,4391,4126,2249,1434,4127, 488,4752, 458,4392, # 4544
-4128,3781, 771,1330,2396,3914,2576,3184,2160,2414,1553,2677,3185,4393,5618,2494, # 4560
-2895,2622,1720,2711,4394,3416,4753,5619,2543,4395,5620,3262,4396,2778,5621,2016, # 4576
-2745,5622,1155,1017,3782,3915,5623,3336,2313, 201,1865,4397,1430,5624,4129,5625, # 4592
-5626,5627,5628,5629,4398,1604,5630, 414,1866, 371,2595,4754,4755,3532,2017,3127, # 4608
-4756,1708, 960,4399, 887, 389,2172,1536,1663,1721,5631,2232,4130,2356,2940,1580, # 4624
-5632,5633,1744,4757,2544,4758,4759,5634,4760,5635,2074,5636,4761,3647,3417,2896, # 4640
-4400,5637,4401,2650,3418,2815, 673,2712,2465, 709,3533,4131,3648,4402,5638,1148, # 4656
- 502, 634,5639,5640,1204,4762,3649,1575,4763,2623,3783,5641,3784,3128, 948,3263, # 4672
- 121,1745,3916,1110,5642,4403,3083,2516,3027,4132,3785,1151,1771,3917,1488,4133, # 4688
-1987,5643,2438,3534,5644,5645,2094,5646,4404,3918,1213,1407,2816, 531,2746,2545, # 4704
-3264,1011,1537,4764,2779,4405,3129,1061,5647,3786,3787,1867,2897,5648,2018, 120, # 4720
-4406,4407,2063,3650,3265,2314,3919,2678,3419,1955,4765,4134,5649,3535,1047,2713, # 4736
-1266,5650,1368,4766,2858, 649,3420,3920,2546,2747,1102,2859,2679,5651,5652,2000, # 4752
-5653,1111,3651,2977,5654,2495,3921,3652,2817,1855,3421,3788,5655,5656,3422,2415, # 4768
-2898,3337,3266,3653,5657,2577,5658,3654,2818,4135,1460, 856,5659,3655,5660,2899, # 4784
-2978,5661,2900,3922,5662,4408, 632,2517, 875,3923,1697,3924,2296,5663,5664,4767, # 4800
-3028,1239, 580,4768,4409,5665, 914, 936,2075,1190,4136,1039,2124,5666,5667,5668, # 4816
-5669,3423,1473,5670,1354,4410,3925,4769,2173,3084,4137, 915,3338,4411,4412,3339, # 4832
-1605,1835,5671,2748, 398,3656,4413,3926,4138, 328,1913,2860,4139,3927,1331,4414, # 4848
-3029, 937,4415,5672,3657,4140,4141,3424,2161,4770,3425, 524, 742, 538,3085,1012, # 4864
-5673,5674,3928,2466,5675, 658,1103, 225,3929,5676,5677,4771,5678,4772,5679,3267, # 4880
-1243,5680,4142, 963,2250,4773,5681,2714,3658,3186,5682,5683,2596,2332,5684,4774, # 4896
-5685,5686,5687,3536, 957,3426,2547,2033,1931,2941,2467, 870,2019,3659,1746,2780, # 4912
-2781,2439,2468,5688,3930,5689,3789,3130,3790,3537,3427,3791,5690,1179,3086,5691, # 4928
-3187,2378,4416,3792,2548,3188,3131,2749,4143,5692,3428,1556,2549,2297, 977,2901, # 4944
-2034,4144,1205,3429,5693,1765,3430,3189,2125,1271, 714,1689,4775,3538,5694,2333, # 4960
-3931, 533,4417,3660,2184, 617,5695,2469,3340,3539,2315,5696,5697,3190,5698,5699, # 4976
-3932,1988, 618, 427,2651,3540,3431,5700,5701,1244,1690,5702,2819,4418,4776,5703, # 4992
-3541,4777,5704,2284,1576, 473,3661,4419,3432, 972,5705,3662,5706,3087,5707,5708, # 5008
-4778,4779,5709,3793,4145,4146,5710, 153,4780, 356,5711,1892,2902,4420,2144, 408, # 5024
- 803,2357,5712,3933,5713,4421,1646,2578,2518,4781,4782,3934,5714,3935,4422,5715, # 5040
-2416,3433, 752,5716,5717,1962,3341,2979,5718, 746,3030,2470,4783,4423,3794, 698, # 5056
-4784,1893,4424,3663,2550,4785,3664,3936,5719,3191,3434,5720,1824,1302,4147,2715, # 5072
-3937,1974,4425,5721,4426,3192, 823,1303,1288,1236,2861,3542,4148,3435, 774,3938, # 5088
-5722,1581,4786,1304,2862,3939,4787,5723,2440,2162,1083,3268,4427,4149,4428, 344, # 5104
-1173, 288,2316, 454,1683,5724,5725,1461,4788,4150,2597,5726,5727,4789, 985, 894, # 5120
-5728,3436,3193,5729,1914,2942,3795,1989,5730,2111,1975,5731,4151,5732,2579,1194, # 5136
- 425,5733,4790,3194,1245,3796,4429,5734,5735,2863,5736, 636,4791,1856,3940, 760, # 5152
-1800,5737,4430,2212,1508,4792,4152,1894,1684,2298,5738,5739,4793,4431,4432,2213, # 5168
- 479,5740,5741, 832,5742,4153,2496,5743,2980,2497,3797, 990,3132, 627,1815,2652, # 5184
-4433,1582,4434,2126,2112,3543,4794,5744, 799,4435,3195,5745,4795,2113,1737,3031, # 5200
-1018, 543, 754,4436,3342,1676,4796,4797,4154,4798,1489,5746,3544,5747,2624,2903, # 5216
-4155,5748,5749,2981,5750,5751,5752,5753,3196,4799,4800,2185,1722,5754,3269,3270, # 5232
-1843,3665,1715, 481, 365,1976,1857,5755,5756,1963,2498,4801,5757,2127,3666,3271, # 5248
- 433,1895,2064,2076,5758, 602,2750,5759,5760,5761,5762,5763,3032,1628,3437,5764, # 5264
-3197,4802,4156,2904,4803,2519,5765,2551,2782,5766,5767,5768,3343,4804,2905,5769, # 5280
-4805,5770,2864,4806,4807,1221,2982,4157,2520,5771,5772,5773,1868,1990,5774,5775, # 5296
-5776,1896,5777,5778,4808,1897,4158, 318,5779,2095,4159,4437,5780,5781, 485,5782, # 5312
- 938,3941, 553,2680, 116,5783,3942,3667,5784,3545,2681,2783,3438,3344,2820,5785, # 5328
-3668,2943,4160,1747,2944,2983,5786,5787, 207,5788,4809,5789,4810,2521,5790,3033, # 5344
- 890,3669,3943,5791,1878,3798,3439,5792,2186,2358,3440,1652,5793,5794,5795, 941, # 5360
-2299, 208,3546,4161,2020, 330,4438,3944,2906,2499,3799,4439,4811,5796,5797,5798, # 5376 #last 512
-#Everything below is of no interest for detection purpose
-2522,1613,4812,5799,3345,3945,2523,5800,4162,5801,1637,4163,2471,4813,3946,5802, # 5392
-2500,3034,3800,5803,5804,2195,4814,5805,2163,5806,5807,5808,5809,5810,5811,5812, # 5408
-5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828, # 5424
-5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844, # 5440
-5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856,5857,5858,5859,5860, # 5456
-5861,5862,5863,5864,5865,5866,5867,5868,5869,5870,5871,5872,5873,5874,5875,5876, # 5472
-5877,5878,5879,5880,5881,5882,5883,5884,5885,5886,5887,5888,5889,5890,5891,5892, # 5488
-5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904,5905,5906,5907,5908, # 5504
-5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920,5921,5922,5923,5924, # 5520
-5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936,5937,5938,5939,5940, # 5536
-5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,5952,5953,5954,5955,5956, # 5552
-5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968,5969,5970,5971,5972, # 5568
-5973,5974,5975,5976,5977,5978,5979,5980,5981,5982,5983,5984,5985,5986,5987,5988, # 5584
-5989,5990,5991,5992,5993,5994,5995,5996,5997,5998,5999,6000,6001,6002,6003,6004, # 5600
-6005,6006,6007,6008,6009,6010,6011,6012,6013,6014,6015,6016,6017,6018,6019,6020, # 5616
-6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032,6033,6034,6035,6036, # 5632
-6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052, # 5648
-6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6068, # 5664
-6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084, # 5680
-6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6100, # 5696
-6101,6102,6103,6104,6105,6106,6107,6108,6109,6110,6111,6112,6113,6114,6115,6116, # 5712
-6117,6118,6119,6120,6121,6122,6123,6124,6125,6126,6127,6128,6129,6130,6131,6132, # 5728
-6133,6134,6135,6136,6137,6138,6139,6140,6141,6142,6143,6144,6145,6146,6147,6148, # 5744
-6149,6150,6151,6152,6153,6154,6155,6156,6157,6158,6159,6160,6161,6162,6163,6164, # 5760
-6165,6166,6167,6168,6169,6170,6171,6172,6173,6174,6175,6176,6177,6178,6179,6180, # 5776
-6181,6182,6183,6184,6185,6186,6187,6188,6189,6190,6191,6192,6193,6194,6195,6196, # 5792
-6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210,6211,6212, # 5808
-6213,6214,6215,6216,6217,6218,6219,6220,6221,6222,6223,3670,6224,6225,6226,6227, # 5824
-6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241,6242,6243, # 5840
-6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,6254,6255,6256,6257,6258,6259, # 5856
-6260,6261,6262,6263,6264,6265,6266,6267,6268,6269,6270,6271,6272,6273,6274,6275, # 5872
-6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,4815,6286,6287,6288,6289,6290, # 5888
-6291,6292,4816,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,6303,6304,6305, # 5904
-6306,6307,6308,6309,6310,6311,4817,4818,6312,6313,6314,6315,6316,6317,6318,4819, # 5920
-6319,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333,6334, # 5936
-6335,6336,6337,4820,6338,6339,6340,6341,6342,6343,6344,6345,6346,6347,6348,6349, # 5952
-6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363,6364,6365, # 5968
-6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379,6380,6381, # 5984
-6382,6383,6384,6385,6386,6387,6388,6389,6390,6391,6392,6393,6394,6395,6396,6397, # 6000
-6398,6399,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,3441,6411,6412, # 6016
-6413,6414,6415,6416,6417,6418,6419,6420,6421,6422,6423,6424,6425,4440,6426,6427, # 6032
-6428,6429,6430,6431,6432,6433,6434,6435,6436,6437,6438,6439,6440,6441,6442,6443, # 6048
-6444,6445,6446,6447,6448,6449,6450,6451,6452,6453,6454,4821,6455,6456,6457,6458, # 6064
-6459,6460,6461,6462,6463,6464,6465,6466,6467,6468,6469,6470,6471,6472,6473,6474, # 6080
-6475,6476,6477,3947,3948,6478,6479,6480,6481,3272,4441,6482,6483,6484,6485,4442, # 6096
-6486,6487,6488,6489,6490,6491,6492,6493,6494,6495,6496,4822,6497,6498,6499,6500, # 6112
-6501,6502,6503,6504,6505,6506,6507,6508,6509,6510,6511,6512,6513,6514,6515,6516, # 6128
-6517,6518,6519,6520,6521,6522,6523,6524,6525,6526,6527,6528,6529,6530,6531,6532, # 6144
-6533,6534,6535,6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548, # 6160
-6549,6550,6551,6552,6553,6554,6555,6556,2784,6557,4823,6558,6559,6560,6561,6562, # 6176
-6563,6564,6565,6566,6567,6568,6569,3949,6570,6571,6572,4824,6573,6574,6575,6576, # 6192
-6577,6578,6579,6580,6581,6582,6583,4825,6584,6585,6586,3950,2785,6587,6588,6589, # 6208
-6590,6591,6592,6593,6594,6595,6596,6597,6598,6599,6600,6601,6602,6603,6604,6605, # 6224
-6606,6607,6608,6609,6610,6611,6612,4826,6613,6614,6615,4827,6616,6617,6618,6619, # 6240
-6620,6621,6622,6623,6624,6625,4164,6626,6627,6628,6629,6630,6631,6632,6633,6634, # 6256
-3547,6635,4828,6636,6637,6638,6639,6640,6641,6642,3951,2984,6643,6644,6645,6646, # 6272
-6647,6648,6649,4165,6650,4829,6651,6652,4830,6653,6654,6655,6656,6657,6658,6659, # 6288
-6660,6661,6662,4831,6663,6664,6665,6666,6667,6668,6669,6670,6671,4166,6672,4832, # 6304
-3952,6673,6674,6675,6676,4833,6677,6678,6679,4167,6680,6681,6682,3198,6683,6684, # 6320
-6685,6686,6687,6688,6689,6690,6691,6692,6693,6694,6695,6696,6697,4834,6698,6699, # 6336
-6700,6701,6702,6703,6704,6705,6706,6707,6708,6709,6710,6711,6712,6713,6714,6715, # 6352
-6716,6717,6718,6719,6720,6721,6722,6723,6724,6725,6726,6727,6728,6729,6730,6731, # 6368
-6732,6733,6734,4443,6735,6736,6737,6738,6739,6740,6741,6742,6743,6744,6745,4444, # 6384
-6746,6747,6748,6749,6750,6751,6752,6753,6754,6755,6756,6757,6758,6759,6760,6761, # 6400
-6762,6763,6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777, # 6416
-6778,6779,6780,6781,4168,6782,6783,3442,6784,6785,6786,6787,6788,6789,6790,6791, # 6432
-4169,6792,6793,6794,6795,6796,6797,6798,6799,6800,6801,6802,6803,6804,6805,6806, # 6448
-6807,6808,6809,6810,6811,4835,6812,6813,6814,4445,6815,6816,4446,6817,6818,6819, # 6464
-6820,6821,6822,6823,6824,6825,6826,6827,6828,6829,6830,6831,6832,6833,6834,6835, # 6480
-3548,6836,6837,6838,6839,6840,6841,6842,6843,6844,6845,6846,4836,6847,6848,6849, # 6496
-6850,6851,6852,6853,6854,3953,6855,6856,6857,6858,6859,6860,6861,6862,6863,6864, # 6512
-6865,6866,6867,6868,6869,6870,6871,6872,6873,6874,6875,6876,6877,3199,6878,6879, # 6528
-6880,6881,6882,4447,6883,6884,6885,6886,6887,6888,6889,6890,6891,6892,6893,6894, # 6544
-6895,6896,6897,6898,6899,6900,6901,6902,6903,6904,4170,6905,6906,6907,6908,6909, # 6560
-6910,6911,6912,6913,6914,6915,6916,6917,6918,6919,6920,6921,6922,6923,6924,6925, # 6576
-6926,6927,4837,6928,6929,6930,6931,6932,6933,6934,6935,6936,3346,6937,6938,4838, # 6592
-6939,6940,6941,4448,6942,6943,6944,6945,6946,4449,6947,6948,6949,6950,6951,6952, # 6608
-6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6964,6965,6966,6967,6968, # 6624
-6969,6970,6971,6972,6973,6974,6975,6976,6977,6978,6979,6980,6981,6982,6983,6984, # 6640
-6985,6986,6987,6988,6989,6990,6991,6992,6993,6994,3671,6995,6996,6997,6998,4839, # 6656
-6999,7000,7001,7002,3549,7003,7004,7005,7006,7007,7008,7009,7010,7011,7012,7013, # 6672
-7014,7015,7016,7017,7018,7019,7020,7021,7022,7023,7024,7025,7026,7027,7028,7029, # 6688
-7030,4840,7031,7032,7033,7034,7035,7036,7037,7038,4841,7039,7040,7041,7042,7043, # 6704
-7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058,7059, # 6720
-7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,2985,7071,7072,7073,7074, # 6736
-7075,7076,7077,7078,7079,7080,4842,7081,7082,7083,7084,7085,7086,7087,7088,7089, # 6752
-7090,7091,7092,7093,7094,7095,7096,7097,7098,7099,7100,7101,7102,7103,7104,7105, # 6768
-7106,7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,4450,7119,7120, # 6784
-7121,7122,7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136, # 6800
-7137,7138,7139,7140,7141,7142,7143,4843,7144,7145,7146,7147,7148,7149,7150,7151, # 6816
-7152,7153,7154,7155,7156,7157,7158,7159,7160,7161,7162,7163,7164,7165,7166,7167, # 6832
-7168,7169,7170,7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183, # 6848
-7184,7185,7186,7187,7188,4171,4172,7189,7190,7191,7192,7193,7194,7195,7196,7197, # 6864
-7198,7199,7200,7201,7202,7203,7204,7205,7206,7207,7208,7209,7210,7211,7212,7213, # 6880
-7214,7215,7216,7217,7218,7219,7220,7221,7222,7223,7224,7225,7226,7227,7228,7229, # 6896
-7230,7231,7232,7233,7234,7235,7236,7237,7238,7239,7240,7241,7242,7243,7244,7245, # 6912
-7246,7247,7248,7249,7250,7251,7252,7253,7254,7255,7256,7257,7258,7259,7260,7261, # 6928
-7262,7263,7264,7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277, # 6944
-7278,7279,7280,7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293, # 6960
-7294,7295,7296,4844,7297,7298,7299,7300,7301,7302,7303,7304,7305,7306,7307,7308, # 6976
-7309,7310,7311,7312,7313,7314,7315,7316,4451,7317,7318,7319,7320,7321,7322,7323, # 6992
-7324,7325,7326,7327,7328,7329,7330,7331,7332,7333,7334,7335,7336,7337,7338,7339, # 7008
-7340,7341,7342,7343,7344,7345,7346,7347,7348,7349,7350,7351,7352,7353,4173,7354, # 7024
-7355,4845,7356,7357,7358,7359,7360,7361,7362,7363,7364,7365,7366,7367,7368,7369, # 7040
-7370,7371,7372,7373,7374,7375,7376,7377,7378,7379,7380,7381,7382,7383,7384,7385, # 7056
-7386,7387,7388,4846,7389,7390,7391,7392,7393,7394,7395,7396,7397,7398,7399,7400, # 7072
-7401,7402,7403,7404,7405,3672,7406,7407,7408,7409,7410,7411,7412,7413,7414,7415, # 7088
-7416,7417,7418,7419,7420,7421,7422,7423,7424,7425,7426,7427,7428,7429,7430,7431, # 7104
-7432,7433,7434,7435,7436,7437,7438,7439,7440,7441,7442,7443,7444,7445,7446,7447, # 7120
-7448,7449,7450,7451,7452,7453,4452,7454,3200,7455,7456,7457,7458,7459,7460,7461, # 7136
-7462,7463,7464,7465,7466,7467,7468,7469,7470,7471,7472,7473,7474,4847,7475,7476, # 7152
-7477,3133,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487,7488,7489,7490,7491, # 7168
-7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,3347,7503,7504,7505,7506, # 7184
-7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519,7520,7521,4848, # 7200
-7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535,7536,7537, # 7216
-7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,3801,4849,7550,7551, # 7232
-7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567, # 7248
-7568,7569,3035,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582, # 7264
-7583,7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598, # 7280
-7599,7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614, # 7296
-7615,7616,4850,7617,7618,3802,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628, # 7312
-7629,7630,7631,7632,4851,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643, # 7328
-7644,7645,7646,7647,7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659, # 7344
-7660,7661,7662,7663,7664,7665,7666,7667,7668,7669,7670,4453,7671,7672,7673,7674, # 7360
-7675,7676,7677,7678,7679,7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690, # 7376
-7691,7692,7693,7694,7695,7696,7697,3443,7698,7699,7700,7701,7702,4454,7703,7704, # 7392
-7705,7706,7707,7708,7709,7710,7711,7712,7713,2472,7714,7715,7716,7717,7718,7719, # 7408
-7720,7721,7722,7723,7724,7725,7726,7727,7728,7729,7730,7731,3954,7732,7733,7734, # 7424
-7735,7736,7737,7738,7739,7740,7741,7742,7743,7744,7745,7746,7747,7748,7749,7750, # 7440
-3134,7751,7752,4852,7753,7754,7755,4853,7756,7757,7758,7759,7760,4174,7761,7762, # 7456
-7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775,7776,7777,7778, # 7472
-7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791,7792,7793,7794, # 7488
-7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,4854,7806,7807,7808,7809, # 7504
-7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,7824,7825, # 7520
-4855,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,7840, # 7536
-7841,7842,7843,7844,7845,7846,7847,3955,7848,7849,7850,7851,7852,7853,7854,7855, # 7552
-7856,7857,7858,7859,7860,3444,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870, # 7568
-7871,7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886, # 7584
-7887,7888,7889,7890,7891,4175,7892,7893,7894,7895,7896,4856,4857,7897,7898,7899, # 7600
-7900,2598,7901,7902,7903,7904,7905,7906,7907,7908,4455,7909,7910,7911,7912,7913, # 7616
-7914,3201,7915,7916,7917,7918,7919,7920,7921,4858,7922,7923,7924,7925,7926,7927, # 7632
-7928,7929,7930,7931,7932,7933,7934,7935,7936,7937,7938,7939,7940,7941,7942,7943, # 7648
-7944,7945,7946,7947,7948,7949,7950,7951,7952,7953,7954,7955,7956,7957,7958,7959, # 7664
-7960,7961,7962,7963,7964,7965,7966,7967,7968,7969,7970,7971,7972,7973,7974,7975, # 7680
-7976,7977,7978,7979,7980,7981,4859,7982,7983,7984,7985,7986,7987,7988,7989,7990, # 7696
-7991,7992,7993,7994,7995,7996,4860,7997,7998,7999,8000,8001,8002,8003,8004,8005, # 7712
-8006,8007,8008,8009,8010,8011,8012,8013,8014,8015,8016,4176,8017,8018,8019,8020, # 7728
-8021,8022,8023,4861,8024,8025,8026,8027,8028,8029,8030,8031,8032,8033,8034,8035, # 7744
-8036,4862,4456,8037,8038,8039,8040,4863,8041,8042,8043,8044,8045,8046,8047,8048, # 7760
-8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063,8064, # 7776
-8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079,8080, # 7792
-8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095,8096, # 7808
-8097,8098,8099,4864,4177,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110, # 7824
-8111,8112,8113,8114,8115,8116,8117,8118,8119,8120,4178,8121,8122,8123,8124,8125, # 7840
-8126,8127,8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141, # 7856
-8142,8143,8144,8145,4865,4866,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155, # 7872
-8156,8157,8158,8159,8160,8161,8162,8163,8164,8165,4179,8166,8167,8168,8169,8170, # 7888
-8171,8172,8173,8174,8175,8176,8177,8178,8179,8180,8181,4457,8182,8183,8184,8185, # 7904
-8186,8187,8188,8189,8190,8191,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201, # 7920
-8202,8203,8204,8205,8206,8207,8208,8209,8210,8211,8212,8213,8214,8215,8216,8217, # 7936
-8218,8219,8220,8221,8222,8223,8224,8225,8226,8227,8228,8229,8230,8231,8232,8233, # 7952
-8234,8235,8236,8237,8238,8239,8240,8241,8242,8243,8244,8245,8246,8247,8248,8249, # 7968
-8250,8251,8252,8253,8254,8255,8256,3445,8257,8258,8259,8260,8261,8262,4458,8263, # 7984
-8264,8265,8266,8267,8268,8269,8270,8271,8272,4459,8273,8274,8275,8276,3550,8277, # 8000
-8278,8279,8280,8281,8282,8283,8284,8285,8286,8287,8288,8289,4460,8290,8291,8292, # 8016
-8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,8304,8305,8306,8307,4867, # 8032
-8308,8309,8310,8311,8312,3551,8313,8314,8315,8316,8317,8318,8319,8320,8321,8322, # 8048
-8323,8324,8325,8326,4868,8327,8328,8329,8330,8331,8332,8333,8334,8335,8336,8337, # 8064
-8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8349,8350,8351,8352,8353, # 8080
-8354,8355,8356,8357,8358,8359,8360,8361,8362,8363,4869,4461,8364,8365,8366,8367, # 8096
-8368,8369,8370,4870,8371,8372,8373,8374,8375,8376,8377,8378,8379,8380,8381,8382, # 8112
-8383,8384,8385,8386,8387,8388,8389,8390,8391,8392,8393,8394,8395,8396,8397,8398, # 8128
-8399,8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,4871,8411,8412,8413, # 8144
-8414,8415,8416,8417,8418,8419,8420,8421,8422,4462,8423,8424,8425,8426,8427,8428, # 8160
-8429,8430,8431,8432,8433,2986,8434,8435,8436,8437,8438,8439,8440,8441,8442,8443, # 8176
-8444,8445,8446,8447,8448,8449,8450,8451,8452,8453,8454,8455,8456,8457,8458,8459, # 8192
-8460,8461,8462,8463,8464,8465,8466,8467,8468,8469,8470,8471,8472,8473,8474,8475, # 8208
-8476,8477,8478,4180,8479,8480,8481,8482,8483,8484,8485,8486,8487,8488,8489,8490, # 8224
-8491,8492,8493,8494,8495,8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8506, # 8240
-8507,8508,8509,8510,8511,8512,8513,8514,8515,8516,8517,8518,8519,8520,8521,8522, # 8256
-8523,8524,8525,8526,8527,8528,8529,8530,8531,8532,8533,8534,8535,8536,8537,8538, # 8272
-8539,8540,8541,8542,8543,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554, # 8288
-8555,8556,8557,8558,8559,8560,8561,8562,8563,8564,4872,8565,8566,8567,8568,8569, # 8304
-8570,8571,8572,8573,4873,8574,8575,8576,8577,8578,8579,8580,8581,8582,8583,8584, # 8320
-8585,8586,8587,8588,8589,8590,8591,8592,8593,8594,8595,8596,8597,8598,8599,8600, # 8336
-8601,8602,8603,8604,8605,3803,8606,8607,8608,8609,8610,8611,8612,8613,4874,3804, # 8352
-8614,8615,8616,8617,8618,8619,8620,8621,3956,8622,8623,8624,8625,8626,8627,8628, # 8368
-8629,8630,8631,8632,8633,8634,8635,8636,8637,8638,2865,8639,8640,8641,8642,8643, # 8384
-8644,8645,8646,8647,8648,8649,8650,8651,8652,8653,8654,8655,8656,4463,8657,8658, # 8400
-8659,4875,4876,8660,8661,8662,8663,8664,8665,8666,8667,8668,8669,8670,8671,8672, # 8416
-8673,8674,8675,8676,8677,8678,8679,8680,8681,4464,8682,8683,8684,8685,8686,8687, # 8432
-8688,8689,8690,8691,8692,8693,8694,8695,8696,8697,8698,8699,8700,8701,8702,8703, # 8448
-8704,8705,8706,8707,8708,8709,2261,8710,8711,8712,8713,8714,8715,8716,8717,8718, # 8464
-8719,8720,8721,8722,8723,8724,8725,8726,8727,8728,8729,8730,8731,8732,8733,4181, # 8480
-8734,8735,8736,8737,8738,8739,8740,8741,8742,8743,8744,8745,8746,8747,8748,8749, # 8496
-8750,8751,8752,8753,8754,8755,8756,8757,8758,8759,8760,8761,8762,8763,4877,8764, # 8512
-8765,8766,8767,8768,8769,8770,8771,8772,8773,8774,8775,8776,8777,8778,8779,8780, # 8528
-8781,8782,8783,8784,8785,8786,8787,8788,4878,8789,4879,8790,8791,8792,4880,8793, # 8544
-8794,8795,8796,8797,8798,8799,8800,8801,4881,8802,8803,8804,8805,8806,8807,8808, # 8560
-8809,8810,8811,8812,8813,8814,8815,3957,8816,8817,8818,8819,8820,8821,8822,8823, # 8576
-8824,8825,8826,8827,8828,8829,8830,8831,8832,8833,8834,8835,8836,8837,8838,8839, # 8592
-8840,8841,8842,8843,8844,8845,8846,8847,4882,8848,8849,8850,8851,8852,8853,8854, # 8608
-8855,8856,8857,8858,8859,8860,8861,8862,8863,8864,8865,8866,8867,8868,8869,8870, # 8624
-8871,8872,8873,8874,8875,8876,8877,8878,8879,8880,8881,8882,8883,8884,3202,8885, # 8640
-8886,8887,8888,8889,8890,8891,8892,8893,8894,8895,8896,8897,8898,8899,8900,8901, # 8656
-8902,8903,8904,8905,8906,8907,8908,8909,8910,8911,8912,8913,8914,8915,8916,8917, # 8672
-8918,8919,8920,8921,8922,8923,8924,4465,8925,8926,8927,8928,8929,8930,8931,8932, # 8688
-4883,8933,8934,8935,8936,8937,8938,8939,8940,8941,8942,8943,2214,8944,8945,8946, # 8704
-8947,8948,8949,8950,8951,8952,8953,8954,8955,8956,8957,8958,8959,8960,8961,8962, # 8720
-8963,8964,8965,4884,8966,8967,8968,8969,8970,8971,8972,8973,8974,8975,8976,8977, # 8736
-8978,8979,8980,8981,8982,8983,8984,8985,8986,8987,8988,8989,8990,8991,8992,4885, # 8752
-8993,8994,8995,8996,8997,8998,8999,9000,9001,9002,9003,9004,9005,9006,9007,9008, # 8768
-9009,9010,9011,9012,9013,9014,9015,9016,9017,9018,9019,9020,9021,4182,9022,9023, # 8784
-9024,9025,9026,9027,9028,9029,9030,9031,9032,9033,9034,9035,9036,9037,9038,9039, # 8800
-9040,9041,9042,9043,9044,9045,9046,9047,9048,9049,9050,9051,9052,9053,9054,9055, # 8816
-9056,9057,9058,9059,9060,9061,9062,9063,4886,9064,9065,9066,9067,9068,9069,4887, # 8832
-9070,9071,9072,9073,9074,9075,9076,9077,9078,9079,9080,9081,9082,9083,9084,9085, # 8848
-9086,9087,9088,9089,9090,9091,9092,9093,9094,9095,9096,9097,9098,9099,9100,9101, # 8864
-9102,9103,9104,9105,9106,9107,9108,9109,9110,9111,9112,9113,9114,9115,9116,9117, # 8880
-9118,9119,9120,9121,9122,9123,9124,9125,9126,9127,9128,9129,9130,9131,9132,9133, # 8896
-9134,9135,9136,9137,9138,9139,9140,9141,3958,9142,9143,9144,9145,9146,9147,9148, # 8912
-9149,9150,9151,4888,9152,9153,9154,9155,9156,9157,9158,9159,9160,9161,9162,9163, # 8928
-9164,9165,9166,9167,9168,9169,9170,9171,9172,9173,9174,9175,4889,9176,9177,9178, # 8944
-9179,9180,9181,9182,9183,9184,9185,9186,9187,9188,9189,9190,9191,9192,9193,9194, # 8960
-9195,9196,9197,9198,9199,9200,9201,9202,9203,4890,9204,9205,9206,9207,9208,9209, # 8976
-9210,9211,9212,9213,9214,9215,9216,9217,9218,9219,9220,9221,9222,4466,9223,9224, # 8992
-9225,9226,9227,9228,9229,9230,9231,9232,9233,9234,9235,9236,9237,9238,9239,9240, # 9008
-9241,9242,9243,9244,9245,4891,9246,9247,9248,9249,9250,9251,9252,9253,9254,9255, # 9024
-9256,9257,4892,9258,9259,9260,9261,4893,4894,9262,9263,9264,9265,9266,9267,9268, # 9040
-9269,9270,9271,9272,9273,4467,9274,9275,9276,9277,9278,9279,9280,9281,9282,9283, # 9056
-9284,9285,3673,9286,9287,9288,9289,9290,9291,9292,9293,9294,9295,9296,9297,9298, # 9072
-9299,9300,9301,9302,9303,9304,9305,9306,9307,9308,9309,9310,9311,9312,9313,9314, # 9088
-9315,9316,9317,9318,9319,9320,9321,9322,4895,9323,9324,9325,9326,9327,9328,9329, # 9104
-9330,9331,9332,9333,9334,9335,9336,9337,9338,9339,9340,9341,9342,9343,9344,9345, # 9120
-9346,9347,4468,9348,9349,9350,9351,9352,9353,9354,9355,9356,9357,9358,9359,9360, # 9136
-9361,9362,9363,9364,9365,9366,9367,9368,9369,9370,9371,9372,9373,4896,9374,4469, # 9152
-9375,9376,9377,9378,9379,4897,9380,9381,9382,9383,9384,9385,9386,9387,9388,9389, # 9168
-9390,9391,9392,9393,9394,9395,9396,9397,9398,9399,9400,9401,9402,9403,9404,9405, # 9184
-9406,4470,9407,2751,9408,9409,3674,3552,9410,9411,9412,9413,9414,9415,9416,9417, # 9200
-9418,9419,9420,9421,4898,9422,9423,9424,9425,9426,9427,9428,9429,3959,9430,9431, # 9216
-9432,9433,9434,9435,9436,4471,9437,9438,9439,9440,9441,9442,9443,9444,9445,9446, # 9232
-9447,9448,9449,9450,3348,9451,9452,9453,9454,9455,9456,9457,9458,9459,9460,9461, # 9248
-9462,9463,9464,9465,9466,9467,9468,9469,9470,9471,9472,4899,9473,9474,9475,9476, # 9264
-9477,4900,9478,9479,9480,9481,9482,9483,9484,9485,9486,9487,9488,3349,9489,9490, # 9280
-9491,9492,9493,9494,9495,9496,9497,9498,9499,9500,9501,9502,9503,9504,9505,9506, # 9296
-9507,9508,9509,9510,9511,9512,9513,9514,9515,9516,9517,9518,9519,9520,4901,9521, # 9312
-9522,9523,9524,9525,9526,4902,9527,9528,9529,9530,9531,9532,9533,9534,9535,9536, # 9328
-9537,9538,9539,9540,9541,9542,9543,9544,9545,9546,9547,9548,9549,9550,9551,9552, # 9344
-9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568, # 9360
-9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9581,9582,9583,9584, # 9376
-3805,9585,9586,9587,9588,9589,9590,9591,9592,9593,9594,9595,9596,9597,9598,9599, # 9392
-9600,9601,9602,4903,9603,9604,9605,9606,9607,4904,9608,9609,9610,9611,9612,9613, # 9408
-9614,4905,9615,9616,9617,9618,9619,9620,9621,9622,9623,9624,9625,9626,9627,9628, # 9424
-9629,9630,9631,9632,4906,9633,9634,9635,9636,9637,9638,9639,9640,9641,9642,9643, # 9440
-4907,9644,9645,9646,9647,9648,9649,9650,9651,9652,9653,9654,9655,9656,9657,9658, # 9456
-9659,9660,9661,9662,9663,9664,9665,9666,9667,9668,9669,9670,9671,9672,4183,9673, # 9472
-9674,9675,9676,9677,4908,9678,9679,9680,9681,4909,9682,9683,9684,9685,9686,9687, # 9488
-9688,9689,9690,4910,9691,9692,9693,3675,9694,9695,9696,2945,9697,9698,9699,9700, # 9504
-9701,9702,9703,9704,9705,4911,9706,9707,9708,9709,9710,9711,9712,9713,9714,9715, # 9520
-9716,9717,9718,9719,9720,9721,9722,9723,9724,9725,9726,9727,9728,9729,9730,9731, # 9536
-9732,9733,9734,9735,4912,9736,9737,9738,9739,9740,4913,9741,9742,9743,9744,9745, # 9552
-9746,9747,9748,9749,9750,9751,9752,9753,9754,9755,9756,9757,9758,4914,9759,9760, # 9568
-9761,9762,9763,9764,9765,9766,9767,9768,9769,9770,9771,9772,9773,9774,9775,9776, # 9584
-9777,9778,9779,9780,9781,9782,4915,9783,9784,9785,9786,9787,9788,9789,9790,9791, # 9600
-9792,9793,4916,9794,9795,9796,9797,9798,9799,9800,9801,9802,9803,9804,9805,9806, # 9616
-9807,9808,9809,9810,9811,9812,9813,9814,9815,9816,9817,9818,9819,9820,9821,9822, # 9632
-9823,9824,9825,9826,9827,9828,9829,9830,9831,9832,9833,9834,9835,9836,9837,9838, # 9648
-9839,9840,9841,9842,9843,9844,9845,9846,9847,9848,9849,9850,9851,9852,9853,9854, # 9664
-9855,9856,9857,9858,9859,9860,9861,9862,9863,9864,9865,9866,9867,9868,4917,9869, # 9680
-9870,9871,9872,9873,9874,9875,9876,9877,9878,9879,9880,9881,9882,9883,9884,9885, # 9696
-9886,9887,9888,9889,9890,9891,9892,4472,9893,9894,9895,9896,9897,3806,9898,9899, # 9712
-9900,9901,9902,9903,9904,9905,9906,9907,9908,9909,9910,9911,9912,9913,9914,4918, # 9728
-9915,9916,9917,4919,9918,9919,9920,9921,4184,9922,9923,9924,9925,9926,9927,9928, # 9744
-9929,9930,9931,9932,9933,9934,9935,9936,9937,9938,9939,9940,9941,9942,9943,9944, # 9760
-9945,9946,4920,9947,9948,9949,9950,9951,9952,9953,9954,9955,4185,9956,9957,9958, # 9776
-9959,9960,9961,9962,9963,9964,9965,4921,9966,9967,9968,4473,9969,9970,9971,9972, # 9792
-9973,9974,9975,9976,9977,4474,9978,9979,9980,9981,9982,9983,9984,9985,9986,9987, # 9808
-9988,9989,9990,9991,9992,9993,9994,9995,9996,9997,9998,9999,10000,10001,10002,10003, # 9824
-10004,10005,10006,10007,10008,10009,10010,10011,10012,10013,10014,10015,10016,10017,10018,10019, # 9840
-10020,10021,4922,10022,4923,10023,10024,10025,10026,10027,10028,10029,10030,10031,10032,10033, # 9856
-10034,10035,10036,10037,10038,10039,10040,10041,10042,10043,10044,10045,10046,10047,10048,4924, # 9872
-10049,10050,10051,10052,10053,10054,10055,10056,10057,10058,10059,10060,10061,10062,10063,10064, # 9888
-10065,10066,10067,10068,10069,10070,10071,10072,10073,10074,10075,10076,10077,10078,10079,10080, # 9904
-10081,10082,10083,10084,10085,10086,10087,4475,10088,10089,10090,10091,10092,10093,10094,10095, # 9920
-10096,10097,4476,10098,10099,10100,10101,10102,10103,10104,10105,10106,10107,10108,10109,10110, # 9936
-10111,2174,10112,10113,10114,10115,10116,10117,10118,10119,10120,10121,10122,10123,10124,10125, # 9952
-10126,10127,10128,10129,10130,10131,10132,10133,10134,10135,10136,10137,10138,10139,10140,3807, # 9968
-4186,4925,10141,10142,10143,10144,10145,10146,10147,4477,4187,10148,10149,10150,10151,10152, # 9984
-10153,4188,10154,10155,10156,10157,10158,10159,10160,10161,4926,10162,10163,10164,10165,10166, #10000
-10167,10168,10169,10170,10171,10172,10173,10174,10175,10176,10177,10178,10179,10180,10181,10182, #10016
-10183,10184,10185,10186,10187,10188,10189,10190,10191,10192,3203,10193,10194,10195,10196,10197, #10032
-10198,10199,10200,4478,10201,10202,10203,10204,4479,10205,10206,10207,10208,10209,10210,10211, #10048
-10212,10213,10214,10215,10216,10217,10218,10219,10220,10221,10222,10223,10224,10225,10226,10227, #10064
-10228,10229,10230,10231,10232,10233,10234,4927,10235,10236,10237,10238,10239,10240,10241,10242, #10080
-10243,10244,10245,10246,10247,10248,10249,10250,10251,10252,10253,10254,10255,10256,10257,10258, #10096
-10259,10260,10261,10262,10263,10264,10265,10266,10267,10268,10269,10270,10271,10272,10273,4480, #10112
-4928,4929,10274,10275,10276,10277,10278,10279,10280,10281,10282,10283,10284,10285,10286,10287, #10128
-10288,10289,10290,10291,10292,10293,10294,10295,10296,10297,10298,10299,10300,10301,10302,10303, #10144
-10304,10305,10306,10307,10308,10309,10310,10311,10312,10313,10314,10315,10316,10317,10318,10319, #10160
-10320,10321,10322,10323,10324,10325,10326,10327,10328,10329,10330,10331,10332,10333,10334,4930, #10176
-10335,10336,10337,10338,10339,10340,10341,10342,4931,10343,10344,10345,10346,10347,10348,10349, #10192
-10350,10351,10352,10353,10354,10355,3088,10356,2786,10357,10358,10359,10360,4189,10361,10362, #10208
-10363,10364,10365,10366,10367,10368,10369,10370,10371,10372,10373,10374,10375,4932,10376,10377, #10224
-10378,10379,10380,10381,10382,10383,10384,10385,10386,10387,10388,10389,10390,10391,10392,4933, #10240
-10393,10394,10395,4934,10396,10397,10398,10399,10400,10401,10402,10403,10404,10405,10406,10407, #10256
-10408,10409,10410,10411,10412,3446,10413,10414,10415,10416,10417,10418,10419,10420,10421,10422, #10272
-10423,4935,10424,10425,10426,10427,10428,10429,10430,4936,10431,10432,10433,10434,10435,10436, #10288
-10437,10438,10439,10440,10441,10442,10443,4937,10444,10445,10446,10447,4481,10448,10449,10450, #10304
-10451,10452,10453,10454,10455,10456,10457,10458,10459,10460,10461,10462,10463,10464,10465,10466, #10320
-10467,10468,10469,10470,10471,10472,10473,10474,10475,10476,10477,10478,10479,10480,10481,10482, #10336
-10483,10484,10485,10486,10487,10488,10489,10490,10491,10492,10493,10494,10495,10496,10497,10498, #10352
-10499,10500,10501,10502,10503,10504,10505,4938,10506,10507,10508,10509,10510,2552,10511,10512, #10368
-10513,10514,10515,10516,3447,10517,10518,10519,10520,10521,10522,10523,10524,10525,10526,10527, #10384
-10528,10529,10530,10531,10532,10533,10534,10535,10536,10537,10538,10539,10540,10541,10542,10543, #10400
-4482,10544,4939,10545,10546,10547,10548,10549,10550,10551,10552,10553,10554,10555,10556,10557, #10416
-10558,10559,10560,10561,10562,10563,10564,10565,10566,10567,3676,4483,10568,10569,10570,10571, #10432
-10572,3448,10573,10574,10575,10576,10577,10578,10579,10580,10581,10582,10583,10584,10585,10586, #10448
-10587,10588,10589,10590,10591,10592,10593,10594,10595,10596,10597,10598,10599,10600,10601,10602, #10464
-10603,10604,10605,10606,10607,10608,10609,10610,10611,10612,10613,10614,10615,10616,10617,10618, #10480
-10619,10620,10621,10622,10623,10624,10625,10626,10627,4484,10628,10629,10630,10631,10632,4940, #10496
-10633,10634,10635,10636,10637,10638,10639,10640,10641,10642,10643,10644,10645,10646,10647,10648, #10512
-10649,10650,10651,10652,10653,10654,10655,10656,4941,10657,10658,10659,2599,10660,10661,10662, #10528
-10663,10664,10665,10666,3089,10667,10668,10669,10670,10671,10672,10673,10674,10675,10676,10677, #10544
-10678,10679,10680,4942,10681,10682,10683,10684,10685,10686,10687,10688,10689,10690,10691,10692, #10560
-10693,10694,10695,10696,10697,4485,10698,10699,10700,10701,10702,10703,10704,4943,10705,3677, #10576
-10706,10707,10708,10709,10710,10711,10712,4944,10713,10714,10715,10716,10717,10718,10719,10720, #10592
-10721,10722,10723,10724,10725,10726,10727,10728,4945,10729,10730,10731,10732,10733,10734,10735, #10608
-10736,10737,10738,10739,10740,10741,10742,10743,10744,10745,10746,10747,10748,10749,10750,10751, #10624
-10752,10753,10754,10755,10756,10757,10758,10759,10760,10761,4946,10762,10763,10764,10765,10766, #10640
-10767,4947,4948,10768,10769,10770,10771,10772,10773,10774,10775,10776,10777,10778,10779,10780, #10656
-10781,10782,10783,10784,10785,10786,10787,10788,10789,10790,10791,10792,10793,10794,10795,10796, #10672
-10797,10798,10799,10800,10801,10802,10803,10804,10805,10806,10807,10808,10809,10810,10811,10812, #10688
-10813,10814,10815,10816,10817,10818,10819,10820,10821,10822,10823,10824,10825,10826,10827,10828, #10704
-10829,10830,10831,10832,10833,10834,10835,10836,10837,10838,10839,10840,10841,10842,10843,10844, #10720
-10845,10846,10847,10848,10849,10850,10851,10852,10853,10854,10855,10856,10857,10858,10859,10860, #10736
-10861,10862,10863,10864,10865,10866,10867,10868,10869,10870,10871,10872,10873,10874,10875,10876, #10752
-10877,10878,4486,10879,10880,10881,10882,10883,10884,10885,4949,10886,10887,10888,10889,10890, #10768
-10891,10892,10893,10894,10895,10896,10897,10898,10899,10900,10901,10902,10903,10904,10905,10906, #10784
-10907,10908,10909,10910,10911,10912,10913,10914,10915,10916,10917,10918,10919,4487,10920,10921, #10800
-10922,10923,10924,10925,10926,10927,10928,10929,10930,10931,10932,4950,10933,10934,10935,10936, #10816
-10937,10938,10939,10940,10941,10942,10943,10944,10945,10946,10947,10948,10949,4488,10950,10951, #10832
-10952,10953,10954,10955,10956,10957,10958,10959,4190,10960,10961,10962,10963,10964,10965,10966, #10848
-10967,10968,10969,10970,10971,10972,10973,10974,10975,10976,10977,10978,10979,10980,10981,10982, #10864
-10983,10984,10985,10986,10987,10988,10989,10990,10991,10992,10993,10994,10995,10996,10997,10998, #10880
-10999,11000,11001,11002,11003,11004,11005,11006,3960,11007,11008,11009,11010,11011,11012,11013, #10896
-11014,11015,11016,11017,11018,11019,11020,11021,11022,11023,11024,11025,11026,11027,11028,11029, #10912
-11030,11031,11032,4951,11033,11034,11035,11036,11037,11038,11039,11040,11041,11042,11043,11044, #10928
-11045,11046,11047,4489,11048,11049,11050,11051,4952,11052,11053,11054,11055,11056,11057,11058, #10944
-4953,11059,11060,11061,11062,11063,11064,11065,11066,11067,11068,11069,11070,11071,4954,11072, #10960
-11073,11074,11075,11076,11077,11078,11079,11080,11081,11082,11083,11084,11085,11086,11087,11088, #10976
-11089,11090,11091,11092,11093,11094,11095,11096,11097,11098,11099,11100,11101,11102,11103,11104, #10992
-11105,11106,11107,11108,11109,11110,11111,11112,11113,11114,11115,3808,11116,11117,11118,11119, #11008
-11120,11121,11122,11123,11124,11125,11126,11127,11128,11129,11130,11131,11132,11133,11134,4955, #11024
-11135,11136,11137,11138,11139,11140,11141,11142,11143,11144,11145,11146,11147,11148,11149,11150, #11040
-11151,11152,11153,11154,11155,11156,11157,11158,11159,11160,11161,4956,11162,11163,11164,11165, #11056
-11166,11167,11168,11169,11170,11171,11172,11173,11174,11175,11176,11177,11178,11179,11180,4957, #11072
-11181,11182,11183,11184,11185,11186,4958,11187,11188,11189,11190,11191,11192,11193,11194,11195, #11088
-11196,11197,11198,11199,11200,3678,11201,11202,11203,11204,11205,11206,4191,11207,11208,11209, #11104
-11210,11211,11212,11213,11214,11215,11216,11217,11218,11219,11220,11221,11222,11223,11224,11225, #11120
-11226,11227,11228,11229,11230,11231,11232,11233,11234,11235,11236,11237,11238,11239,11240,11241, #11136
-11242,11243,11244,11245,11246,11247,11248,11249,11250,11251,4959,11252,11253,11254,11255,11256, #11152
-11257,11258,11259,11260,11261,11262,11263,11264,11265,11266,11267,11268,11269,11270,11271,11272, #11168
-11273,11274,11275,11276,11277,11278,11279,11280,11281,11282,11283,11284,11285,11286,11287,11288, #11184
-11289,11290,11291,11292,11293,11294,11295,11296,11297,11298,11299,11300,11301,11302,11303,11304, #11200
-11305,11306,11307,11308,11309,11310,11311,11312,11313,11314,3679,11315,11316,11317,11318,4490, #11216
-11319,11320,11321,11322,11323,11324,11325,11326,11327,11328,11329,11330,11331,11332,11333,11334, #11232
-11335,11336,11337,11338,11339,11340,11341,11342,11343,11344,11345,11346,11347,4960,11348,11349, #11248
-11350,11351,11352,11353,11354,11355,11356,11357,11358,11359,11360,11361,11362,11363,11364,11365, #11264
-11366,11367,11368,11369,11370,11371,11372,11373,11374,11375,11376,11377,3961,4961,11378,11379, #11280
-11380,11381,11382,11383,11384,11385,11386,11387,11388,11389,11390,11391,11392,11393,11394,11395, #11296
-11396,11397,4192,11398,11399,11400,11401,11402,11403,11404,11405,11406,11407,11408,11409,11410, #11312
-11411,4962,11412,11413,11414,11415,11416,11417,11418,11419,11420,11421,11422,11423,11424,11425, #11328
-11426,11427,11428,11429,11430,11431,11432,11433,11434,11435,11436,11437,11438,11439,11440,11441, #11344
-11442,11443,11444,11445,11446,11447,11448,11449,11450,11451,11452,11453,11454,11455,11456,11457, #11360
-11458,11459,11460,11461,11462,11463,11464,11465,11466,11467,11468,11469,4963,11470,11471,4491, #11376
-11472,11473,11474,11475,4964,11476,11477,11478,11479,11480,11481,11482,11483,11484,11485,11486, #11392
-11487,11488,11489,11490,11491,11492,4965,11493,11494,11495,11496,11497,11498,11499,11500,11501, #11408
-11502,11503,11504,11505,11506,11507,11508,11509,11510,11511,11512,11513,11514,11515,11516,11517, #11424
-11518,11519,11520,11521,11522,11523,11524,11525,11526,11527,11528,11529,3962,11530,11531,11532, #11440
-11533,11534,11535,11536,11537,11538,11539,11540,11541,11542,11543,11544,11545,11546,11547,11548, #11456
-11549,11550,11551,11552,11553,11554,11555,11556,11557,11558,11559,11560,11561,11562,11563,11564, #11472
-4193,4194,11565,11566,11567,11568,11569,11570,11571,11572,11573,11574,11575,11576,11577,11578, #11488
-11579,11580,11581,11582,11583,11584,11585,11586,11587,11588,11589,11590,11591,4966,4195,11592, #11504
-11593,11594,11595,11596,11597,11598,11599,11600,11601,11602,11603,11604,3090,11605,11606,11607, #11520
-11608,11609,11610,4967,11611,11612,11613,11614,11615,11616,11617,11618,11619,11620,11621,11622, #11536
-11623,11624,11625,11626,11627,11628,11629,11630,11631,11632,11633,11634,11635,11636,11637,11638, #11552
-11639,11640,11641,11642,11643,11644,11645,11646,11647,11648,11649,11650,11651,11652,11653,11654, #11568
-11655,11656,11657,11658,11659,11660,11661,11662,11663,11664,11665,11666,11667,11668,11669,11670, #11584
-11671,11672,11673,11674,4968,11675,11676,11677,11678,11679,11680,11681,11682,11683,11684,11685, #11600
-11686,11687,11688,11689,11690,11691,11692,11693,3809,11694,11695,11696,11697,11698,11699,11700, #11616
-11701,11702,11703,11704,11705,11706,11707,11708,11709,11710,11711,11712,11713,11714,11715,11716, #11632
-11717,11718,3553,11719,11720,11721,11722,11723,11724,11725,11726,11727,11728,11729,11730,4969, #11648
-11731,11732,11733,11734,11735,11736,11737,11738,11739,11740,4492,11741,11742,11743,11744,11745, #11664
-11746,11747,11748,11749,11750,11751,11752,4970,11753,11754,11755,11756,11757,11758,11759,11760, #11680
-11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,11776, #11696
-11777,11778,11779,11780,11781,11782,11783,11784,11785,11786,11787,11788,11789,11790,4971,11791, #11712
-11792,11793,11794,11795,11796,11797,4972,11798,11799,11800,11801,11802,11803,11804,11805,11806, #11728
-11807,11808,11809,11810,4973,11811,11812,11813,11814,11815,11816,11817,11818,11819,11820,11821, #11744
-11822,11823,11824,11825,11826,11827,11828,11829,11830,11831,11832,11833,11834,3680,3810,11835, #11760
-11836,4974,11837,11838,11839,11840,11841,11842,11843,11844,11845,11846,11847,11848,11849,11850, #11776
-11851,11852,11853,11854,11855,11856,11857,11858,11859,11860,11861,11862,11863,11864,11865,11866, #11792
-11867,11868,11869,11870,11871,11872,11873,11874,11875,11876,11877,11878,11879,11880,11881,11882, #11808
-11883,11884,4493,11885,11886,11887,11888,11889,11890,11891,11892,11893,11894,11895,11896,11897, #11824
-11898,11899,11900,11901,11902,11903,11904,11905,11906,11907,11908,11909,11910,11911,11912,11913, #11840
-11914,11915,4975,11916,11917,11918,11919,11920,11921,11922,11923,11924,11925,11926,11927,11928, #11856
-11929,11930,11931,11932,11933,11934,11935,11936,11937,11938,11939,11940,11941,11942,11943,11944, #11872
-11945,11946,11947,11948,11949,4976,11950,11951,11952,11953,11954,11955,11956,11957,11958,11959, #11888
-11960,11961,11962,11963,11964,11965,11966,11967,11968,11969,11970,11971,11972,11973,11974,11975, #11904
-11976,11977,11978,11979,11980,11981,11982,11983,11984,11985,11986,11987,4196,11988,11989,11990, #11920
-11991,11992,4977,11993,11994,11995,11996,11997,11998,11999,12000,12001,12002,12003,12004,12005, #11936
-12006,12007,12008,12009,12010,12011,12012,12013,12014,12015,12016,12017,12018,12019,12020,12021, #11952
-12022,12023,12024,12025,12026,12027,12028,12029,12030,12031,12032,12033,12034,12035,12036,12037, #11968
-12038,12039,12040,12041,12042,12043,12044,12045,12046,12047,12048,12049,12050,12051,12052,12053, #11984
-12054,12055,12056,12057,12058,12059,12060,12061,4978,12062,12063,12064,12065,12066,12067,12068, #12000
-12069,12070,12071,12072,12073,12074,12075,12076,12077,12078,12079,12080,12081,12082,12083,12084, #12016
-12085,12086,12087,12088,12089,12090,12091,12092,12093,12094,12095,12096,12097,12098,12099,12100, #12032
-12101,12102,12103,12104,12105,12106,12107,12108,12109,12110,12111,12112,12113,12114,12115,12116, #12048
-12117,12118,12119,12120,12121,12122,12123,4979,12124,12125,12126,12127,12128,4197,12129,12130, #12064
-12131,12132,12133,12134,12135,12136,12137,12138,12139,12140,12141,12142,12143,12144,12145,12146, #12080
-12147,12148,12149,12150,12151,12152,12153,12154,4980,12155,12156,12157,12158,12159,12160,4494, #12096
-12161,12162,12163,12164,3811,12165,12166,12167,12168,12169,4495,12170,12171,4496,12172,12173, #12112
-12174,12175,12176,3812,12177,12178,12179,12180,12181,12182,12183,12184,12185,12186,12187,12188, #12128
-12189,12190,12191,12192,12193,12194,12195,12196,12197,12198,12199,12200,12201,12202,12203,12204, #12144
-12205,12206,12207,12208,12209,12210,12211,12212,12213,12214,12215,12216,12217,12218,12219,12220, #12160
-12221,4981,12222,12223,12224,12225,12226,12227,12228,12229,12230,12231,12232,12233,12234,12235, #12176
-4982,12236,12237,12238,12239,12240,12241,12242,12243,12244,12245,4983,12246,12247,12248,12249, #12192
-4984,12250,12251,12252,12253,12254,12255,12256,12257,12258,12259,12260,12261,12262,12263,12264, #12208
-4985,12265,4497,12266,12267,12268,12269,12270,12271,12272,12273,12274,12275,12276,12277,12278, #12224
-12279,12280,12281,12282,12283,12284,12285,12286,12287,4986,12288,12289,12290,12291,12292,12293, #12240
-12294,12295,12296,2473,12297,12298,12299,12300,12301,12302,12303,12304,12305,12306,12307,12308, #12256
-12309,12310,12311,12312,12313,12314,12315,12316,12317,12318,12319,3963,12320,12321,12322,12323, #12272
-12324,12325,12326,12327,12328,12329,12330,12331,12332,4987,12333,12334,12335,12336,12337,12338, #12288
-12339,12340,12341,12342,12343,12344,12345,12346,12347,12348,12349,12350,12351,12352,12353,12354, #12304
-12355,12356,12357,12358,12359,3964,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369, #12320
-12370,3965,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384, #12336
-12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400, #12352
-12401,12402,12403,12404,12405,12406,12407,12408,4988,12409,12410,12411,12412,12413,12414,12415, #12368
-12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431, #12384
-12432,12433,12434,12435,12436,12437,12438,3554,12439,12440,12441,12442,12443,12444,12445,12446, #12400
-12447,12448,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462, #12416
-12463,12464,4989,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477, #12432
-12478,12479,12480,4990,12481,12482,12483,12484,12485,12486,12487,12488,12489,4498,12490,12491, #12448
-12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507, #12464
-12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523, #12480
-12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,12535,12536,12537,12538,12539, #12496
-12540,12541,12542,12543,12544,12545,12546,12547,12548,12549,12550,12551,4991,12552,12553,12554, #12512
-12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570, #12528
-12571,12572,12573,12574,12575,12576,12577,12578,3036,12579,12580,12581,12582,12583,3966,12584, #12544
-12585,12586,12587,12588,12589,12590,12591,12592,12593,12594,12595,12596,12597,12598,12599,12600, #12560
-12601,12602,12603,12604,12605,12606,12607,12608,12609,12610,12611,12612,12613,12614,12615,12616, #12576
-12617,12618,12619,12620,12621,12622,12623,12624,12625,12626,12627,12628,12629,12630,12631,12632, #12592
-12633,12634,12635,12636,12637,12638,12639,12640,12641,12642,12643,12644,12645,12646,4499,12647, #12608
-12648,12649,12650,12651,12652,12653,12654,12655,12656,12657,12658,12659,12660,12661,12662,12663, #12624
-12664,12665,12666,12667,12668,12669,12670,12671,12672,12673,12674,12675,12676,12677,12678,12679, #12640
-12680,12681,12682,12683,12684,12685,12686,12687,12688,12689,12690,12691,12692,12693,12694,12695, #12656
-12696,12697,12698,4992,12699,12700,12701,12702,12703,12704,12705,12706,12707,12708,12709,12710, #12672
-12711,12712,12713,12714,12715,12716,12717,12718,12719,12720,12721,12722,12723,12724,12725,12726, #12688
-12727,12728,12729,12730,12731,12732,12733,12734,12735,12736,12737,12738,12739,12740,12741,12742, #12704
-12743,12744,12745,12746,12747,12748,12749,12750,12751,12752,12753,12754,12755,12756,12757,12758, #12720
-12759,12760,12761,12762,12763,12764,12765,12766,12767,12768,12769,12770,12771,12772,12773,12774, #12736
-12775,12776,12777,12778,4993,2175,12779,12780,12781,12782,12783,12784,12785,12786,4500,12787, #12752
-12788,12789,12790,12791,12792,12793,12794,12795,12796,12797,12798,12799,12800,12801,12802,12803, #12768
-12804,12805,12806,12807,12808,12809,12810,12811,12812,12813,12814,12815,12816,12817,12818,12819, #12784
-12820,12821,12822,12823,12824,12825,12826,4198,3967,12827,12828,12829,12830,12831,12832,12833, #12800
-12834,12835,12836,12837,12838,12839,12840,12841,12842,12843,12844,12845,12846,12847,12848,12849, #12816
-12850,12851,12852,12853,12854,12855,12856,12857,12858,12859,12860,12861,4199,12862,12863,12864, #12832
-12865,12866,12867,12868,12869,12870,12871,12872,12873,12874,12875,12876,12877,12878,12879,12880, #12848
-12881,12882,12883,12884,12885,12886,12887,4501,12888,12889,12890,12891,12892,12893,12894,12895, #12864
-12896,12897,12898,12899,12900,12901,12902,12903,12904,12905,12906,12907,12908,12909,12910,12911, #12880
-12912,4994,12913,12914,12915,12916,12917,12918,12919,12920,12921,12922,12923,12924,12925,12926, #12896
-12927,12928,12929,12930,12931,12932,12933,12934,12935,12936,12937,12938,12939,12940,12941,12942, #12912
-12943,12944,12945,12946,12947,12948,12949,12950,12951,12952,12953,12954,12955,12956,1772,12957, #12928
-12958,12959,12960,12961,12962,12963,12964,12965,12966,12967,12968,12969,12970,12971,12972,12973, #12944
-12974,12975,12976,12977,12978,12979,12980,12981,12982,12983,12984,12985,12986,12987,12988,12989, #12960
-12990,12991,12992,12993,12994,12995,12996,12997,4502,12998,4503,12999,13000,13001,13002,13003, #12976
-4504,13004,13005,13006,13007,13008,13009,13010,13011,13012,13013,13014,13015,13016,13017,13018, #12992
-13019,13020,13021,13022,13023,13024,13025,13026,13027,13028,13029,3449,13030,13031,13032,13033, #13008
-13034,13035,13036,13037,13038,13039,13040,13041,13042,13043,13044,13045,13046,13047,13048,13049, #13024
-13050,13051,13052,13053,13054,13055,13056,13057,13058,13059,13060,13061,13062,13063,13064,13065, #13040
-13066,13067,13068,13069,13070,13071,13072,13073,13074,13075,13076,13077,13078,13079,13080,13081, #13056
-13082,13083,13084,13085,13086,13087,13088,13089,13090,13091,13092,13093,13094,13095,13096,13097, #13072
-13098,13099,13100,13101,13102,13103,13104,13105,13106,13107,13108,13109,13110,13111,13112,13113, #13088
-13114,13115,13116,13117,13118,3968,13119,4995,13120,13121,13122,13123,13124,13125,13126,13127, #13104
-4505,13128,13129,13130,13131,13132,13133,13134,4996,4506,13135,13136,13137,13138,13139,4997, #13120
-13140,13141,13142,13143,13144,13145,13146,13147,13148,13149,13150,13151,13152,13153,13154,13155, #13136
-13156,13157,13158,13159,4998,13160,13161,13162,13163,13164,13165,13166,13167,13168,13169,13170, #13152
-13171,13172,13173,13174,13175,13176,4999,13177,13178,13179,13180,13181,13182,13183,13184,13185, #13168
-13186,13187,13188,13189,13190,13191,13192,13193,13194,13195,13196,13197,13198,13199,13200,13201, #13184
-13202,13203,13204,13205,13206,5000,13207,13208,13209,13210,13211,13212,13213,13214,13215,13216, #13200
-13217,13218,13219,13220,13221,13222,13223,13224,13225,13226,13227,4200,5001,13228,13229,13230, #13216
-13231,13232,13233,13234,13235,13236,13237,13238,13239,13240,3969,13241,13242,13243,13244,3970, #13232
-13245,13246,13247,13248,13249,13250,13251,13252,13253,13254,13255,13256,13257,13258,13259,13260, #13248
-13261,13262,13263,13264,13265,13266,13267,13268,3450,13269,13270,13271,13272,13273,13274,13275, #13264
-13276,5002,13277,13278,13279,13280,13281,13282,13283,13284,13285,13286,13287,13288,13289,13290, #13280
-13291,13292,13293,13294,13295,13296,13297,13298,13299,13300,13301,13302,3813,13303,13304,13305, #13296
-13306,13307,13308,13309,13310,13311,13312,13313,13314,13315,13316,13317,13318,13319,13320,13321, #13312
-13322,13323,13324,13325,13326,13327,13328,4507,13329,13330,13331,13332,13333,13334,13335,13336, #13328
-13337,13338,13339,13340,13341,5003,13342,13343,13344,13345,13346,13347,13348,13349,13350,13351, #13344
-13352,13353,13354,13355,13356,13357,13358,13359,13360,13361,13362,13363,13364,13365,13366,13367, #13360
-5004,13368,13369,13370,13371,13372,13373,13374,13375,13376,13377,13378,13379,13380,13381,13382, #13376
-13383,13384,13385,13386,13387,13388,13389,13390,13391,13392,13393,13394,13395,13396,13397,13398, #13392
-13399,13400,13401,13402,13403,13404,13405,13406,13407,13408,13409,13410,13411,13412,13413,13414, #13408
-13415,13416,13417,13418,13419,13420,13421,13422,13423,13424,13425,13426,13427,13428,13429,13430, #13424
-13431,13432,4508,13433,13434,13435,4201,13436,13437,13438,13439,13440,13441,13442,13443,13444, #13440
-13445,13446,13447,13448,13449,13450,13451,13452,13453,13454,13455,13456,13457,5005,13458,13459, #13456
-13460,13461,13462,13463,13464,13465,13466,13467,13468,13469,13470,4509,13471,13472,13473,13474, #13472
-13475,13476,13477,13478,13479,13480,13481,13482,13483,13484,13485,13486,13487,13488,13489,13490, #13488
-13491,13492,13493,13494,13495,13496,13497,13498,13499,13500,13501,13502,13503,13504,13505,13506, #13504
-13507,13508,13509,13510,13511,13512,13513,13514,13515,13516,13517,13518,13519,13520,13521,13522, #13520
-13523,13524,13525,13526,13527,13528,13529,13530,13531,13532,13533,13534,13535,13536,13537,13538, #13536
-13539,13540,13541,13542,13543,13544,13545,13546,13547,13548,13549,13550,13551,13552,13553,13554, #13552
-13555,13556,13557,13558,13559,13560,13561,13562,13563,13564,13565,13566,13567,13568,13569,13570, #13568
-13571,13572,13573,13574,13575,13576,13577,13578,13579,13580,13581,13582,13583,13584,13585,13586, #13584
-13587,13588,13589,13590,13591,13592,13593,13594,13595,13596,13597,13598,13599,13600,13601,13602, #13600
-13603,13604,13605,13606,13607,13608,13609,13610,13611,13612,13613,13614,13615,13616,13617,13618, #13616
-13619,13620,13621,13622,13623,13624,13625,13626,13627,13628,13629,13630,13631,13632,13633,13634, #13632
-13635,13636,13637,13638,13639,13640,13641,13642,5006,13643,13644,13645,13646,13647,13648,13649, #13648
-13650,13651,5007,13652,13653,13654,13655,13656,13657,13658,13659,13660,13661,13662,13663,13664, #13664
-13665,13666,13667,13668,13669,13670,13671,13672,13673,13674,13675,13676,13677,13678,13679,13680, #13680
-13681,13682,13683,13684,13685,13686,13687,13688,13689,13690,13691,13692,13693,13694,13695,13696, #13696
-13697,13698,13699,13700,13701,13702,13703,13704,13705,13706,13707,13708,13709,13710,13711,13712, #13712
-13713,13714,13715,13716,13717,13718,13719,13720,13721,13722,13723,13724,13725,13726,13727,13728, #13728
-13729,13730,13731,13732,13733,13734,13735,13736,13737,13738,13739,13740,13741,13742,13743,13744, #13744
-13745,13746,13747,13748,13749,13750,13751,13752,13753,13754,13755,13756,13757,13758,13759,13760, #13760
-13761,13762,13763,13764,13765,13766,13767,13768,13769,13770,13771,13772,13773,13774,3273,13775, #13776
-13776,13777,13778,13779,13780,13781,13782,13783,13784,13785,13786,13787,13788,13789,13790,13791, #13792
-13792,13793,13794,13795,13796,13797,13798,13799,13800,13801,13802,13803,13804,13805,13806,13807, #13808
-13808,13809,13810,13811,13812,13813,13814,13815,13816,13817,13818,13819,13820,13821,13822,13823, #13824
-13824,13825,13826,13827,13828,13829,13830,13831,13832,13833,13834,13835,13836,13837,13838,13839, #13840
-13840,13841,13842,13843,13844,13845,13846,13847,13848,13849,13850,13851,13852,13853,13854,13855, #13856
-13856,13857,13858,13859,13860,13861,13862,13863,13864,13865,13866,13867,13868,13869,13870,13871, #13872
-13872,13873,13874,13875,13876,13877,13878,13879,13880,13881,13882,13883,13884,13885,13886,13887, #13888
-13888,13889,13890,13891,13892,13893,13894,13895,13896,13897,13898,13899,13900,13901,13902,13903, #13904
-13904,13905,13906,13907,13908,13909,13910,13911,13912,13913,13914,13915,13916,13917,13918,13919, #13920
-13920,13921,13922,13923,13924,13925,13926,13927,13928,13929,13930,13931,13932,13933,13934,13935, #13936
-13936,13937,13938,13939,13940,13941,13942,13943,13944,13945,13946,13947,13948,13949,13950,13951, #13952
-13952,13953,13954,13955,13956,13957,13958,13959,13960,13961,13962,13963,13964,13965,13966,13967, #13968
-13968,13969,13970,13971,13972) #13973
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/big5prober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/big5prober.py
deleted file mode 100644
index becce81..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/big5prober.py
+++ /dev/null
@@ -1,42 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .mbcharsetprober import MultiByteCharSetProber
-from .codingstatemachine import CodingStateMachine
-from .chardistribution import Big5DistributionAnalysis
-from .mbcssm import Big5SMModel
-
-
-class Big5Prober(MultiByteCharSetProber):
- def __init__(self):
- MultiByteCharSetProber.__init__(self)
- self._mCodingSM = CodingStateMachine(Big5SMModel)
- self._mDistributionAnalyzer = Big5DistributionAnalysis()
- self.reset()
-
- def get_charset_name(self):
- return "Big5"
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/chardistribution.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/chardistribution.py
deleted file mode 100644
index 4e64a00..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/chardistribution.py
+++ /dev/null
@@ -1,231 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .euctwfreq import (EUCTWCharToFreqOrder, EUCTW_TABLE_SIZE,
- EUCTW_TYPICAL_DISTRIBUTION_RATIO)
-from .euckrfreq import (EUCKRCharToFreqOrder, EUCKR_TABLE_SIZE,
- EUCKR_TYPICAL_DISTRIBUTION_RATIO)
-from .gb2312freq import (GB2312CharToFreqOrder, GB2312_TABLE_SIZE,
- GB2312_TYPICAL_DISTRIBUTION_RATIO)
-from .big5freq import (Big5CharToFreqOrder, BIG5_TABLE_SIZE,
- BIG5_TYPICAL_DISTRIBUTION_RATIO)
-from .jisfreq import (JISCharToFreqOrder, JIS_TABLE_SIZE,
- JIS_TYPICAL_DISTRIBUTION_RATIO)
-from .compat import wrap_ord
-
-ENOUGH_DATA_THRESHOLD = 1024
-SURE_YES = 0.99
-SURE_NO = 0.01
-MINIMUM_DATA_THRESHOLD = 3
-
-
-class CharDistributionAnalysis:
- def __init__(self):
- # Mapping table to get frequency order from char order (get from
- # GetOrder())
- self._mCharToFreqOrder = None
- self._mTableSize = None # Size of above table
- # This is a constant value which varies from language to language,
- # used in calculating confidence. See
- # http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html
- # for further detail.
- self._mTypicalDistributionRatio = None
- self.reset()
-
- def reset(self):
- """reset analyser, clear any state"""
- # If this flag is set to True, detection is done and conclusion has
- # been made
- self._mDone = False
- self._mTotalChars = 0 # Total characters encountered
- # The number of characters whose frequency order is less than 512
- self._mFreqChars = 0
-
- def feed(self, aBuf, aCharLen):
- """feed a character with known length"""
- if aCharLen == 2:
- # we only care about 2-bytes character in our distribution analysis
- order = self.get_order(aBuf)
- else:
- order = -1
- if order >= 0:
- self._mTotalChars += 1
- # order is valid
- if order < self._mTableSize:
- if 512 > self._mCharToFreqOrder[order]:
- self._mFreqChars += 1
-
- def get_confidence(self):
- """return confidence based on existing data"""
- # if we didn't receive any character in our consideration range,
- # return negative answer
- if self._mTotalChars <= 0 or self._mFreqChars <= MINIMUM_DATA_THRESHOLD:
- return SURE_NO
-
- if self._mTotalChars != self._mFreqChars:
- r = (self._mFreqChars / ((self._mTotalChars - self._mFreqChars)
- * self._mTypicalDistributionRatio))
- if r < SURE_YES:
- return r
-
- # normalize confidence (we don't want to be 100% sure)
- return SURE_YES
-
- def got_enough_data(self):
- # It is not necessary to receive all data to draw conclusion.
- # For charset detection, certain amount of data is enough
- return self._mTotalChars > ENOUGH_DATA_THRESHOLD
-
- def get_order(self, aBuf):
- # We do not handle characters based on the original encoding string,
- # but convert this encoding string to a number, here called order.
- # This allows multiple encodings of a language to share one frequency
- # table.
- return -1
-
-
-class EUCTWDistributionAnalysis(CharDistributionAnalysis):
- def __init__(self):
- CharDistributionAnalysis.__init__(self)
- self._mCharToFreqOrder = EUCTWCharToFreqOrder
- self._mTableSize = EUCTW_TABLE_SIZE
- self._mTypicalDistributionRatio = EUCTW_TYPICAL_DISTRIBUTION_RATIO
-
- def get_order(self, aBuf):
- # for euc-TW encoding, we are interested
- # first byte range: 0xc4 -- 0xfe
- # second byte range: 0xa1 -- 0xfe
- # no validation needed here. State machine has done that
- first_char = wrap_ord(aBuf[0])
- if first_char >= 0xC4:
- return 94 * (first_char - 0xC4) + wrap_ord(aBuf[1]) - 0xA1
- else:
- return -1
-
-
-class EUCKRDistributionAnalysis(CharDistributionAnalysis):
- def __init__(self):
- CharDistributionAnalysis.__init__(self)
- self._mCharToFreqOrder = EUCKRCharToFreqOrder
- self._mTableSize = EUCKR_TABLE_SIZE
- self._mTypicalDistributionRatio = EUCKR_TYPICAL_DISTRIBUTION_RATIO
-
- def get_order(self, aBuf):
- # for euc-KR encoding, we are interested
- # first byte range: 0xb0 -- 0xfe
- # second byte range: 0xa1 -- 0xfe
- # no validation needed here. State machine has done that
- first_char = wrap_ord(aBuf[0])
- if first_char >= 0xB0:
- return 94 * (first_char - 0xB0) + wrap_ord(aBuf[1]) - 0xA1
- else:
- return -1
-
-
-class GB2312DistributionAnalysis(CharDistributionAnalysis):
- def __init__(self):
- CharDistributionAnalysis.__init__(self)
- self._mCharToFreqOrder = GB2312CharToFreqOrder
- self._mTableSize = GB2312_TABLE_SIZE
- self._mTypicalDistributionRatio = GB2312_TYPICAL_DISTRIBUTION_RATIO
-
- def get_order(self, aBuf):
- # for GB2312 encoding, we are interested
- # first byte range: 0xb0 -- 0xfe
- # second byte range: 0xa1 -- 0xfe
- # no validation needed here. State machine has done that
- first_char, second_char = wrap_ord(aBuf[0]), wrap_ord(aBuf[1])
- if (first_char >= 0xB0) and (second_char >= 0xA1):
- return 94 * (first_char - 0xB0) + second_char - 0xA1
- else:
- return -1
-
-
-class Big5DistributionAnalysis(CharDistributionAnalysis):
- def __init__(self):
- CharDistributionAnalysis.__init__(self)
- self._mCharToFreqOrder = Big5CharToFreqOrder
- self._mTableSize = BIG5_TABLE_SIZE
- self._mTypicalDistributionRatio = BIG5_TYPICAL_DISTRIBUTION_RATIO
-
- def get_order(self, aBuf):
- # for big5 encoding, we are interested
- # first byte range: 0xa4 -- 0xfe
- # second byte range: 0x40 -- 0x7e , 0xa1 -- 0xfe
- # no validation needed here. State machine has done that
- first_char, second_char = wrap_ord(aBuf[0]), wrap_ord(aBuf[1])
- if first_char >= 0xA4:
- if second_char >= 0xA1:
- return 157 * (first_char - 0xA4) + second_char - 0xA1 + 63
- else:
- return 157 * (first_char - 0xA4) + second_char - 0x40
- else:
- return -1
-
-
-class SJISDistributionAnalysis(CharDistributionAnalysis):
- def __init__(self):
- CharDistributionAnalysis.__init__(self)
- self._mCharToFreqOrder = JISCharToFreqOrder
- self._mTableSize = JIS_TABLE_SIZE
- self._mTypicalDistributionRatio = JIS_TYPICAL_DISTRIBUTION_RATIO
-
- def get_order(self, aBuf):
- # for sjis encoding, we are interested
- # first byte range: 0x81 -- 0x9f , 0xe0 -- 0xfe
- # second byte range: 0x40 -- 0x7e, 0x81 -- oxfe
- # no validation needed here. State machine has done that
- first_char, second_char = wrap_ord(aBuf[0]), wrap_ord(aBuf[1])
- if (first_char >= 0x81) and (first_char <= 0x9F):
- order = 188 * (first_char - 0x81)
- elif (first_char >= 0xE0) and (first_char <= 0xEF):
- order = 188 * (first_char - 0xE0 + 31)
- else:
- return -1
- order = order + second_char - 0x40
- if second_char > 0x7F:
- order = -1
- return order
-
-
-class EUCJPDistributionAnalysis(CharDistributionAnalysis):
- def __init__(self):
- CharDistributionAnalysis.__init__(self)
- self._mCharToFreqOrder = JISCharToFreqOrder
- self._mTableSize = JIS_TABLE_SIZE
- self._mTypicalDistributionRatio = JIS_TYPICAL_DISTRIBUTION_RATIO
-
- def get_order(self, aBuf):
- # for euc-JP encoding, we are interested
- # first byte range: 0xa0 -- 0xfe
- # second byte range: 0xa1 -- 0xfe
- # no validation needed here. State machine has done that
- char = wrap_ord(aBuf[0])
- if char >= 0xA0:
- return 94 * (char - 0xA1) + wrap_ord(aBuf[1]) - 0xa1
- else:
- return -1
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/charsetgroupprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/charsetgroupprober.py
deleted file mode 100644
index 85e7a1c..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/charsetgroupprober.py
+++ /dev/null
@@ -1,106 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from . import constants
-import sys
-from .charsetprober import CharSetProber
-
-
-class CharSetGroupProber(CharSetProber):
- def __init__(self):
- CharSetProber.__init__(self)
- self._mActiveNum = 0
- self._mProbers = []
- self._mBestGuessProber = None
-
- def reset(self):
- CharSetProber.reset(self)
- self._mActiveNum = 0
- for prober in self._mProbers:
- if prober:
- prober.reset()
- prober.active = True
- self._mActiveNum += 1
- self._mBestGuessProber = None
-
- def get_charset_name(self):
- if not self._mBestGuessProber:
- self.get_confidence()
- if not self._mBestGuessProber:
- return None
-# self._mBestGuessProber = self._mProbers[0]
- return self._mBestGuessProber.get_charset_name()
-
- def feed(self, aBuf):
- for prober in self._mProbers:
- if not prober:
- continue
- if not prober.active:
- continue
- st = prober.feed(aBuf)
- if not st:
- continue
- if st == constants.eFoundIt:
- self._mBestGuessProber = prober
- return self.get_state()
- elif st == constants.eNotMe:
- prober.active = False
- self._mActiveNum -= 1
- if self._mActiveNum <= 0:
- self._mState = constants.eNotMe
- return self.get_state()
- return self.get_state()
-
- def get_confidence(self):
- st = self.get_state()
- if st == constants.eFoundIt:
- return 0.99
- elif st == constants.eNotMe:
- return 0.01
- bestConf = 0.0
- self._mBestGuessProber = None
- for prober in self._mProbers:
- if not prober:
- continue
- if not prober.active:
- if constants._debug:
- sys.stderr.write(prober.get_charset_name()
- + ' not active\n')
- continue
- cf = prober.get_confidence()
- if constants._debug:
- sys.stderr.write('%s confidence = %s\n' %
- (prober.get_charset_name(), cf))
- if bestConf < cf:
- bestConf = cf
- self._mBestGuessProber = prober
- if not self._mBestGuessProber:
- return 0.0
- return bestConf
-# else:
-# self._mBestGuessProber = self._mProbers[0]
-# return self._mBestGuessProber.get_confidence()
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/charsetprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/charsetprober.py
deleted file mode 100644
index 9758171..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/charsetprober.py
+++ /dev/null
@@ -1,62 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Universal charset detector code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-# Shy Shalom - original C code
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from . import constants
-import re
-
-
-class CharSetProber:
- def __init__(self):
- pass
-
- def reset(self):
- self._mState = constants.eDetecting
-
- def get_charset_name(self):
- return None
-
- def feed(self, aBuf):
- pass
-
- def get_state(self):
- return self._mState
-
- def get_confidence(self):
- return 0.0
-
- def filter_high_bit_only(self, aBuf):
- aBuf = re.sub(b'([\x00-\x7F])+', b' ', aBuf)
- return aBuf
-
- def filter_without_english_letters(self, aBuf):
- aBuf = re.sub(b'([A-Za-z])+', b' ', aBuf)
- return aBuf
-
- def filter_with_english_letters(self, aBuf):
- # TODO
- return aBuf
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/codingstatemachine.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/codingstatemachine.py
deleted file mode 100644
index 8dd8c91..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/codingstatemachine.py
+++ /dev/null
@@ -1,61 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .constants import eStart
-from .compat import wrap_ord
-
-
-class CodingStateMachine:
- def __init__(self, sm):
- self._mModel = sm
- self._mCurrentBytePos = 0
- self._mCurrentCharLen = 0
- self.reset()
-
- def reset(self):
- self._mCurrentState = eStart
-
- def next_state(self, c):
- # for each byte we get its class
- # if it is first byte, we also get byte length
- # PY3K: aBuf is a byte stream, so c is an int, not a byte
- byteCls = self._mModel['classTable'][wrap_ord(c)]
- if self._mCurrentState == eStart:
- self._mCurrentBytePos = 0
- self._mCurrentCharLen = self._mModel['charLenTable'][byteCls]
- # from byte's class and stateTable, we get its next state
- curr_state = (self._mCurrentState * self._mModel['classFactor']
- + byteCls)
- self._mCurrentState = self._mModel['stateTable'][curr_state]
- self._mCurrentBytePos += 1
- return self._mCurrentState
-
- def get_current_charlen(self):
- return self._mCurrentCharLen
-
- def get_coding_state_machine(self):
- return self._mModel['name']
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/compat.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/compat.py
deleted file mode 100644
index d9e30ad..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/compat.py
+++ /dev/null
@@ -1,34 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# Contributor(s):
-# Ian Cordasco - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-import sys
-
-
-if sys.version_info < (3, 0):
- base_str = (str, unicode)
-else:
- base_str = (bytes, str)
-
-
-def wrap_ord(a):
- if sys.version_info < (3, 0) and isinstance(a, base_str):
- return ord(a)
- else:
- return a
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/constants.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/constants.py
deleted file mode 100644
index e4d148b..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/constants.py
+++ /dev/null
@@ -1,39 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Universal charset detector code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-# Shy Shalom - original C code
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-_debug = 0
-
-eDetecting = 0
-eFoundIt = 1
-eNotMe = 2
-
-eStart = 0
-eError = 1
-eItsMe = 2
-
-SHORTCUT_THRESHOLD = 0.95
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/cp949prober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/cp949prober.py
deleted file mode 100644
index ff4272f..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/cp949prober.py
+++ /dev/null
@@ -1,44 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .mbcharsetprober import MultiByteCharSetProber
-from .codingstatemachine import CodingStateMachine
-from .chardistribution import EUCKRDistributionAnalysis
-from .mbcssm import CP949SMModel
-
-
-class CP949Prober(MultiByteCharSetProber):
- def __init__(self):
- MultiByteCharSetProber.__init__(self)
- self._mCodingSM = CodingStateMachine(CP949SMModel)
- # NOTE: CP949 is a superset of EUC-KR, so the distribution should be
- # not different.
- self._mDistributionAnalyzer = EUCKRDistributionAnalysis()
- self.reset()
-
- def get_charset_name(self):
- return "CP949"
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/escprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/escprober.py
deleted file mode 100644
index 80a844f..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/escprober.py
+++ /dev/null
@@ -1,86 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from . import constants
-from .escsm import (HZSMModel, ISO2022CNSMModel, ISO2022JPSMModel,
- ISO2022KRSMModel)
-from .charsetprober import CharSetProber
-from .codingstatemachine import CodingStateMachine
-from .compat import wrap_ord
-
-
-class EscCharSetProber(CharSetProber):
- def __init__(self):
- CharSetProber.__init__(self)
- self._mCodingSM = [
- CodingStateMachine(HZSMModel),
- CodingStateMachine(ISO2022CNSMModel),
- CodingStateMachine(ISO2022JPSMModel),
- CodingStateMachine(ISO2022KRSMModel)
- ]
- self.reset()
-
- def reset(self):
- CharSetProber.reset(self)
- for codingSM in self._mCodingSM:
- if not codingSM:
- continue
- codingSM.active = True
- codingSM.reset()
- self._mActiveSM = len(self._mCodingSM)
- self._mDetectedCharset = None
-
- def get_charset_name(self):
- return self._mDetectedCharset
-
- def get_confidence(self):
- if self._mDetectedCharset:
- return 0.99
- else:
- return 0.00
-
- def feed(self, aBuf):
- for c in aBuf:
- # PY3K: aBuf is a byte array, so c is an int, not a byte
- for codingSM in self._mCodingSM:
- if not codingSM:
- continue
- if not codingSM.active:
- continue
- codingState = codingSM.next_state(wrap_ord(c))
- if codingState == constants.eError:
- codingSM.active = False
- self._mActiveSM -= 1
- if self._mActiveSM <= 0:
- self._mState = constants.eNotMe
- return self.get_state()
- elif codingState == constants.eItsMe:
- self._mState = constants.eFoundIt
- self._mDetectedCharset = codingSM.get_coding_state_machine() # nopep8
- return self.get_state()
-
- return self.get_state()
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/escsm.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/escsm.py
deleted file mode 100644
index bd302b4..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/escsm.py
+++ /dev/null
@@ -1,242 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .constants import eStart, eError, eItsMe
-
-HZ_cls = (
-1,0,0,0,0,0,0,0, # 00 - 07
-0,0,0,0,0,0,0,0, # 08 - 0f
-0,0,0,0,0,0,0,0, # 10 - 17
-0,0,0,1,0,0,0,0, # 18 - 1f
-0,0,0,0,0,0,0,0, # 20 - 27
-0,0,0,0,0,0,0,0, # 28 - 2f
-0,0,0,0,0,0,0,0, # 30 - 37
-0,0,0,0,0,0,0,0, # 38 - 3f
-0,0,0,0,0,0,0,0, # 40 - 47
-0,0,0,0,0,0,0,0, # 48 - 4f
-0,0,0,0,0,0,0,0, # 50 - 57
-0,0,0,0,0,0,0,0, # 58 - 5f
-0,0,0,0,0,0,0,0, # 60 - 67
-0,0,0,0,0,0,0,0, # 68 - 6f
-0,0,0,0,0,0,0,0, # 70 - 77
-0,0,0,4,0,5,2,0, # 78 - 7f
-1,1,1,1,1,1,1,1, # 80 - 87
-1,1,1,1,1,1,1,1, # 88 - 8f
-1,1,1,1,1,1,1,1, # 90 - 97
-1,1,1,1,1,1,1,1, # 98 - 9f
-1,1,1,1,1,1,1,1, # a0 - a7
-1,1,1,1,1,1,1,1, # a8 - af
-1,1,1,1,1,1,1,1, # b0 - b7
-1,1,1,1,1,1,1,1, # b8 - bf
-1,1,1,1,1,1,1,1, # c0 - c7
-1,1,1,1,1,1,1,1, # c8 - cf
-1,1,1,1,1,1,1,1, # d0 - d7
-1,1,1,1,1,1,1,1, # d8 - df
-1,1,1,1,1,1,1,1, # e0 - e7
-1,1,1,1,1,1,1,1, # e8 - ef
-1,1,1,1,1,1,1,1, # f0 - f7
-1,1,1,1,1,1,1,1, # f8 - ff
-)
-
-HZ_st = (
-eStart,eError, 3,eStart,eStart,eStart,eError,eError,# 00-07
-eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,# 08-0f
-eItsMe,eItsMe,eError,eError,eStart,eStart, 4,eError,# 10-17
- 5,eError, 6,eError, 5, 5, 4,eError,# 18-1f
- 4,eError, 4, 4, 4,eError, 4,eError,# 20-27
- 4,eItsMe,eStart,eStart,eStart,eStart,eStart,eStart,# 28-2f
-)
-
-HZCharLenTable = (0, 0, 0, 0, 0, 0)
-
-HZSMModel = {'classTable': HZ_cls,
- 'classFactor': 6,
- 'stateTable': HZ_st,
- 'charLenTable': HZCharLenTable,
- 'name': "HZ-GB-2312"}
-
-ISO2022CN_cls = (
-2,0,0,0,0,0,0,0, # 00 - 07
-0,0,0,0,0,0,0,0, # 08 - 0f
-0,0,0,0,0,0,0,0, # 10 - 17
-0,0,0,1,0,0,0,0, # 18 - 1f
-0,0,0,0,0,0,0,0, # 20 - 27
-0,3,0,0,0,0,0,0, # 28 - 2f
-0,0,0,0,0,0,0,0, # 30 - 37
-0,0,0,0,0,0,0,0, # 38 - 3f
-0,0,0,4,0,0,0,0, # 40 - 47
-0,0,0,0,0,0,0,0, # 48 - 4f
-0,0,0,0,0,0,0,0, # 50 - 57
-0,0,0,0,0,0,0,0, # 58 - 5f
-0,0,0,0,0,0,0,0, # 60 - 67
-0,0,0,0,0,0,0,0, # 68 - 6f
-0,0,0,0,0,0,0,0, # 70 - 77
-0,0,0,0,0,0,0,0, # 78 - 7f
-2,2,2,2,2,2,2,2, # 80 - 87
-2,2,2,2,2,2,2,2, # 88 - 8f
-2,2,2,2,2,2,2,2, # 90 - 97
-2,2,2,2,2,2,2,2, # 98 - 9f
-2,2,2,2,2,2,2,2, # a0 - a7
-2,2,2,2,2,2,2,2, # a8 - af
-2,2,2,2,2,2,2,2, # b0 - b7
-2,2,2,2,2,2,2,2, # b8 - bf
-2,2,2,2,2,2,2,2, # c0 - c7
-2,2,2,2,2,2,2,2, # c8 - cf
-2,2,2,2,2,2,2,2, # d0 - d7
-2,2,2,2,2,2,2,2, # d8 - df
-2,2,2,2,2,2,2,2, # e0 - e7
-2,2,2,2,2,2,2,2, # e8 - ef
-2,2,2,2,2,2,2,2, # f0 - f7
-2,2,2,2,2,2,2,2, # f8 - ff
-)
-
-ISO2022CN_st = (
-eStart, 3,eError,eStart,eStart,eStart,eStart,eStart,# 00-07
-eStart,eError,eError,eError,eError,eError,eError,eError,# 08-0f
-eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,# 10-17
-eItsMe,eItsMe,eItsMe,eError,eError,eError, 4,eError,# 18-1f
-eError,eError,eError,eItsMe,eError,eError,eError,eError,# 20-27
- 5, 6,eError,eError,eError,eError,eError,eError,# 28-2f
-eError,eError,eError,eItsMe,eError,eError,eError,eError,# 30-37
-eError,eError,eError,eError,eError,eItsMe,eError,eStart,# 38-3f
-)
-
-ISO2022CNCharLenTable = (0, 0, 0, 0, 0, 0, 0, 0, 0)
-
-ISO2022CNSMModel = {'classTable': ISO2022CN_cls,
- 'classFactor': 9,
- 'stateTable': ISO2022CN_st,
- 'charLenTable': ISO2022CNCharLenTable,
- 'name': "ISO-2022-CN"}
-
-ISO2022JP_cls = (
-2,0,0,0,0,0,0,0, # 00 - 07
-0,0,0,0,0,0,2,2, # 08 - 0f
-0,0,0,0,0,0,0,0, # 10 - 17
-0,0,0,1,0,0,0,0, # 18 - 1f
-0,0,0,0,7,0,0,0, # 20 - 27
-3,0,0,0,0,0,0,0, # 28 - 2f
-0,0,0,0,0,0,0,0, # 30 - 37
-0,0,0,0,0,0,0,0, # 38 - 3f
-6,0,4,0,8,0,0,0, # 40 - 47
-0,9,5,0,0,0,0,0, # 48 - 4f
-0,0,0,0,0,0,0,0, # 50 - 57
-0,0,0,0,0,0,0,0, # 58 - 5f
-0,0,0,0,0,0,0,0, # 60 - 67
-0,0,0,0,0,0,0,0, # 68 - 6f
-0,0,0,0,0,0,0,0, # 70 - 77
-0,0,0,0,0,0,0,0, # 78 - 7f
-2,2,2,2,2,2,2,2, # 80 - 87
-2,2,2,2,2,2,2,2, # 88 - 8f
-2,2,2,2,2,2,2,2, # 90 - 97
-2,2,2,2,2,2,2,2, # 98 - 9f
-2,2,2,2,2,2,2,2, # a0 - a7
-2,2,2,2,2,2,2,2, # a8 - af
-2,2,2,2,2,2,2,2, # b0 - b7
-2,2,2,2,2,2,2,2, # b8 - bf
-2,2,2,2,2,2,2,2, # c0 - c7
-2,2,2,2,2,2,2,2, # c8 - cf
-2,2,2,2,2,2,2,2, # d0 - d7
-2,2,2,2,2,2,2,2, # d8 - df
-2,2,2,2,2,2,2,2, # e0 - e7
-2,2,2,2,2,2,2,2, # e8 - ef
-2,2,2,2,2,2,2,2, # f0 - f7
-2,2,2,2,2,2,2,2, # f8 - ff
-)
-
-ISO2022JP_st = (
-eStart, 3,eError,eStart,eStart,eStart,eStart,eStart,# 00-07
-eStart,eStart,eError,eError,eError,eError,eError,eError,# 08-0f
-eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,# 10-17
-eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eError,eError,# 18-1f
-eError, 5,eError,eError,eError, 4,eError,eError,# 20-27
-eError,eError,eError, 6,eItsMe,eError,eItsMe,eError,# 28-2f
-eError,eError,eError,eError,eError,eError,eItsMe,eItsMe,# 30-37
-eError,eError,eError,eItsMe,eError,eError,eError,eError,# 38-3f
-eError,eError,eError,eError,eItsMe,eError,eStart,eStart,# 40-47
-)
-
-ISO2022JPCharLenTable = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
-
-ISO2022JPSMModel = {'classTable': ISO2022JP_cls,
- 'classFactor': 10,
- 'stateTable': ISO2022JP_st,
- 'charLenTable': ISO2022JPCharLenTable,
- 'name': "ISO-2022-JP"}
-
-ISO2022KR_cls = (
-2,0,0,0,0,0,0,0, # 00 - 07
-0,0,0,0,0,0,0,0, # 08 - 0f
-0,0,0,0,0,0,0,0, # 10 - 17
-0,0,0,1,0,0,0,0, # 18 - 1f
-0,0,0,0,3,0,0,0, # 20 - 27
-0,4,0,0,0,0,0,0, # 28 - 2f
-0,0,0,0,0,0,0,0, # 30 - 37
-0,0,0,0,0,0,0,0, # 38 - 3f
-0,0,0,5,0,0,0,0, # 40 - 47
-0,0,0,0,0,0,0,0, # 48 - 4f
-0,0,0,0,0,0,0,0, # 50 - 57
-0,0,0,0,0,0,0,0, # 58 - 5f
-0,0,0,0,0,0,0,0, # 60 - 67
-0,0,0,0,0,0,0,0, # 68 - 6f
-0,0,0,0,0,0,0,0, # 70 - 77
-0,0,0,0,0,0,0,0, # 78 - 7f
-2,2,2,2,2,2,2,2, # 80 - 87
-2,2,2,2,2,2,2,2, # 88 - 8f
-2,2,2,2,2,2,2,2, # 90 - 97
-2,2,2,2,2,2,2,2, # 98 - 9f
-2,2,2,2,2,2,2,2, # a0 - a7
-2,2,2,2,2,2,2,2, # a8 - af
-2,2,2,2,2,2,2,2, # b0 - b7
-2,2,2,2,2,2,2,2, # b8 - bf
-2,2,2,2,2,2,2,2, # c0 - c7
-2,2,2,2,2,2,2,2, # c8 - cf
-2,2,2,2,2,2,2,2, # d0 - d7
-2,2,2,2,2,2,2,2, # d8 - df
-2,2,2,2,2,2,2,2, # e0 - e7
-2,2,2,2,2,2,2,2, # e8 - ef
-2,2,2,2,2,2,2,2, # f0 - f7
-2,2,2,2,2,2,2,2, # f8 - ff
-)
-
-ISO2022KR_st = (
-eStart, 3,eError,eStart,eStart,eStart,eError,eError,# 00-07
-eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,# 08-0f
-eItsMe,eItsMe,eError,eError,eError, 4,eError,eError,# 10-17
-eError,eError,eError,eError, 5,eError,eError,eError,# 18-1f
-eError,eError,eError,eItsMe,eStart,eStart,eStart,eStart,# 20-27
-)
-
-ISO2022KRCharLenTable = (0, 0, 0, 0, 0, 0)
-
-ISO2022KRSMModel = {'classTable': ISO2022KR_cls,
- 'classFactor': 6,
- 'stateTable': ISO2022KR_st,
- 'charLenTable': ISO2022KRCharLenTable,
- 'name': "ISO-2022-KR"}
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/eucjpprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/eucjpprober.py
deleted file mode 100644
index 8e64fdc..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/eucjpprober.py
+++ /dev/null
@@ -1,90 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-import sys
-from . import constants
-from .mbcharsetprober import MultiByteCharSetProber
-from .codingstatemachine import CodingStateMachine
-from .chardistribution import EUCJPDistributionAnalysis
-from .jpcntx import EUCJPContextAnalysis
-from .mbcssm import EUCJPSMModel
-
-
-class EUCJPProber(MultiByteCharSetProber):
- def __init__(self):
- MultiByteCharSetProber.__init__(self)
- self._mCodingSM = CodingStateMachine(EUCJPSMModel)
- self._mDistributionAnalyzer = EUCJPDistributionAnalysis()
- self._mContextAnalyzer = EUCJPContextAnalysis()
- self.reset()
-
- def reset(self):
- MultiByteCharSetProber.reset(self)
- self._mContextAnalyzer.reset()
-
- def get_charset_name(self):
- return "EUC-JP"
-
- def feed(self, aBuf):
- aLen = len(aBuf)
- for i in range(0, aLen):
- # PY3K: aBuf is a byte array, so aBuf[i] is an int, not a byte
- codingState = self._mCodingSM.next_state(aBuf[i])
- if codingState == constants.eError:
- if constants._debug:
- sys.stderr.write(self.get_charset_name()
- + ' prober hit error at byte ' + str(i)
- + '\n')
- self._mState = constants.eNotMe
- break
- elif codingState == constants.eItsMe:
- self._mState = constants.eFoundIt
- break
- elif codingState == constants.eStart:
- charLen = self._mCodingSM.get_current_charlen()
- if i == 0:
- self._mLastChar[1] = aBuf[0]
- self._mContextAnalyzer.feed(self._mLastChar, charLen)
- self._mDistributionAnalyzer.feed(self._mLastChar, charLen)
- else:
- self._mContextAnalyzer.feed(aBuf[i - 1:i + 1], charLen)
- self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1],
- charLen)
-
- self._mLastChar[0] = aBuf[aLen - 1]
-
- if self.get_state() == constants.eDetecting:
- if (self._mContextAnalyzer.got_enough_data() and
- (self.get_confidence() > constants.SHORTCUT_THRESHOLD)):
- self._mState = constants.eFoundIt
-
- return self.get_state()
-
- def get_confidence(self):
- contxtCf = self._mContextAnalyzer.get_confidence()
- distribCf = self._mDistributionAnalyzer.get_confidence()
- return max(contxtCf, distribCf)
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euckrfreq.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euckrfreq.py
deleted file mode 100644
index a179e4c..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euckrfreq.py
+++ /dev/null
@@ -1,596 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# Sampling from about 20M text materials include literature and computer technology
-
-# 128 --> 0.79
-# 256 --> 0.92
-# 512 --> 0.986
-# 1024 --> 0.99944
-# 2048 --> 0.99999
-#
-# Idea Distribution Ratio = 0.98653 / (1-0.98653) = 73.24
-# Random Distribution Ration = 512 / (2350-512) = 0.279.
-#
-# Typical Distribution Ratio
-
-EUCKR_TYPICAL_DISTRIBUTION_RATIO = 6.0
-
-EUCKR_TABLE_SIZE = 2352
-
-# Char to FreqOrder table ,
-EUCKRCharToFreqOrder = ( \
- 13, 130, 120,1396, 481,1719,1720, 328, 609, 212,1721, 707, 400, 299,1722, 87,
-1397,1723, 104, 536,1117,1203,1724,1267, 685,1268, 508,1725,1726,1727,1728,1398,
-1399,1729,1730,1731, 141, 621, 326,1057, 368,1732, 267, 488, 20,1733,1269,1734,
- 945,1400,1735, 47, 904,1270,1736,1737, 773, 248,1738, 409, 313, 786, 429,1739,
- 116, 987, 813,1401, 683, 75,1204, 145,1740,1741,1742,1743, 16, 847, 667, 622,
- 708,1744,1745,1746, 966, 787, 304, 129,1747, 60, 820, 123, 676,1748,1749,1750,
-1751, 617,1752, 626,1753,1754,1755,1756, 653,1757,1758,1759,1760,1761,1762, 856,
- 344,1763,1764,1765,1766, 89, 401, 418, 806, 905, 848,1767,1768,1769, 946,1205,
- 709,1770,1118,1771, 241,1772,1773,1774,1271,1775, 569,1776, 999,1777,1778,1779,
-1780, 337, 751,1058, 28, 628, 254,1781, 177, 906, 270, 349, 891,1079,1782, 19,
-1783, 379,1784, 315,1785, 629, 754,1402, 559,1786, 636, 203,1206,1787, 710, 567,
-1788, 935, 814,1789,1790,1207, 766, 528,1791,1792,1208,1793,1794,1795,1796,1797,
-1403,1798,1799, 533,1059,1404,1405,1156,1406, 936, 884,1080,1800, 351,1801,1802,
-1803,1804,1805, 801,1806,1807,1808,1119,1809,1157, 714, 474,1407,1810, 298, 899,
- 885,1811,1120, 802,1158,1812, 892,1813,1814,1408, 659,1815,1816,1121,1817,1818,
-1819,1820,1821,1822, 319,1823, 594, 545,1824, 815, 937,1209,1825,1826, 573,1409,
-1022,1827,1210,1828,1829,1830,1831,1832,1833, 556, 722, 807,1122,1060,1834, 697,
-1835, 900, 557, 715,1836,1410, 540,1411, 752,1159, 294, 597,1211, 976, 803, 770,
-1412,1837,1838, 39, 794,1413, 358,1839, 371, 925,1840, 453, 661, 788, 531, 723,
- 544,1023,1081, 869, 91,1841, 392, 430, 790, 602,1414, 677,1082, 457,1415,1416,
-1842,1843, 475, 327,1024,1417, 795, 121,1844, 733, 403,1418,1845,1846,1847, 300,
- 119, 711,1212, 627,1848,1272, 207,1849,1850, 796,1213, 382,1851, 519,1852,1083,
- 893,1853,1854,1855, 367, 809, 487, 671,1856, 663,1857,1858, 956, 471, 306, 857,
-1859,1860,1160,1084,1861,1862,1863,1864,1865,1061,1866,1867,1868,1869,1870,1871,
- 282, 96, 574,1872, 502,1085,1873,1214,1874, 907,1875,1876, 827, 977,1419,1420,
-1421, 268,1877,1422,1878,1879,1880, 308,1881, 2, 537,1882,1883,1215,1884,1885,
- 127, 791,1886,1273,1423,1887, 34, 336, 404, 643,1888, 571, 654, 894, 840,1889,
- 0, 886,1274, 122, 575, 260, 908, 938,1890,1275, 410, 316,1891,1892, 100,1893,
-1894,1123, 48,1161,1124,1025,1895, 633, 901,1276,1896,1897, 115, 816,1898, 317,
-1899, 694,1900, 909, 734,1424, 572, 866,1425, 691, 85, 524,1010, 543, 394, 841,
-1901,1902,1903,1026,1904,1905,1906,1907,1908,1909, 30, 451, 651, 988, 310,1910,
-1911,1426, 810,1216, 93,1912,1913,1277,1217,1914, 858, 759, 45, 58, 181, 610,
- 269,1915,1916, 131,1062, 551, 443,1000, 821,1427, 957, 895,1086,1917,1918, 375,
-1919, 359,1920, 687,1921, 822,1922, 293,1923,1924, 40, 662, 118, 692, 29, 939,
- 887, 640, 482, 174,1925, 69,1162, 728,1428, 910,1926,1278,1218,1279, 386, 870,
- 217, 854,1163, 823,1927,1928,1929,1930, 834,1931, 78,1932, 859,1933,1063,1934,
-1935,1936,1937, 438,1164, 208, 595,1938,1939,1940,1941,1219,1125,1942, 280, 888,
-1429,1430,1220,1431,1943,1944,1945,1946,1947,1280, 150, 510,1432,1948,1949,1950,
-1951,1952,1953,1954,1011,1087,1955,1433,1043,1956, 881,1957, 614, 958,1064,1065,
-1221,1958, 638,1001, 860, 967, 896,1434, 989, 492, 553,1281,1165,1959,1282,1002,
-1283,1222,1960,1961,1962,1963, 36, 383, 228, 753, 247, 454,1964, 876, 678,1965,
-1966,1284, 126, 464, 490, 835, 136, 672, 529, 940,1088,1435, 473,1967,1968, 467,
- 50, 390, 227, 587, 279, 378, 598, 792, 968, 240, 151, 160, 849, 882,1126,1285,
- 639,1044, 133, 140, 288, 360, 811, 563,1027, 561, 142, 523,1969,1970,1971, 7,
- 103, 296, 439, 407, 506, 634, 990,1972,1973,1974,1975, 645,1976,1977,1978,1979,
-1980,1981, 236,1982,1436,1983,1984,1089, 192, 828, 618, 518,1166, 333,1127,1985,
- 818,1223,1986,1987,1988,1989,1990,1991,1992,1993, 342,1128,1286, 746, 842,1994,
-1995, 560, 223,1287, 98, 8, 189, 650, 978,1288,1996,1437,1997, 17, 345, 250,
- 423, 277, 234, 512, 226, 97, 289, 42, 167,1998, 201,1999,2000, 843, 836, 824,
- 532, 338, 783,1090, 182, 576, 436,1438,1439, 527, 500,2001, 947, 889,2002,2003,
-2004,2005, 262, 600, 314, 447,2006, 547,2007, 693, 738,1129,2008, 71,1440, 745,
- 619, 688,2009, 829,2010,2011, 147,2012, 33, 948,2013,2014, 74, 224,2015, 61,
- 191, 918, 399, 637,2016,1028,1130, 257, 902,2017,2018,2019,2020,2021,2022,2023,
-2024,2025,2026, 837,2027,2028,2029,2030, 179, 874, 591, 52, 724, 246,2031,2032,
-2033,2034,1167, 969,2035,1289, 630, 605, 911,1091,1168,2036,2037,2038,1441, 912,
-2039, 623,2040,2041, 253,1169,1290,2042,1442, 146, 620, 611, 577, 433,2043,1224,
- 719,1170, 959, 440, 437, 534, 84, 388, 480,1131, 159, 220, 198, 679,2044,1012,
- 819,1066,1443, 113,1225, 194, 318,1003,1029,2045,2046,2047,2048,1067,2049,2050,
-2051,2052,2053, 59, 913, 112,2054, 632,2055, 455, 144, 739,1291,2056, 273, 681,
- 499,2057, 448,2058,2059, 760,2060,2061, 970, 384, 169, 245,1132,2062,2063, 414,
-1444,2064,2065, 41, 235,2066, 157, 252, 877, 568, 919, 789, 580,2067, 725,2068,
-2069,1292,2070,2071,1445,2072,1446,2073,2074, 55, 588, 66,1447, 271,1092,2075,
-1226,2076, 960,1013, 372,2077,2078,2079,2080,2081,1293,2082,2083,2084,2085, 850,
-2086,2087,2088,2089,2090, 186,2091,1068, 180,2092,2093,2094, 109,1227, 522, 606,
-2095, 867,1448,1093, 991,1171, 926, 353,1133,2096, 581,2097,2098,2099,1294,1449,
-1450,2100, 596,1172,1014,1228,2101,1451,1295,1173,1229,2102,2103,1296,1134,1452,
- 949,1135,2104,2105,1094,1453,1454,1455,2106,1095,2107,2108,2109,2110,2111,2112,
-2113,2114,2115,2116,2117, 804,2118,2119,1230,1231, 805,1456, 405,1136,2120,2121,
-2122,2123,2124, 720, 701,1297, 992,1457, 927,1004,2125,2126,2127,2128,2129,2130,
- 22, 417,2131, 303,2132, 385,2133, 971, 520, 513,2134,1174, 73,1096, 231, 274,
- 962,1458, 673,2135,1459,2136, 152,1137,2137,2138,2139,2140,1005,1138,1460,1139,
-2141,2142,2143,2144, 11, 374, 844,2145, 154,1232, 46,1461,2146, 838, 830, 721,
-1233, 106,2147, 90, 428, 462, 578, 566,1175, 352,2148,2149, 538,1234, 124,1298,
-2150,1462, 761, 565,2151, 686,2152, 649,2153, 72, 173,2154, 460, 415,2155,1463,
-2156,1235, 305,2157,2158,2159,2160,2161,2162, 579,2163,2164,2165,2166,2167, 747,
-2168,2169,2170,2171,1464, 669,2172,2173,2174,2175,2176,1465,2177, 23, 530, 285,
-2178, 335, 729,2179, 397,2180,2181,2182,1030,2183,2184, 698,2185,2186, 325,2187,
-2188, 369,2189, 799,1097,1015, 348,2190,1069, 680,2191, 851,1466,2192,2193, 10,
-2194, 613, 424,2195, 979, 108, 449, 589, 27, 172, 81,1031, 80, 774, 281, 350,
-1032, 525, 301, 582,1176,2196, 674,1045,2197,2198,1467, 730, 762,2199,2200,2201,
-2202,1468,2203, 993,2204,2205, 266,1070, 963,1140,2206,2207,2208, 664,1098, 972,
-2209,2210,2211,1177,1469,1470, 871,2212,2213,2214,2215,2216,1471,2217,2218,2219,
-2220,2221,2222,2223,2224,2225,2226,2227,1472,1236,2228,2229,2230,2231,2232,2233,
-2234,2235,1299,2236,2237, 200,2238, 477, 373,2239,2240, 731, 825, 777,2241,2242,
-2243, 521, 486, 548,2244,2245,2246,1473,1300, 53, 549, 137, 875, 76, 158,2247,
-1301,1474, 469, 396,1016, 278, 712,2248, 321, 442, 503, 767, 744, 941,1237,1178,
-1475,2249, 82, 178,1141,1179, 973,2250,1302,2251, 297,2252,2253, 570,2254,2255,
-2256, 18, 450, 206,2257, 290, 292,1142,2258, 511, 162, 99, 346, 164, 735,2259,
-1476,1477, 4, 554, 343, 798,1099,2260,1100,2261, 43, 171,1303, 139, 215,2262,
-2263, 717, 775,2264,1033, 322, 216,2265, 831,2266, 149,2267,1304,2268,2269, 702,
-1238, 135, 845, 347, 309,2270, 484,2271, 878, 655, 238,1006,1478,2272, 67,2273,
- 295,2274,2275, 461,2276, 478, 942, 412,2277,1034,2278,2279,2280, 265,2281, 541,
-2282,2283,2284,2285,2286, 70, 852,1071,2287,2288,2289,2290, 21, 56, 509, 117,
- 432,2291,2292, 331, 980, 552,1101, 148, 284, 105, 393,1180,1239, 755,2293, 187,
-2294,1046,1479,2295, 340,2296, 63,1047, 230,2297,2298,1305, 763,1306, 101, 800,
- 808, 494,2299,2300,2301, 903,2302, 37,1072, 14, 5,2303, 79, 675,2304, 312,
-2305,2306,2307,2308,2309,1480, 6,1307,2310,2311,2312, 1, 470, 35, 24, 229,
-2313, 695, 210, 86, 778, 15, 784, 592, 779, 32, 77, 855, 964,2314, 259,2315,
- 501, 380,2316,2317, 83, 981, 153, 689,1308,1481,1482,1483,2318,2319, 716,1484,
-2320,2321,2322,2323,2324,2325,1485,2326,2327, 128, 57, 68, 261,1048, 211, 170,
-1240, 31,2328, 51, 435, 742,2329,2330,2331, 635,2332, 264, 456,2333,2334,2335,
- 425,2336,1486, 143, 507, 263, 943,2337, 363, 920,1487, 256,1488,1102, 243, 601,
-1489,2338,2339,2340,2341,2342,2343,2344, 861,2345,2346,2347,2348,2349,2350, 395,
-2351,1490,1491, 62, 535, 166, 225,2352,2353, 668, 419,1241, 138, 604, 928,2354,
-1181,2355,1492,1493,2356,2357,2358,1143,2359, 696,2360, 387, 307,1309, 682, 476,
-2361,2362, 332, 12, 222, 156,2363, 232,2364, 641, 276, 656, 517,1494,1495,1035,
- 416, 736,1496,2365,1017, 586,2366,2367,2368,1497,2369, 242,2370,2371,2372,1498,
-2373, 965, 713,2374,2375,2376,2377, 740, 982,1499, 944,1500,1007,2378,2379,1310,
-1501,2380,2381,2382, 785, 329,2383,2384,1502,2385,2386,2387, 932,2388,1503,2389,
-2390,2391,2392,1242,2393,2394,2395,2396,2397, 994, 950,2398,2399,2400,2401,1504,
-1311,2402,2403,2404,2405,1049, 749,2406,2407, 853, 718,1144,1312,2408,1182,1505,
-2409,2410, 255, 516, 479, 564, 550, 214,1506,1507,1313, 413, 239, 444, 339,1145,
-1036,1508,1509,1314,1037,1510,1315,2411,1511,2412,2413,2414, 176, 703, 497, 624,
- 593, 921, 302,2415, 341, 165,1103,1512,2416,1513,2417,2418,2419, 376,2420, 700,
-2421,2422,2423, 258, 768,1316,2424,1183,2425, 995, 608,2426,2427,2428,2429, 221,
-2430,2431,2432,2433,2434,2435,2436,2437, 195, 323, 726, 188, 897, 983,1317, 377,
- 644,1050, 879,2438, 452,2439,2440,2441,2442,2443,2444, 914,2445,2446,2447,2448,
- 915, 489,2449,1514,1184,2450,2451, 515, 64, 427, 495,2452, 583,2453, 483, 485,
-1038, 562, 213,1515, 748, 666,2454,2455,2456,2457, 334,2458, 780, 996,1008, 705,
-1243,2459,2460,2461,2462,2463, 114,2464, 493,1146, 366, 163,1516, 961,1104,2465,
- 291,2466,1318,1105,2467,1517, 365,2468, 355, 951,1244,2469,1319,2470, 631,2471,
-2472, 218,1320, 364, 320, 756,1518,1519,1321,1520,1322,2473,2474,2475,2476, 997,
-2477,2478,2479,2480, 665,1185,2481, 916,1521,2482,2483,2484, 584, 684,2485,2486,
- 797,2487,1051,1186,2488,2489,2490,1522,2491,2492, 370,2493,1039,1187, 65,2494,
- 434, 205, 463,1188,2495, 125, 812, 391, 402, 826, 699, 286, 398, 155, 781, 771,
- 585,2496, 590, 505,1073,2497, 599, 244, 219, 917,1018, 952, 646,1523,2498,1323,
-2499,2500, 49, 984, 354, 741,2501, 625,2502,1324,2503,1019, 190, 357, 757, 491,
- 95, 782, 868,2504,2505,2506,2507,2508,2509, 134,1524,1074, 422,1525, 898,2510,
- 161,2511,2512,2513,2514, 769,2515,1526,2516,2517, 411,1325,2518, 472,1527,2519,
-2520,2521,2522,2523,2524, 985,2525,2526,2527,2528,2529,2530, 764,2531,1245,2532,
-2533, 25, 204, 311,2534, 496,2535,1052,2536,2537,2538,2539,2540,2541,2542, 199,
- 704, 504, 468, 758, 657,1528, 196, 44, 839,1246, 272, 750,2543, 765, 862,2544,
-2545,1326,2546, 132, 615, 933,2547, 732,2548,2549,2550,1189,1529,2551, 283,1247,
-1053, 607, 929,2552,2553,2554, 930, 183, 872, 616,1040,1147,2555,1148,1020, 441,
- 249,1075,2556,2557,2558, 466, 743,2559,2560,2561, 92, 514, 426, 420, 526,2562,
-2563,2564,2565,2566,2567,2568, 185,2569,2570,2571,2572, 776,1530, 658,2573, 362,
-2574, 361, 922,1076, 793,2575,2576,2577,2578,2579,2580,1531, 251,2581,2582,2583,
-2584,1532, 54, 612, 237,1327,2585,2586, 275, 408, 647, 111,2587,1533,1106, 465,
- 3, 458, 9, 38,2588, 107, 110, 890, 209, 26, 737, 498,2589,1534,2590, 431,
- 202, 88,1535, 356, 287,1107, 660,1149,2591, 381,1536, 986,1150, 445,1248,1151,
- 974,2592,2593, 846,2594, 446, 953, 184,1249,1250, 727,2595, 923, 193, 883,2596,
-2597,2598, 102, 324, 539, 817,2599, 421,1041,2600, 832,2601, 94, 175, 197, 406,
-2602, 459,2603,2604,2605,2606,2607, 330, 555,2608,2609,2610, 706,1108, 389,2611,
-2612,2613,2614, 233,2615, 833, 558, 931, 954,1251,2616,2617,1537, 546,2618,2619,
-1009,2620,2621,2622,1538, 690,1328,2623, 955,2624,1539,2625,2626, 772,2627,2628,
-2629,2630,2631, 924, 648, 863, 603,2632,2633, 934,1540, 864, 865,2634, 642,1042,
- 670,1190,2635,2636,2637,2638, 168,2639, 652, 873, 542,1054,1541,2640,2641,2642, # 512, 256
-#Everything below is of no interest for detection purpose
-2643,2644,2645,2646,2647,2648,2649,2650,2651,2652,2653,2654,2655,2656,2657,2658,
-2659,2660,2661,2662,2663,2664,2665,2666,2667,2668,2669,2670,2671,2672,2673,2674,
-2675,2676,2677,2678,2679,2680,2681,2682,2683,2684,2685,2686,2687,2688,2689,2690,
-2691,2692,2693,2694,2695,2696,2697,2698,2699,1542, 880,2700,2701,2702,2703,2704,
-2705,2706,2707,2708,2709,2710,2711,2712,2713,2714,2715,2716,2717,2718,2719,2720,
-2721,2722,2723,2724,2725,1543,2726,2727,2728,2729,2730,2731,2732,1544,2733,2734,
-2735,2736,2737,2738,2739,2740,2741,2742,2743,2744,2745,2746,2747,2748,2749,2750,
-2751,2752,2753,2754,1545,2755,2756,2757,2758,2759,2760,2761,2762,2763,2764,2765,
-2766,1546,2767,1547,2768,2769,2770,2771,2772,2773,2774,2775,2776,2777,2778,2779,
-2780,2781,2782,2783,2784,2785,2786,1548,2787,2788,2789,1109,2790,2791,2792,2793,
-2794,2795,2796,2797,2798,2799,2800,2801,2802,2803,2804,2805,2806,2807,2808,2809,
-2810,2811,2812,1329,2813,2814,2815,2816,2817,2818,2819,2820,2821,2822,2823,2824,
-2825,2826,2827,2828,2829,2830,2831,2832,2833,2834,2835,2836,2837,2838,2839,2840,
-2841,2842,2843,2844,2845,2846,2847,2848,2849,2850,2851,2852,2853,2854,2855,2856,
-1549,2857,2858,2859,2860,1550,2861,2862,1551,2863,2864,2865,2866,2867,2868,2869,
-2870,2871,2872,2873,2874,1110,1330,2875,2876,2877,2878,2879,2880,2881,2882,2883,
-2884,2885,2886,2887,2888,2889,2890,2891,2892,2893,2894,2895,2896,2897,2898,2899,
-2900,2901,2902,2903,2904,2905,2906,2907,2908,2909,2910,2911,2912,2913,2914,2915,
-2916,2917,2918,2919,2920,2921,2922,2923,2924,2925,2926,2927,2928,2929,2930,1331,
-2931,2932,2933,2934,2935,2936,2937,2938,2939,2940,2941,2942,2943,1552,2944,2945,
-2946,2947,2948,2949,2950,2951,2952,2953,2954,2955,2956,2957,2958,2959,2960,2961,
-2962,2963,2964,1252,2965,2966,2967,2968,2969,2970,2971,2972,2973,2974,2975,2976,
-2977,2978,2979,2980,2981,2982,2983,2984,2985,2986,2987,2988,2989,2990,2991,2992,
-2993,2994,2995,2996,2997,2998,2999,3000,3001,3002,3003,3004,3005,3006,3007,3008,
-3009,3010,3011,3012,1553,3013,3014,3015,3016,3017,1554,3018,1332,3019,3020,3021,
-3022,3023,3024,3025,3026,3027,3028,3029,3030,3031,3032,3033,3034,3035,3036,3037,
-3038,3039,3040,3041,3042,3043,3044,3045,3046,3047,3048,3049,3050,1555,3051,3052,
-3053,1556,1557,3054,3055,3056,3057,3058,3059,3060,3061,3062,3063,3064,3065,3066,
-3067,1558,3068,3069,3070,3071,3072,3073,3074,3075,3076,1559,3077,3078,3079,3080,
-3081,3082,3083,1253,3084,3085,3086,3087,3088,3089,3090,3091,3092,3093,3094,3095,
-3096,3097,3098,3099,3100,3101,3102,3103,3104,3105,3106,3107,3108,1152,3109,3110,
-3111,3112,3113,1560,3114,3115,3116,3117,1111,3118,3119,3120,3121,3122,3123,3124,
-3125,3126,3127,3128,3129,3130,3131,3132,3133,3134,3135,3136,3137,3138,3139,3140,
-3141,3142,3143,3144,3145,3146,3147,3148,3149,3150,3151,3152,3153,3154,3155,3156,
-3157,3158,3159,3160,3161,3162,3163,3164,3165,3166,3167,3168,3169,3170,3171,3172,
-3173,3174,3175,3176,1333,3177,3178,3179,3180,3181,3182,3183,3184,3185,3186,3187,
-3188,3189,1561,3190,3191,1334,3192,3193,3194,3195,3196,3197,3198,3199,3200,3201,
-3202,3203,3204,3205,3206,3207,3208,3209,3210,3211,3212,3213,3214,3215,3216,3217,
-3218,3219,3220,3221,3222,3223,3224,3225,3226,3227,3228,3229,3230,3231,3232,3233,
-3234,1562,3235,3236,3237,3238,3239,3240,3241,3242,3243,3244,3245,3246,3247,3248,
-3249,3250,3251,3252,3253,3254,3255,3256,3257,3258,3259,3260,3261,3262,3263,3264,
-3265,3266,3267,3268,3269,3270,3271,3272,3273,3274,3275,3276,3277,1563,3278,3279,
-3280,3281,3282,3283,3284,3285,3286,3287,3288,3289,3290,3291,3292,3293,3294,3295,
-3296,3297,3298,3299,3300,3301,3302,3303,3304,3305,3306,3307,3308,3309,3310,3311,
-3312,3313,3314,3315,3316,3317,3318,3319,3320,3321,3322,3323,3324,3325,3326,3327,
-3328,3329,3330,3331,3332,3333,3334,3335,3336,3337,3338,3339,3340,3341,3342,3343,
-3344,3345,3346,3347,3348,3349,3350,3351,3352,3353,3354,3355,3356,3357,3358,3359,
-3360,3361,3362,3363,3364,1335,3365,3366,3367,3368,3369,3370,3371,3372,3373,3374,
-3375,3376,3377,3378,3379,3380,3381,3382,3383,3384,3385,3386,3387,1336,3388,3389,
-3390,3391,3392,3393,3394,3395,3396,3397,3398,3399,3400,3401,3402,3403,3404,3405,
-3406,3407,3408,3409,3410,3411,3412,3413,3414,1337,3415,3416,3417,3418,3419,1338,
-3420,3421,3422,1564,1565,3423,3424,3425,3426,3427,3428,3429,3430,3431,1254,3432,
-3433,3434,1339,3435,3436,3437,3438,3439,1566,3440,3441,3442,3443,3444,3445,3446,
-3447,3448,3449,3450,3451,3452,3453,3454,1255,3455,3456,3457,3458,3459,1567,1191,
-3460,1568,1569,3461,3462,3463,1570,3464,3465,3466,3467,3468,1571,3469,3470,3471,
-3472,3473,1572,3474,3475,3476,3477,3478,3479,3480,3481,3482,3483,3484,3485,3486,
-1340,3487,3488,3489,3490,3491,3492,1021,3493,3494,3495,3496,3497,3498,1573,3499,
-1341,3500,3501,3502,3503,3504,3505,3506,3507,3508,3509,3510,3511,1342,3512,3513,
-3514,3515,3516,1574,1343,3517,3518,3519,1575,3520,1576,3521,3522,3523,3524,3525,
-3526,3527,3528,3529,3530,3531,3532,3533,3534,3535,3536,3537,3538,3539,3540,3541,
-3542,3543,3544,3545,3546,3547,3548,3549,3550,3551,3552,3553,3554,3555,3556,3557,
-3558,3559,3560,3561,3562,3563,3564,3565,3566,3567,3568,3569,3570,3571,3572,3573,
-3574,3575,3576,3577,3578,3579,3580,1577,3581,3582,1578,3583,3584,3585,3586,3587,
-3588,3589,3590,3591,3592,3593,3594,3595,3596,3597,3598,3599,3600,3601,3602,3603,
-3604,1579,3605,3606,3607,3608,3609,3610,3611,3612,3613,3614,3615,3616,3617,3618,
-3619,3620,3621,3622,3623,3624,3625,3626,3627,3628,3629,1580,3630,3631,1581,3632,
-3633,3634,3635,3636,3637,3638,3639,3640,3641,3642,3643,3644,3645,3646,3647,3648,
-3649,3650,3651,3652,3653,3654,3655,3656,1582,3657,3658,3659,3660,3661,3662,3663,
-3664,3665,3666,3667,3668,3669,3670,3671,3672,3673,3674,3675,3676,3677,3678,3679,
-3680,3681,3682,3683,3684,3685,3686,3687,3688,3689,3690,3691,3692,3693,3694,3695,
-3696,3697,3698,3699,3700,1192,3701,3702,3703,3704,1256,3705,3706,3707,3708,1583,
-1257,3709,3710,3711,3712,3713,3714,3715,3716,1584,3717,3718,3719,3720,3721,3722,
-3723,3724,3725,3726,3727,3728,3729,3730,3731,3732,3733,3734,3735,3736,3737,3738,
-3739,3740,3741,3742,3743,3744,3745,1344,3746,3747,3748,3749,3750,3751,3752,3753,
-3754,3755,3756,1585,3757,3758,3759,3760,3761,3762,3763,3764,3765,3766,1586,3767,
-3768,3769,3770,3771,3772,3773,3774,3775,3776,3777,3778,1345,3779,3780,3781,3782,
-3783,3784,3785,3786,3787,3788,3789,3790,3791,3792,3793,3794,3795,1346,1587,3796,
-3797,1588,3798,3799,3800,3801,3802,3803,3804,3805,3806,1347,3807,3808,3809,3810,
-3811,1589,3812,3813,3814,3815,3816,3817,3818,3819,3820,3821,1590,3822,3823,1591,
-1348,3824,3825,3826,3827,3828,3829,3830,1592,3831,3832,1593,3833,3834,3835,3836,
-3837,3838,3839,3840,3841,3842,3843,3844,1349,3845,3846,3847,3848,3849,3850,3851,
-3852,3853,3854,3855,3856,3857,3858,1594,3859,3860,3861,3862,3863,3864,3865,3866,
-3867,3868,3869,1595,3870,3871,3872,3873,1596,3874,3875,3876,3877,3878,3879,3880,
-3881,3882,3883,3884,3885,3886,1597,3887,3888,3889,3890,3891,3892,3893,3894,3895,
-1598,3896,3897,3898,1599,1600,3899,1350,3900,1351,3901,3902,1352,3903,3904,3905,
-3906,3907,3908,3909,3910,3911,3912,3913,3914,3915,3916,3917,3918,3919,3920,3921,
-3922,3923,3924,1258,3925,3926,3927,3928,3929,3930,3931,1193,3932,1601,3933,3934,
-3935,3936,3937,3938,3939,3940,3941,3942,3943,1602,3944,3945,3946,3947,3948,1603,
-3949,3950,3951,3952,3953,3954,3955,3956,3957,3958,3959,3960,3961,3962,3963,3964,
-3965,1604,3966,3967,3968,3969,3970,3971,3972,3973,3974,3975,3976,3977,1353,3978,
-3979,3980,3981,3982,3983,3984,3985,3986,3987,3988,3989,3990,3991,1354,3992,3993,
-3994,3995,3996,3997,3998,3999,4000,4001,4002,4003,4004,4005,4006,4007,4008,4009,
-4010,4011,4012,4013,4014,4015,4016,4017,4018,4019,4020,4021,4022,4023,1355,4024,
-4025,4026,4027,4028,4029,4030,4031,4032,4033,4034,4035,4036,4037,4038,4039,4040,
-1605,4041,4042,4043,4044,4045,4046,4047,4048,4049,4050,4051,4052,4053,4054,4055,
-4056,4057,4058,4059,4060,1606,4061,4062,4063,4064,1607,4065,4066,4067,4068,4069,
-4070,4071,4072,4073,4074,4075,4076,1194,4077,4078,1608,4079,4080,4081,4082,4083,
-4084,4085,4086,4087,1609,4088,4089,4090,4091,4092,4093,4094,4095,4096,4097,4098,
-4099,4100,4101,4102,4103,4104,4105,4106,4107,4108,1259,4109,4110,4111,4112,4113,
-4114,4115,4116,4117,4118,4119,4120,4121,4122,4123,4124,1195,4125,4126,4127,1610,
-4128,4129,4130,4131,4132,4133,4134,4135,4136,4137,1356,4138,4139,4140,4141,4142,
-4143,4144,1611,4145,4146,4147,4148,4149,4150,4151,4152,4153,4154,4155,4156,4157,
-4158,4159,4160,4161,4162,4163,4164,4165,4166,4167,4168,4169,4170,4171,4172,4173,
-4174,4175,4176,4177,4178,4179,4180,4181,4182,4183,4184,4185,4186,4187,4188,4189,
-4190,4191,4192,4193,4194,4195,4196,4197,4198,4199,4200,4201,4202,4203,4204,4205,
-4206,4207,4208,4209,4210,4211,4212,4213,4214,4215,4216,4217,4218,4219,1612,4220,
-4221,4222,4223,4224,4225,4226,4227,1357,4228,1613,4229,4230,4231,4232,4233,4234,
-4235,4236,4237,4238,4239,4240,4241,4242,4243,1614,4244,4245,4246,4247,4248,4249,
-4250,4251,4252,4253,4254,4255,4256,4257,4258,4259,4260,4261,4262,4263,4264,4265,
-4266,4267,4268,4269,4270,1196,1358,4271,4272,4273,4274,4275,4276,4277,4278,4279,
-4280,4281,4282,4283,4284,4285,4286,4287,1615,4288,4289,4290,4291,4292,4293,4294,
-4295,4296,4297,4298,4299,4300,4301,4302,4303,4304,4305,4306,4307,4308,4309,4310,
-4311,4312,4313,4314,4315,4316,4317,4318,4319,4320,4321,4322,4323,4324,4325,4326,
-4327,4328,4329,4330,4331,4332,4333,4334,1616,4335,4336,4337,4338,4339,4340,4341,
-4342,4343,4344,4345,4346,4347,4348,4349,4350,4351,4352,4353,4354,4355,4356,4357,
-4358,4359,4360,1617,4361,4362,4363,4364,4365,1618,4366,4367,4368,4369,4370,4371,
-4372,4373,4374,4375,4376,4377,4378,4379,4380,4381,4382,4383,4384,4385,4386,4387,
-4388,4389,4390,4391,4392,4393,4394,4395,4396,4397,4398,4399,4400,4401,4402,4403,
-4404,4405,4406,4407,4408,4409,4410,4411,4412,4413,4414,4415,4416,1619,4417,4418,
-4419,4420,4421,4422,4423,4424,4425,1112,4426,4427,4428,4429,4430,1620,4431,4432,
-4433,4434,4435,4436,4437,4438,4439,4440,4441,4442,1260,1261,4443,4444,4445,4446,
-4447,4448,4449,4450,4451,4452,4453,4454,4455,1359,4456,4457,4458,4459,4460,4461,
-4462,4463,4464,4465,1621,4466,4467,4468,4469,4470,4471,4472,4473,4474,4475,4476,
-4477,4478,4479,4480,4481,4482,4483,4484,4485,4486,4487,4488,4489,1055,4490,4491,
-4492,4493,4494,4495,4496,4497,4498,4499,4500,4501,4502,4503,4504,4505,4506,4507,
-4508,4509,4510,4511,4512,4513,4514,4515,4516,4517,4518,1622,4519,4520,4521,1623,
-4522,4523,4524,4525,4526,4527,4528,4529,4530,4531,4532,4533,4534,4535,1360,4536,
-4537,4538,4539,4540,4541,4542,4543, 975,4544,4545,4546,4547,4548,4549,4550,4551,
-4552,4553,4554,4555,4556,4557,4558,4559,4560,4561,4562,4563,4564,4565,4566,4567,
-4568,4569,4570,4571,1624,4572,4573,4574,4575,4576,1625,4577,4578,4579,4580,4581,
-4582,4583,4584,1626,4585,4586,4587,4588,4589,4590,4591,4592,4593,4594,4595,1627,
-4596,4597,4598,4599,4600,4601,4602,4603,4604,4605,4606,4607,4608,4609,4610,4611,
-4612,4613,4614,4615,1628,4616,4617,4618,4619,4620,4621,4622,4623,4624,4625,4626,
-4627,4628,4629,4630,4631,4632,4633,4634,4635,4636,4637,4638,4639,4640,4641,4642,
-4643,4644,4645,4646,4647,4648,4649,1361,4650,4651,4652,4653,4654,4655,4656,4657,
-4658,4659,4660,4661,1362,4662,4663,4664,4665,4666,4667,4668,4669,4670,4671,4672,
-4673,4674,4675,4676,4677,4678,4679,4680,4681,4682,1629,4683,4684,4685,4686,4687,
-1630,4688,4689,4690,4691,1153,4692,4693,4694,1113,4695,4696,4697,4698,4699,4700,
-4701,4702,4703,4704,4705,4706,4707,4708,4709,4710,4711,1197,4712,4713,4714,4715,
-4716,4717,4718,4719,4720,4721,4722,4723,4724,4725,4726,4727,4728,4729,4730,4731,
-4732,4733,4734,4735,1631,4736,1632,4737,4738,4739,4740,4741,4742,4743,4744,1633,
-4745,4746,4747,4748,4749,1262,4750,4751,4752,4753,4754,1363,4755,4756,4757,4758,
-4759,4760,4761,4762,4763,4764,4765,4766,4767,4768,1634,4769,4770,4771,4772,4773,
-4774,4775,4776,4777,4778,1635,4779,4780,4781,4782,4783,4784,4785,4786,4787,4788,
-4789,1636,4790,4791,4792,4793,4794,4795,4796,4797,4798,4799,4800,4801,4802,4803,
-4804,4805,4806,1637,4807,4808,4809,1638,4810,4811,4812,4813,4814,4815,4816,4817,
-4818,1639,4819,4820,4821,4822,4823,4824,4825,4826,4827,4828,4829,4830,4831,4832,
-4833,1077,4834,4835,4836,4837,4838,4839,4840,4841,4842,4843,4844,4845,4846,4847,
-4848,4849,4850,4851,4852,4853,4854,4855,4856,4857,4858,4859,4860,4861,4862,4863,
-4864,4865,4866,4867,4868,4869,4870,4871,4872,4873,4874,4875,4876,4877,4878,4879,
-4880,4881,4882,4883,1640,4884,4885,1641,4886,4887,4888,4889,4890,4891,4892,4893,
-4894,4895,4896,4897,4898,4899,4900,4901,4902,4903,4904,4905,4906,4907,4908,4909,
-4910,4911,1642,4912,4913,4914,1364,4915,4916,4917,4918,4919,4920,4921,4922,4923,
-4924,4925,4926,4927,4928,4929,4930,4931,1643,4932,4933,4934,4935,4936,4937,4938,
-4939,4940,4941,4942,4943,4944,4945,4946,4947,4948,4949,4950,4951,4952,4953,4954,
-4955,4956,4957,4958,4959,4960,4961,4962,4963,4964,4965,4966,4967,4968,4969,4970,
-4971,4972,4973,4974,4975,4976,4977,4978,4979,4980,1644,4981,4982,4983,4984,1645,
-4985,4986,1646,4987,4988,4989,4990,4991,4992,4993,4994,4995,4996,4997,4998,4999,
-5000,5001,5002,5003,5004,5005,1647,5006,1648,5007,5008,5009,5010,5011,5012,1078,
-5013,5014,5015,5016,5017,5018,5019,5020,5021,5022,5023,5024,5025,5026,5027,5028,
-1365,5029,5030,5031,5032,5033,5034,5035,5036,5037,5038,5039,1649,5040,5041,5042,
-5043,5044,5045,1366,5046,5047,5048,5049,5050,5051,5052,5053,5054,5055,1650,5056,
-5057,5058,5059,5060,5061,5062,5063,5064,5065,5066,5067,5068,5069,5070,5071,5072,
-5073,5074,5075,5076,5077,1651,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087,
-5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102,5103,
-5104,5105,5106,5107,5108,5109,5110,1652,5111,5112,5113,5114,5115,5116,5117,5118,
-1367,5119,5120,5121,5122,5123,5124,5125,5126,5127,5128,5129,1653,5130,5131,5132,
-5133,5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148,
-5149,1368,5150,1654,5151,1369,5152,5153,5154,5155,5156,5157,5158,5159,5160,5161,
-5162,5163,5164,5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,5176,5177,
-5178,1370,5179,5180,5181,5182,5183,5184,5185,5186,5187,5188,5189,5190,5191,5192,
-5193,5194,5195,5196,5197,5198,1655,5199,5200,5201,5202,1656,5203,5204,5205,5206,
-1371,5207,1372,5208,5209,5210,5211,1373,5212,5213,1374,5214,5215,5216,5217,5218,
-5219,5220,5221,5222,5223,5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234,
-5235,5236,5237,5238,5239,5240,5241,5242,5243,5244,5245,5246,5247,1657,5248,5249,
-5250,5251,1658,1263,5252,5253,5254,5255,5256,1375,5257,5258,5259,5260,5261,5262,
-5263,5264,5265,5266,5267,5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278,
-5279,5280,5281,5282,5283,1659,5284,5285,5286,5287,5288,5289,5290,5291,5292,5293,
-5294,5295,5296,5297,5298,5299,5300,1660,5301,5302,5303,5304,5305,5306,5307,5308,
-5309,5310,5311,5312,5313,5314,5315,5316,5317,5318,5319,5320,5321,1376,5322,5323,
-5324,5325,5326,5327,5328,5329,5330,5331,5332,5333,1198,5334,5335,5336,5337,5338,
-5339,5340,5341,5342,5343,1661,5344,5345,5346,5347,5348,5349,5350,5351,5352,5353,
-5354,5355,5356,5357,5358,5359,5360,5361,5362,5363,5364,5365,5366,5367,5368,5369,
-5370,5371,5372,5373,5374,5375,5376,5377,5378,5379,5380,5381,5382,5383,5384,5385,
-5386,5387,5388,5389,5390,5391,5392,5393,5394,5395,5396,5397,5398,1264,5399,5400,
-5401,5402,5403,5404,5405,5406,5407,5408,5409,5410,5411,5412,1662,5413,5414,5415,
-5416,1663,5417,5418,5419,5420,5421,5422,5423,5424,5425,5426,5427,5428,5429,5430,
-5431,5432,5433,5434,5435,5436,5437,5438,1664,5439,5440,5441,5442,5443,5444,5445,
-5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456,5457,5458,5459,5460,5461,
-5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472,5473,5474,5475,5476,5477,
-5478,1154,5479,5480,5481,5482,5483,5484,5485,1665,5486,5487,5488,5489,5490,5491,
-5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504,5505,5506,5507,
-5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520,5521,5522,5523,
-5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536,5537,5538,5539,
-5540,5541,5542,5543,5544,5545,5546,5547,5548,1377,5549,5550,5551,5552,5553,5554,
-5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568,5569,5570,
-1114,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584,5585,
-5586,5587,5588,5589,5590,5591,5592,1378,5593,5594,5595,5596,5597,5598,5599,5600,
-5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,1379,5615,
-5616,5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631,
-5632,5633,5634,1380,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646,
-5647,5648,5649,1381,1056,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660,
-1666,5661,5662,5663,5664,5665,5666,5667,5668,1667,5669,1668,5670,5671,5672,5673,
-5674,5675,5676,5677,5678,1155,5679,5680,5681,5682,5683,5684,5685,5686,5687,5688,
-5689,5690,5691,5692,5693,5694,5695,5696,5697,5698,1669,5699,5700,5701,5702,5703,
-5704,5705,1670,5706,5707,5708,5709,5710,1671,5711,5712,5713,5714,1382,5715,5716,
-5717,5718,5719,5720,5721,5722,5723,5724,5725,1672,5726,5727,1673,1674,5728,5729,
-5730,5731,5732,5733,5734,5735,5736,1675,5737,5738,5739,5740,5741,5742,5743,5744,
-1676,5745,5746,5747,5748,5749,5750,5751,1383,5752,5753,5754,5755,5756,5757,5758,
-5759,5760,5761,5762,5763,5764,5765,5766,5767,5768,1677,5769,5770,5771,5772,5773,
-1678,5774,5775,5776, 998,5777,5778,5779,5780,5781,5782,5783,5784,5785,1384,5786,
-5787,5788,5789,5790,5791,5792,5793,5794,5795,5796,5797,5798,5799,5800,1679,5801,
-5802,5803,1115,1116,5804,5805,5806,5807,5808,5809,5810,5811,5812,5813,5814,5815,
-5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828,5829,5830,5831,
-5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844,5845,5846,5847,
-5848,5849,5850,5851,5852,5853,5854,5855,1680,5856,5857,5858,5859,5860,5861,5862,
-5863,5864,1681,5865,5866,5867,1682,5868,5869,5870,5871,5872,5873,5874,5875,5876,
-5877,5878,5879,1683,5880,1684,5881,5882,5883,5884,1685,5885,5886,5887,5888,5889,
-5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904,5905,
-5906,5907,1686,5908,5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920,
-5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,1687,
-5936,5937,5938,5939,5940,5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,
-5952,1688,1689,5953,1199,5954,5955,5956,5957,5958,5959,5960,5961,1690,5962,5963,
-5964,5965,5966,5967,5968,5969,5970,5971,5972,5973,5974,5975,5976,5977,5978,5979,
-5980,5981,1385,5982,1386,5983,5984,5985,5986,5987,5988,5989,5990,5991,5992,5993,
-5994,5995,5996,5997,5998,5999,6000,6001,6002,6003,6004,6005,6006,6007,6008,6009,
-6010,6011,6012,6013,6014,6015,6016,6017,6018,6019,6020,6021,6022,6023,6024,6025,
-6026,6027,1265,6028,6029,1691,6030,6031,6032,6033,6034,6035,6036,6037,6038,6039,
-6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052,6053,6054,6055,
-6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6068,6069,6070,6071,
-6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084,1692,6085,6086,
-6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6100,6101,6102,
-6103,6104,6105,6106,6107,6108,6109,6110,6111,6112,6113,6114,6115,6116,6117,6118,
-6119,6120,6121,6122,6123,6124,6125,6126,6127,6128,6129,6130,6131,1693,6132,6133,
-6134,6135,6136,1694,6137,6138,6139,6140,6141,1695,6142,6143,6144,6145,6146,6147,
-6148,6149,6150,6151,6152,6153,6154,6155,6156,6157,6158,6159,6160,6161,6162,6163,
-6164,6165,6166,6167,6168,6169,6170,6171,6172,6173,6174,6175,6176,6177,6178,6179,
-6180,6181,6182,6183,6184,6185,1696,6186,6187,6188,6189,6190,6191,6192,6193,6194,
-6195,6196,6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210,
-6211,6212,6213,6214,6215,6216,6217,6218,6219,1697,6220,6221,6222,6223,6224,6225,
-6226,6227,6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241,
-6242,6243,6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,1698,6254,6255,6256,
-6257,6258,6259,6260,6261,6262,6263,1200,6264,6265,6266,6267,6268,6269,6270,6271, #1024
-6272,6273,6274,6275,6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,6286,6287,
-6288,6289,6290,6291,6292,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,1699,
-6303,6304,1700,6305,6306,6307,6308,6309,6310,6311,6312,6313,6314,6315,6316,6317,
-6318,6319,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333,
-6334,6335,6336,6337,6338,6339,1701,6340,6341,6342,6343,6344,1387,6345,6346,6347,
-6348,6349,6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363,
-6364,6365,6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379,
-6380,6381,6382,6383,6384,6385,6386,6387,6388,6389,6390,6391,6392,6393,6394,6395,
-6396,6397,6398,6399,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,6411,
-6412,6413,1702,6414,6415,6416,6417,6418,6419,6420,6421,6422,1703,6423,6424,6425,
-6426,6427,6428,6429,6430,6431,6432,6433,6434,6435,6436,6437,6438,1704,6439,6440,
-6441,6442,6443,6444,6445,6446,6447,6448,6449,6450,6451,6452,6453,6454,6455,6456,
-6457,6458,6459,6460,6461,6462,6463,6464,6465,6466,6467,6468,6469,6470,6471,6472,
-6473,6474,6475,6476,6477,6478,6479,6480,6481,6482,6483,6484,6485,6486,6487,6488,
-6489,6490,6491,6492,6493,6494,6495,6496,6497,6498,6499,6500,6501,6502,6503,1266,
-6504,6505,6506,6507,6508,6509,6510,6511,6512,6513,6514,6515,6516,6517,6518,6519,
-6520,6521,6522,6523,6524,6525,6526,6527,6528,6529,6530,6531,6532,6533,6534,6535,
-6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548,6549,6550,6551,
-1705,1706,6552,6553,6554,6555,6556,6557,6558,6559,6560,6561,6562,6563,6564,6565,
-6566,6567,6568,6569,6570,6571,6572,6573,6574,6575,6576,6577,6578,6579,6580,6581,
-6582,6583,6584,6585,6586,6587,6588,6589,6590,6591,6592,6593,6594,6595,6596,6597,
-6598,6599,6600,6601,6602,6603,6604,6605,6606,6607,6608,6609,6610,6611,6612,6613,
-6614,6615,6616,6617,6618,6619,6620,6621,6622,6623,6624,6625,6626,6627,6628,6629,
-6630,6631,6632,6633,6634,6635,6636,6637,1388,6638,6639,6640,6641,6642,6643,6644,
-1707,6645,6646,6647,6648,6649,6650,6651,6652,6653,6654,6655,6656,6657,6658,6659,
-6660,6661,6662,6663,1708,6664,6665,6666,6667,6668,6669,6670,6671,6672,6673,6674,
-1201,6675,6676,6677,6678,6679,6680,6681,6682,6683,6684,6685,6686,6687,6688,6689,
-6690,6691,6692,6693,6694,6695,6696,6697,6698,6699,6700,6701,6702,6703,6704,6705,
-6706,6707,6708,6709,6710,6711,6712,6713,6714,6715,6716,6717,6718,6719,6720,6721,
-6722,6723,6724,6725,1389,6726,6727,6728,6729,6730,6731,6732,6733,6734,6735,6736,
-1390,1709,6737,6738,6739,6740,6741,6742,1710,6743,6744,6745,6746,1391,6747,6748,
-6749,6750,6751,6752,6753,6754,6755,6756,6757,1392,6758,6759,6760,6761,6762,6763,
-6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777,6778,6779,
-6780,1202,6781,6782,6783,6784,6785,6786,6787,6788,6789,6790,6791,6792,6793,6794,
-6795,6796,6797,6798,6799,6800,6801,6802,6803,6804,6805,6806,6807,6808,6809,1711,
-6810,6811,6812,6813,6814,6815,6816,6817,6818,6819,6820,6821,6822,6823,6824,6825,
-6826,6827,6828,6829,6830,6831,6832,6833,6834,6835,6836,1393,6837,6838,6839,6840,
-6841,6842,6843,6844,6845,6846,6847,6848,6849,6850,6851,6852,6853,6854,6855,6856,
-6857,6858,6859,6860,6861,6862,6863,6864,6865,6866,6867,6868,6869,6870,6871,6872,
-6873,6874,6875,6876,6877,6878,6879,6880,6881,6882,6883,6884,6885,6886,6887,6888,
-6889,6890,6891,6892,6893,6894,6895,6896,6897,6898,6899,6900,6901,6902,1712,6903,
-6904,6905,6906,6907,6908,6909,6910,1713,6911,6912,6913,6914,6915,6916,6917,6918,
-6919,6920,6921,6922,6923,6924,6925,6926,6927,6928,6929,6930,6931,6932,6933,6934,
-6935,6936,6937,6938,6939,6940,6941,6942,6943,6944,6945,6946,6947,6948,6949,6950,
-6951,6952,6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6964,6965,6966,
-6967,6968,6969,6970,6971,6972,6973,6974,1714,6975,6976,6977,6978,6979,6980,6981,
-6982,6983,6984,6985,6986,6987,6988,1394,6989,6990,6991,6992,6993,6994,6995,6996,
-6997,6998,6999,7000,1715,7001,7002,7003,7004,7005,7006,7007,7008,7009,7010,7011,
-7012,7013,7014,7015,7016,7017,7018,7019,7020,7021,7022,7023,7024,7025,7026,7027,
-7028,1716,7029,7030,7031,7032,7033,7034,7035,7036,7037,7038,7039,7040,7041,7042,
-7043,7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058,
-7059,7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,7071,7072,7073,7074,
-7075,7076,7077,7078,7079,7080,7081,7082,7083,7084,7085,7086,7087,7088,7089,7090,
-7091,7092,7093,7094,7095,7096,7097,7098,7099,7100,7101,7102,7103,7104,7105,7106,
-7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,7119,7120,7121,7122,
-7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136,7137,7138,
-7139,7140,7141,7142,7143,7144,7145,7146,7147,7148,7149,7150,7151,7152,7153,7154,
-7155,7156,7157,7158,7159,7160,7161,7162,7163,7164,7165,7166,7167,7168,7169,7170,
-7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183,7184,7185,7186,
-7187,7188,7189,7190,7191,7192,7193,7194,7195,7196,7197,7198,7199,7200,7201,7202,
-7203,7204,7205,7206,7207,1395,7208,7209,7210,7211,7212,7213,1717,7214,7215,7216,
-7217,7218,7219,7220,7221,7222,7223,7224,7225,7226,7227,7228,7229,7230,7231,7232,
-7233,7234,7235,7236,7237,7238,7239,7240,7241,7242,7243,7244,7245,7246,7247,7248,
-7249,7250,7251,7252,7253,7254,7255,7256,7257,7258,7259,7260,7261,7262,7263,7264,
-7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277,7278,7279,7280,
-7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293,7294,7295,7296,
-7297,7298,7299,7300,7301,7302,7303,7304,7305,7306,7307,7308,7309,7310,7311,7312,
-7313,1718,7314,7315,7316,7317,7318,7319,7320,7321,7322,7323,7324,7325,7326,7327,
-7328,7329,7330,7331,7332,7333,7334,7335,7336,7337,7338,7339,7340,7341,7342,7343,
-7344,7345,7346,7347,7348,7349,7350,7351,7352,7353,7354,7355,7356,7357,7358,7359,
-7360,7361,7362,7363,7364,7365,7366,7367,7368,7369,7370,7371,7372,7373,7374,7375,
-7376,7377,7378,7379,7380,7381,7382,7383,7384,7385,7386,7387,7388,7389,7390,7391,
-7392,7393,7394,7395,7396,7397,7398,7399,7400,7401,7402,7403,7404,7405,7406,7407,
-7408,7409,7410,7411,7412,7413,7414,7415,7416,7417,7418,7419,7420,7421,7422,7423,
-7424,7425,7426,7427,7428,7429,7430,7431,7432,7433,7434,7435,7436,7437,7438,7439,
-7440,7441,7442,7443,7444,7445,7446,7447,7448,7449,7450,7451,7452,7453,7454,7455,
-7456,7457,7458,7459,7460,7461,7462,7463,7464,7465,7466,7467,7468,7469,7470,7471,
-7472,7473,7474,7475,7476,7477,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487,
-7488,7489,7490,7491,7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,7503,
-7504,7505,7506,7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519,
-7520,7521,7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535,
-7536,7537,7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,7550,7551,
-7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567,
-7568,7569,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582,7583,
-7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598,7599,
-7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614,7615,
-7616,7617,7618,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628,7629,7630,7631,
-7632,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643,7644,7645,7646,7647,
-7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659,7660,7661,7662,7663,
-7664,7665,7666,7667,7668,7669,7670,7671,7672,7673,7674,7675,7676,7677,7678,7679,
-7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690,7691,7692,7693,7694,7695,
-7696,7697,7698,7699,7700,7701,7702,7703,7704,7705,7706,7707,7708,7709,7710,7711,
-7712,7713,7714,7715,7716,7717,7718,7719,7720,7721,7722,7723,7724,7725,7726,7727,
-7728,7729,7730,7731,7732,7733,7734,7735,7736,7737,7738,7739,7740,7741,7742,7743,
-7744,7745,7746,7747,7748,7749,7750,7751,7752,7753,7754,7755,7756,7757,7758,7759,
-7760,7761,7762,7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775,
-7776,7777,7778,7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791,
-7792,7793,7794,7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,7806,7807,
-7808,7809,7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,
-7824,7825,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,
-7840,7841,7842,7843,7844,7845,7846,7847,7848,7849,7850,7851,7852,7853,7854,7855,
-7856,7857,7858,7859,7860,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870,7871,
-7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886,7887,
-7888,7889,7890,7891,7892,7893,7894,7895,7896,7897,7898,7899,7900,7901,7902,7903,
-7904,7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919,
-7920,7921,7922,7923,7924,7925,7926,7927,7928,7929,7930,7931,7932,7933,7934,7935,
-7936,7937,7938,7939,7940,7941,7942,7943,7944,7945,7946,7947,7948,7949,7950,7951,
-7952,7953,7954,7955,7956,7957,7958,7959,7960,7961,7962,7963,7964,7965,7966,7967,
-7968,7969,7970,7971,7972,7973,7974,7975,7976,7977,7978,7979,7980,7981,7982,7983,
-7984,7985,7986,7987,7988,7989,7990,7991,7992,7993,7994,7995,7996,7997,7998,7999,
-8000,8001,8002,8003,8004,8005,8006,8007,8008,8009,8010,8011,8012,8013,8014,8015,
-8016,8017,8018,8019,8020,8021,8022,8023,8024,8025,8026,8027,8028,8029,8030,8031,
-8032,8033,8034,8035,8036,8037,8038,8039,8040,8041,8042,8043,8044,8045,8046,8047,
-8048,8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063,
-8064,8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079,
-8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095,
-8096,8097,8098,8099,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110,8111,
-8112,8113,8114,8115,8116,8117,8118,8119,8120,8121,8122,8123,8124,8125,8126,8127,
-8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141,8142,8143,
-8144,8145,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155,8156,8157,8158,8159,
-8160,8161,8162,8163,8164,8165,8166,8167,8168,8169,8170,8171,8172,8173,8174,8175,
-8176,8177,8178,8179,8180,8181,8182,8183,8184,8185,8186,8187,8188,8189,8190,8191,
-8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207,
-8208,8209,8210,8211,8212,8213,8214,8215,8216,8217,8218,8219,8220,8221,8222,8223,
-8224,8225,8226,8227,8228,8229,8230,8231,8232,8233,8234,8235,8236,8237,8238,8239,
-8240,8241,8242,8243,8244,8245,8246,8247,8248,8249,8250,8251,8252,8253,8254,8255,
-8256,8257,8258,8259,8260,8261,8262,8263,8264,8265,8266,8267,8268,8269,8270,8271,
-8272,8273,8274,8275,8276,8277,8278,8279,8280,8281,8282,8283,8284,8285,8286,8287,
-8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,
-8304,8305,8306,8307,8308,8309,8310,8311,8312,8313,8314,8315,8316,8317,8318,8319,
-8320,8321,8322,8323,8324,8325,8326,8327,8328,8329,8330,8331,8332,8333,8334,8335,
-8336,8337,8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8349,8350,8351,
-8352,8353,8354,8355,8356,8357,8358,8359,8360,8361,8362,8363,8364,8365,8366,8367,
-8368,8369,8370,8371,8372,8373,8374,8375,8376,8377,8378,8379,8380,8381,8382,8383,
-8384,8385,8386,8387,8388,8389,8390,8391,8392,8393,8394,8395,8396,8397,8398,8399,
-8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,8411,8412,8413,8414,8415,
-8416,8417,8418,8419,8420,8421,8422,8423,8424,8425,8426,8427,8428,8429,8430,8431,
-8432,8433,8434,8435,8436,8437,8438,8439,8440,8441,8442,8443,8444,8445,8446,8447,
-8448,8449,8450,8451,8452,8453,8454,8455,8456,8457,8458,8459,8460,8461,8462,8463,
-8464,8465,8466,8467,8468,8469,8470,8471,8472,8473,8474,8475,8476,8477,8478,8479,
-8480,8481,8482,8483,8484,8485,8486,8487,8488,8489,8490,8491,8492,8493,8494,8495,
-8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8506,8507,8508,8509,8510,8511,
-8512,8513,8514,8515,8516,8517,8518,8519,8520,8521,8522,8523,8524,8525,8526,8527,
-8528,8529,8530,8531,8532,8533,8534,8535,8536,8537,8538,8539,8540,8541,8542,8543,
-8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554,8555,8556,8557,8558,8559,
-8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,8570,8571,8572,8573,8574,8575,
-8576,8577,8578,8579,8580,8581,8582,8583,8584,8585,8586,8587,8588,8589,8590,8591,
-8592,8593,8594,8595,8596,8597,8598,8599,8600,8601,8602,8603,8604,8605,8606,8607,
-8608,8609,8610,8611,8612,8613,8614,8615,8616,8617,8618,8619,8620,8621,8622,8623,
-8624,8625,8626,8627,8628,8629,8630,8631,8632,8633,8634,8635,8636,8637,8638,8639,
-8640,8641,8642,8643,8644,8645,8646,8647,8648,8649,8650,8651,8652,8653,8654,8655,
-8656,8657,8658,8659,8660,8661,8662,8663,8664,8665,8666,8667,8668,8669,8670,8671,
-8672,8673,8674,8675,8676,8677,8678,8679,8680,8681,8682,8683,8684,8685,8686,8687,
-8688,8689,8690,8691,8692,8693,8694,8695,8696,8697,8698,8699,8700,8701,8702,8703,
-8704,8705,8706,8707,8708,8709,8710,8711,8712,8713,8714,8715,8716,8717,8718,8719,
-8720,8721,8722,8723,8724,8725,8726,8727,8728,8729,8730,8731,8732,8733,8734,8735,
-8736,8737,8738,8739,8740,8741)
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euckrprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euckrprober.py
deleted file mode 100644
index 5982a46..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euckrprober.py
+++ /dev/null
@@ -1,42 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .mbcharsetprober import MultiByteCharSetProber
-from .codingstatemachine import CodingStateMachine
-from .chardistribution import EUCKRDistributionAnalysis
-from .mbcssm import EUCKRSMModel
-
-
-class EUCKRProber(MultiByteCharSetProber):
- def __init__(self):
- MultiByteCharSetProber.__init__(self)
- self._mCodingSM = CodingStateMachine(EUCKRSMModel)
- self._mDistributionAnalyzer = EUCKRDistributionAnalysis()
- self.reset()
-
- def get_charset_name(self):
- return "EUC-KR"
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euctwfreq.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euctwfreq.py
deleted file mode 100644
index 576e750..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euctwfreq.py
+++ /dev/null
@@ -1,428 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# EUCTW frequency table
-# Converted from big5 work
-# by Taiwan's Mandarin Promotion Council
-#
-
-# 128 --> 0.42261
-# 256 --> 0.57851
-# 512 --> 0.74851
-# 1024 --> 0.89384
-# 2048 --> 0.97583
-#
-# Idea Distribution Ratio = 0.74851/(1-0.74851) =2.98
-# Random Distribution Ration = 512/(5401-512)=0.105
-#
-# Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR
-
-EUCTW_TYPICAL_DISTRIBUTION_RATIO = 0.75
-
-# Char to FreqOrder table ,
-EUCTW_TABLE_SIZE = 8102
-
-EUCTWCharToFreqOrder = (
- 1,1800,1506, 255,1431, 198, 9, 82, 6,7310, 177, 202,3615,1256,2808, 110, # 2742
-3735, 33,3241, 261, 76, 44,2113, 16,2931,2184,1176, 659,3868, 26,3404,2643, # 2758
-1198,3869,3313,4060, 410,2211, 302, 590, 361,1963, 8, 204, 58,4296,7311,1931, # 2774
- 63,7312,7313, 317,1614, 75, 222, 159,4061,2412,1480,7314,3500,3068, 224,2809, # 2790
-3616, 3, 10,3870,1471, 29,2774,1135,2852,1939, 873, 130,3242,1123, 312,7315, # 2806
-4297,2051, 507, 252, 682,7316, 142,1914, 124, 206,2932, 34,3501,3173, 64, 604, # 2822
-7317,2494,1976,1977, 155,1990, 645, 641,1606,7318,3405, 337, 72, 406,7319, 80, # 2838
- 630, 238,3174,1509, 263, 939,1092,2644, 756,1440,1094,3406, 449, 69,2969, 591, # 2854
- 179,2095, 471, 115,2034,1843, 60, 50,2970, 134, 806,1868, 734,2035,3407, 180, # 2870
- 995,1607, 156, 537,2893, 688,7320, 319,1305, 779,2144, 514,2374, 298,4298, 359, # 2886
-2495, 90,2707,1338, 663, 11, 906,1099,2545, 20,2436, 182, 532,1716,7321, 732, # 2902
-1376,4062,1311,1420,3175, 25,2312,1056, 113, 399, 382,1949, 242,3408,2467, 529, # 2918
-3243, 475,1447,3617,7322, 117, 21, 656, 810,1297,2295,2329,3502,7323, 126,4063, # 2934
- 706, 456, 150, 613,4299, 71,1118,2036,4064, 145,3069, 85, 835, 486,2114,1246, # 2950
-1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,7324,2127,2354, 347,3736, 221, # 2966
-3503,3110,7325,1955,1153,4065, 83, 296,1199,3070, 192, 624, 93,7326, 822,1897, # 2982
-2810,3111, 795,2064, 991,1554,1542,1592, 27, 43,2853, 859, 139,1456, 860,4300, # 2998
- 437, 712,3871, 164,2392,3112, 695, 211,3017,2096, 195,3872,1608,3504,3505,3618, # 3014
-3873, 234, 811,2971,2097,3874,2229,1441,3506,1615,2375, 668,2076,1638, 305, 228, # 3030
-1664,4301, 467, 415,7327, 262,2098,1593, 239, 108, 300, 200,1033, 512,1247,2077, # 3046
-7328,7329,2173,3176,3619,2673, 593, 845,1062,3244, 88,1723,2037,3875,1950, 212, # 3062
- 266, 152, 149, 468,1898,4066,4302, 77, 187,7330,3018, 37, 5,2972,7331,3876, # 3078
-7332,7333, 39,2517,4303,2894,3177,2078, 55, 148, 74,4304, 545, 483,1474,1029, # 3094
-1665, 217,1869,1531,3113,1104,2645,4067, 24, 172,3507, 900,3877,3508,3509,4305, # 3110
- 32,1408,2811,1312, 329, 487,2355,2247,2708, 784,2674, 4,3019,3314,1427,1788, # 3126
- 188, 109, 499,7334,3620,1717,1789, 888,1217,3020,4306,7335,3510,7336,3315,1520, # 3142
-3621,3878, 196,1034, 775,7337,7338, 929,1815, 249, 439, 38,7339,1063,7340, 794, # 3158
-3879,1435,2296, 46, 178,3245,2065,7341,2376,7342, 214,1709,4307, 804, 35, 707, # 3174
- 324,3622,1601,2546, 140, 459,4068,7343,7344,1365, 839, 272, 978,2257,2572,3409, # 3190
-2128,1363,3623,1423, 697, 100,3071, 48, 70,1231, 495,3114,2193,7345,1294,7346, # 3206
-2079, 462, 586,1042,3246, 853, 256, 988, 185,2377,3410,1698, 434,1084,7347,3411, # 3222
- 314,2615,2775,4308,2330,2331, 569,2280, 637,1816,2518, 757,1162,1878,1616,3412, # 3238
- 287,1577,2115, 768,4309,1671,2854,3511,2519,1321,3737, 909,2413,7348,4069, 933, # 3254
-3738,7349,2052,2356,1222,4310, 765,2414,1322, 786,4311,7350,1919,1462,1677,2895, # 3270
-1699,7351,4312,1424,2437,3115,3624,2590,3316,1774,1940,3413,3880,4070, 309,1369, # 3286
-1130,2812, 364,2230,1653,1299,3881,3512,3882,3883,2646, 525,1085,3021, 902,2000, # 3302
-1475, 964,4313, 421,1844,1415,1057,2281, 940,1364,3116, 376,4314,4315,1381, 7, # 3318
-2520, 983,2378, 336,1710,2675,1845, 321,3414, 559,1131,3022,2742,1808,1132,1313, # 3334
- 265,1481,1857,7352, 352,1203,2813,3247, 167,1089, 420,2814, 776, 792,1724,3513, # 3350
-4071,2438,3248,7353,4072,7354, 446, 229, 333,2743, 901,3739,1200,1557,4316,2647, # 3366
-1920, 395,2744,2676,3740,4073,1835, 125, 916,3178,2616,4317,7355,7356,3741,7357, # 3382
-7358,7359,4318,3117,3625,1133,2547,1757,3415,1510,2313,1409,3514,7360,2145, 438, # 3398
-2591,2896,2379,3317,1068, 958,3023, 461, 311,2855,2677,4074,1915,3179,4075,1978, # 3414
- 383, 750,2745,2617,4076, 274, 539, 385,1278,1442,7361,1154,1964, 384, 561, 210, # 3430
- 98,1295,2548,3515,7362,1711,2415,1482,3416,3884,2897,1257, 129,7363,3742, 642, # 3446
- 523,2776,2777,2648,7364, 141,2231,1333, 68, 176, 441, 876, 907,4077, 603,2592, # 3462
- 710, 171,3417, 404, 549, 18,3118,2393,1410,3626,1666,7365,3516,4319,2898,4320, # 3478
-7366,2973, 368,7367, 146, 366, 99, 871,3627,1543, 748, 807,1586,1185, 22,2258, # 3494
- 379,3743,3180,7368,3181, 505,1941,2618,1991,1382,2314,7369, 380,2357, 218, 702, # 3510
-1817,1248,3418,3024,3517,3318,3249,7370,2974,3628, 930,3250,3744,7371, 59,7372, # 3526
- 585, 601,4078, 497,3419,1112,1314,4321,1801,7373,1223,1472,2174,7374, 749,1836, # 3542
- 690,1899,3745,1772,3885,1476, 429,1043,1790,2232,2116, 917,4079, 447,1086,1629, # 3558
-7375, 556,7376,7377,2020,1654, 844,1090, 105, 550, 966,1758,2815,1008,1782, 686, # 3574
-1095,7378,2282, 793,1602,7379,3518,2593,4322,4080,2933,2297,4323,3746, 980,2496, # 3590
- 544, 353, 527,4324, 908,2678,2899,7380, 381,2619,1942,1348,7381,1341,1252, 560, # 3606
-3072,7382,3420,2856,7383,2053, 973, 886,2080, 143,4325,7384,7385, 157,3886, 496, # 3622
-4081, 57, 840, 540,2038,4326,4327,3421,2117,1445, 970,2259,1748,1965,2081,4082, # 3638
-3119,1234,1775,3251,2816,3629, 773,1206,2129,1066,2039,1326,3887,1738,1725,4083, # 3654
- 279,3120, 51,1544,2594, 423,1578,2130,2066, 173,4328,1879,7386,7387,1583, 264, # 3670
- 610,3630,4329,2439, 280, 154,7388,7389,7390,1739, 338,1282,3073, 693,2857,1411, # 3686
-1074,3747,2440,7391,4330,7392,7393,1240, 952,2394,7394,2900,1538,2679, 685,1483, # 3702
-4084,2468,1436, 953,4085,2054,4331, 671,2395, 79,4086,2441,3252, 608, 567,2680, # 3718
-3422,4087,4088,1691, 393,1261,1791,2396,7395,4332,7396,7397,7398,7399,1383,1672, # 3734
-3748,3182,1464, 522,1119, 661,1150, 216, 675,4333,3888,1432,3519, 609,4334,2681, # 3750
-2397,7400,7401,7402,4089,3025, 0,7403,2469, 315, 231,2442, 301,3319,4335,2380, # 3766
-7404, 233,4090,3631,1818,4336,4337,7405, 96,1776,1315,2082,7406, 257,7407,1809, # 3782
-3632,2709,1139,1819,4091,2021,1124,2163,2778,1777,2649,7408,3074, 363,1655,3183, # 3798
-7409,2975,7410,7411,7412,3889,1567,3890, 718, 103,3184, 849,1443, 341,3320,2934, # 3814
-1484,7413,1712, 127, 67, 339,4092,2398, 679,1412, 821,7414,7415, 834, 738, 351, # 3830
-2976,2146, 846, 235,1497,1880, 418,1992,3749,2710, 186,1100,2147,2746,3520,1545, # 3846
-1355,2935,2858,1377, 583,3891,4093,2573,2977,7416,1298,3633,1078,2549,3634,2358, # 3862
- 78,3750,3751, 267,1289,2099,2001,1594,4094, 348, 369,1274,2194,2175,1837,4338, # 3878
-1820,2817,3635,2747,2283,2002,4339,2936,2748, 144,3321, 882,4340,3892,2749,3423, # 3894
-4341,2901,7417,4095,1726, 320,7418,3893,3026, 788,2978,7419,2818,1773,1327,2859, # 3910
-3894,2819,7420,1306,4342,2003,1700,3752,3521,2359,2650, 787,2022, 506, 824,3636, # 3926
- 534, 323,4343,1044,3322,2023,1900, 946,3424,7421,1778,1500,1678,7422,1881,4344, # 3942
- 165, 243,4345,3637,2521, 123, 683,4096, 764,4346, 36,3895,1792, 589,2902, 816, # 3958
- 626,1667,3027,2233,1639,1555,1622,3753,3896,7423,3897,2860,1370,1228,1932, 891, # 3974
-2083,2903, 304,4097,7424, 292,2979,2711,3522, 691,2100,4098,1115,4347, 118, 662, # 3990
-7425, 611,1156, 854,2381,1316,2861, 2, 386, 515,2904,7426,7427,3253, 868,2234, # 4006
-1486, 855,2651, 785,2212,3028,7428,1040,3185,3523,7429,3121, 448,7430,1525,7431, # 4022
-2164,4348,7432,3754,7433,4099,2820,3524,3122, 503, 818,3898,3123,1568, 814, 676, # 4038
-1444, 306,1749,7434,3755,1416,1030, 197,1428, 805,2821,1501,4349,7435,7436,7437, # 4054
-1993,7438,4350,7439,7440,2195, 13,2779,3638,2980,3124,1229,1916,7441,3756,2131, # 4070
-7442,4100,4351,2399,3525,7443,2213,1511,1727,1120,7444,7445, 646,3757,2443, 307, # 4086
-7446,7447,1595,3186,7448,7449,7450,3639,1113,1356,3899,1465,2522,2523,7451, 519, # 4102
-7452, 128,2132, 92,2284,1979,7453,3900,1512, 342,3125,2196,7454,2780,2214,1980, # 4118
-3323,7455, 290,1656,1317, 789, 827,2360,7456,3758,4352, 562, 581,3901,7457, 401, # 4134
-4353,2248, 94,4354,1399,2781,7458,1463,2024,4355,3187,1943,7459, 828,1105,4101, # 4150
-1262,1394,7460,4102, 605,4356,7461,1783,2862,7462,2822, 819,2101, 578,2197,2937, # 4166
-7463,1502, 436,3254,4103,3255,2823,3902,2905,3425,3426,7464,2712,2315,7465,7466, # 4182
-2332,2067, 23,4357, 193, 826,3759,2102, 699,1630,4104,3075, 390,1793,1064,3526, # 4198
-7467,1579,3076,3077,1400,7468,4105,1838,1640,2863,7469,4358,4359, 137,4106, 598, # 4214
-3078,1966, 780, 104, 974,2938,7470, 278, 899, 253, 402, 572, 504, 493,1339,7471, # 4230
-3903,1275,4360,2574,2550,7472,3640,3029,3079,2249, 565,1334,2713, 863, 41,7473, # 4246
-7474,4361,7475,1657,2333, 19, 463,2750,4107, 606,7476,2981,3256,1087,2084,1323, # 4262
-2652,2982,7477,1631,1623,1750,4108,2682,7478,2864, 791,2714,2653,2334, 232,2416, # 4278
-7479,2983,1498,7480,2654,2620, 755,1366,3641,3257,3126,2025,1609, 119,1917,3427, # 4294
- 862,1026,4109,7481,3904,3760,4362,3905,4363,2260,1951,2470,7482,1125, 817,4110, # 4310
-4111,3906,1513,1766,2040,1487,4112,3030,3258,2824,3761,3127,7483,7484,1507,7485, # 4326
-2683, 733, 40,1632,1106,2865, 345,4113, 841,2524, 230,4364,2984,1846,3259,3428, # 4342
-7486,1263, 986,3429,7487, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562,3907, # 4358
-3908,2939, 967,2751,2655,1349, 592,2133,1692,3324,2985,1994,4114,1679,3909,1901, # 4374
-2185,7488, 739,3642,2715,1296,1290,7489,4115,2198,2199,1921,1563,2595,2551,1870, # 4390
-2752,2986,7490, 435,7491, 343,1108, 596, 17,1751,4365,2235,3430,3643,7492,4366, # 4406
- 294,3527,2940,1693, 477, 979, 281,2041,3528, 643,2042,3644,2621,2782,2261,1031, # 4422
-2335,2134,2298,3529,4367, 367,1249,2552,7493,3530,7494,4368,1283,3325,2004, 240, # 4438
-1762,3326,4369,4370, 836,1069,3128, 474,7495,2148,2525, 268,3531,7496,3188,1521, # 4454
-1284,7497,1658,1546,4116,7498,3532,3533,7499,4117,3327,2684,1685,4118, 961,1673, # 4470
-2622, 190,2005,2200,3762,4371,4372,7500, 570,2497,3645,1490,7501,4373,2623,3260, # 4486
-1956,4374, 584,1514, 396,1045,1944,7502,4375,1967,2444,7503,7504,4376,3910, 619, # 4502
-7505,3129,3261, 215,2006,2783,2553,3189,4377,3190,4378, 763,4119,3763,4379,7506, # 4518
-7507,1957,1767,2941,3328,3646,1174, 452,1477,4380,3329,3130,7508,2825,1253,2382, # 4534
-2186,1091,2285,4120, 492,7509, 638,1169,1824,2135,1752,3911, 648, 926,1021,1324, # 4550
-4381, 520,4382, 997, 847,1007, 892,4383,3764,2262,1871,3647,7510,2400,1784,4384, # 4566
-1952,2942,3080,3191,1728,4121,2043,3648,4385,2007,1701,3131,1551, 30,2263,4122, # 4582
-7511,2026,4386,3534,7512, 501,7513,4123, 594,3431,2165,1821,3535,3432,3536,3192, # 4598
- 829,2826,4124,7514,1680,3132,1225,4125,7515,3262,4387,4126,3133,2336,7516,4388, # 4614
-4127,7517,3912,3913,7518,1847,2383,2596,3330,7519,4389, 374,3914, 652,4128,4129, # 4630
- 375,1140, 798,7520,7521,7522,2361,4390,2264, 546,1659, 138,3031,2445,4391,7523, # 4646
-2250, 612,1848, 910, 796,3765,1740,1371, 825,3766,3767,7524,2906,2554,7525, 692, # 4662
- 444,3032,2624, 801,4392,4130,7526,1491, 244,1053,3033,4131,4132, 340,7527,3915, # 4678
-1041,2987, 293,1168, 87,1357,7528,1539, 959,7529,2236, 721, 694,4133,3768, 219, # 4694
-1478, 644,1417,3331,2656,1413,1401,1335,1389,3916,7530,7531,2988,2362,3134,1825, # 4710
- 730,1515, 184,2827, 66,4393,7532,1660,2943, 246,3332, 378,1457, 226,3433, 975, # 4726
-3917,2944,1264,3537, 674, 696,7533, 163,7534,1141,2417,2166, 713,3538,3333,4394, # 4742
-3918,7535,7536,1186, 15,7537,1079,1070,7538,1522,3193,3539, 276,1050,2716, 758, # 4758
-1126, 653,2945,3263,7539,2337, 889,3540,3919,3081,2989, 903,1250,4395,3920,3434, # 4774
-3541,1342,1681,1718, 766,3264, 286, 89,2946,3649,7540,1713,7541,2597,3334,2990, # 4790
-7542,2947,2215,3194,2866,7543,4396,2498,2526, 181, 387,1075,3921, 731,2187,3335, # 4806
-7544,3265, 310, 313,3435,2299, 770,4134, 54,3034, 189,4397,3082,3769,3922,7545, # 4822
-1230,1617,1849, 355,3542,4135,4398,3336, 111,4136,3650,1350,3135,3436,3035,4137, # 4838
-2149,3266,3543,7546,2784,3923,3924,2991, 722,2008,7547,1071, 247,1207,2338,2471, # 4854
-1378,4399,2009, 864,1437,1214,4400, 373,3770,1142,2216, 667,4401, 442,2753,2555, # 4870
-3771,3925,1968,4138,3267,1839, 837, 170,1107, 934,1336,1882,7548,7549,2118,4139, # 4886
-2828, 743,1569,7550,4402,4140, 582,2384,1418,3437,7551,1802,7552, 357,1395,1729, # 4902
-3651,3268,2418,1564,2237,7553,3083,3772,1633,4403,1114,2085,4141,1532,7554, 482, # 4918
-2446,4404,7555,7556,1492, 833,1466,7557,2717,3544,1641,2829,7558,1526,1272,3652, # 4934
-4142,1686,1794, 416,2556,1902,1953,1803,7559,3773,2785,3774,1159,2316,7560,2867, # 4950
-4405,1610,1584,3036,2419,2754, 443,3269,1163,3136,7561,7562,3926,7563,4143,2499, # 4966
-3037,4406,3927,3137,2103,1647,3545,2010,1872,4144,7564,4145, 431,3438,7565, 250, # 4982
- 97, 81,4146,7566,1648,1850,1558, 160, 848,7567, 866, 740,1694,7568,2201,2830, # 4998
-3195,4147,4407,3653,1687, 950,2472, 426, 469,3196,3654,3655,3928,7569,7570,1188, # 5014
- 424,1995, 861,3546,4148,3775,2202,2685, 168,1235,3547,4149,7571,2086,1674,4408, # 5030
-3337,3270, 220,2557,1009,7572,3776, 670,2992, 332,1208, 717,7573,7574,3548,2447, # 5046
-3929,3338,7575, 513,7576,1209,2868,3339,3138,4409,1080,7577,7578,7579,7580,2527, # 5062
-3656,3549, 815,1587,3930,3931,7581,3550,3439,3777,1254,4410,1328,3038,1390,3932, # 5078
-1741,3933,3778,3934,7582, 236,3779,2448,3271,7583,7584,3657,3780,1273,3781,4411, # 5094
-7585, 308,7586,4412, 245,4413,1851,2473,1307,2575, 430, 715,2136,2449,7587, 270, # 5110
- 199,2869,3935,7588,3551,2718,1753, 761,1754, 725,1661,1840,4414,3440,3658,7589, # 5126
-7590, 587, 14,3272, 227,2598, 326, 480,2265, 943,2755,3552, 291, 650,1883,7591, # 5142
-1702,1226, 102,1547, 62,3441, 904,4415,3442,1164,4150,7592,7593,1224,1548,2756, # 5158
- 391, 498,1493,7594,1386,1419,7595,2055,1177,4416, 813, 880,1081,2363, 566,1145, # 5174
-4417,2286,1001,1035,2558,2599,2238, 394,1286,7596,7597,2068,7598, 86,1494,1730, # 5190
-3936, 491,1588, 745, 897,2948, 843,3340,3937,2757,2870,3273,1768, 998,2217,2069, # 5206
- 397,1826,1195,1969,3659,2993,3341, 284,7599,3782,2500,2137,2119,1903,7600,3938, # 5222
-2150,3939,4151,1036,3443,1904, 114,2559,4152, 209,1527,7601,7602,2949,2831,2625, # 5238
-2385,2719,3139, 812,2560,7603,3274,7604,1559, 737,1884,3660,1210, 885, 28,2686, # 5254
-3553,3783,7605,4153,1004,1779,4418,7606, 346,1981,2218,2687,4419,3784,1742, 797, # 5270
-1642,3940,1933,1072,1384,2151, 896,3941,3275,3661,3197,2871,3554,7607,2561,1958, # 5286
-4420,2450,1785,7608,7609,7610,3942,4154,1005,1308,3662,4155,2720,4421,4422,1528, # 5302
-2600, 161,1178,4156,1982, 987,4423,1101,4157, 631,3943,1157,3198,2420,1343,1241, # 5318
-1016,2239,2562, 372, 877,2339,2501,1160, 555,1934, 911,3944,7611, 466,1170, 169, # 5334
-1051,2907,2688,3663,2474,2994,1182,2011,2563,1251,2626,7612, 992,2340,3444,1540, # 5350
-2721,1201,2070,2401,1996,2475,7613,4424, 528,1922,2188,1503,1873,1570,2364,3342, # 5366
-3276,7614, 557,1073,7615,1827,3445,2087,2266,3140,3039,3084, 767,3085,2786,4425, # 5382
-1006,4158,4426,2341,1267,2176,3664,3199, 778,3945,3200,2722,1597,2657,7616,4427, # 5398
-7617,3446,7618,7619,7620,3277,2689,1433,3278, 131, 95,1504,3946, 723,4159,3141, # 5414
-1841,3555,2758,2189,3947,2027,2104,3665,7621,2995,3948,1218,7622,3343,3201,3949, # 5430
-4160,2576, 248,1634,3785, 912,7623,2832,3666,3040,3786, 654, 53,7624,2996,7625, # 5446
-1688,4428, 777,3447,1032,3950,1425,7626, 191, 820,2120,2833, 971,4429, 931,3202, # 5462
- 135, 664, 783,3787,1997, 772,2908,1935,3951,3788,4430,2909,3203, 282,2723, 640, # 5478
-1372,3448,1127, 922, 325,3344,7627,7628, 711,2044,7629,7630,3952,2219,2787,1936, # 5494
-3953,3345,2220,2251,3789,2300,7631,4431,3790,1258,3279,3954,3204,2138,2950,3955, # 5510
-3956,7632,2221, 258,3205,4432, 101,1227,7633,3280,1755,7634,1391,3281,7635,2910, # 5526
-2056, 893,7636,7637,7638,1402,4161,2342,7639,7640,3206,3556,7641,7642, 878,1325, # 5542
-1780,2788,4433, 259,1385,2577, 744,1183,2267,4434,7643,3957,2502,7644, 684,1024, # 5558
-4162,7645, 472,3557,3449,1165,3282,3958,3959, 322,2152, 881, 455,1695,1152,1340, # 5574
- 660, 554,2153,4435,1058,4436,4163, 830,1065,3346,3960,4437,1923,7646,1703,1918, # 5590
-7647, 932,2268, 122,7648,4438, 947, 677,7649,3791,2627, 297,1905,1924,2269,4439, # 5606
-2317,3283,7650,7651,4164,7652,4165, 84,4166, 112, 989,7653, 547,1059,3961, 701, # 5622
-3558,1019,7654,4167,7655,3450, 942, 639, 457,2301,2451, 993,2951, 407, 851, 494, # 5638
-4440,3347, 927,7656,1237,7657,2421,3348, 573,4168, 680, 921,2911,1279,1874, 285, # 5654
- 790,1448,1983, 719,2167,7658,7659,4441,3962,3963,1649,7660,1541, 563,7661,1077, # 5670
-7662,3349,3041,3451, 511,2997,3964,3965,3667,3966,1268,2564,3350,3207,4442,4443, # 5686
-7663, 535,1048,1276,1189,2912,2028,3142,1438,1373,2834,2952,1134,2012,7664,4169, # 5702
-1238,2578,3086,1259,7665, 700,7666,2953,3143,3668,4170,7667,4171,1146,1875,1906, # 5718
-4444,2601,3967, 781,2422, 132,1589, 203, 147, 273,2789,2402, 898,1786,2154,3968, # 5734
-3969,7668,3792,2790,7669,7670,4445,4446,7671,3208,7672,1635,3793, 965,7673,1804, # 5750
-2690,1516,3559,1121,1082,1329,3284,3970,1449,3794, 65,1128,2835,2913,2759,1590, # 5766
-3795,7674,7675, 12,2658, 45, 976,2579,3144,4447, 517,2528,1013,1037,3209,7676, # 5782
-3796,2836,7677,3797,7678,3452,7679,2602, 614,1998,2318,3798,3087,2724,2628,7680, # 5798
-2580,4172, 599,1269,7681,1810,3669,7682,2691,3088, 759,1060, 489,1805,3351,3285, # 5814
-1358,7683,7684,2386,1387,1215,2629,2252, 490,7685,7686,4173,1759,2387,2343,7687, # 5830
-4448,3799,1907,3971,2630,1806,3210,4449,3453,3286,2760,2344, 874,7688,7689,3454, # 5846
-3670,1858, 91,2914,3671,3042,3800,4450,7690,3145,3972,2659,7691,3455,1202,1403, # 5862
-3801,2954,2529,1517,2503,4451,3456,2504,7692,4452,7693,2692,1885,1495,1731,3973, # 5878
-2365,4453,7694,2029,7695,7696,3974,2693,1216, 237,2581,4174,2319,3975,3802,4454, # 5894
-4455,2694,3560,3457, 445,4456,7697,7698,7699,7700,2761, 61,3976,3672,1822,3977, # 5910
-7701, 687,2045, 935, 925, 405,2660, 703,1096,1859,2725,4457,3978,1876,1367,2695, # 5926
-3352, 918,2105,1781,2476, 334,3287,1611,1093,4458, 564,3146,3458,3673,3353, 945, # 5942
-2631,2057,4459,7702,1925, 872,4175,7703,3459,2696,3089, 349,4176,3674,3979,4460, # 5958
-3803,4177,3675,2155,3980,4461,4462,4178,4463,2403,2046, 782,3981, 400, 251,4179, # 5974
-1624,7704,7705, 277,3676, 299,1265, 476,1191,3804,2121,4180,4181,1109, 205,7706, # 5990
-2582,1000,2156,3561,1860,7707,7708,7709,4464,7710,4465,2565, 107,2477,2157,3982, # 6006
-3460,3147,7711,1533, 541,1301, 158, 753,4182,2872,3562,7712,1696, 370,1088,4183, # 6022
-4466,3563, 579, 327, 440, 162,2240, 269,1937,1374,3461, 968,3043, 56,1396,3090, # 6038
-2106,3288,3354,7713,1926,2158,4467,2998,7714,3564,7715,7716,3677,4468,2478,7717, # 6054
-2791,7718,1650,4469,7719,2603,7720,7721,3983,2661,3355,1149,3356,3984,3805,3985, # 6070
-7722,1076, 49,7723, 951,3211,3289,3290, 450,2837, 920,7724,1811,2792,2366,4184, # 6086
-1908,1138,2367,3806,3462,7725,3212,4470,1909,1147,1518,2423,4471,3807,7726,4472, # 6102
-2388,2604, 260,1795,3213,7727,7728,3808,3291, 708,7729,3565,1704,7730,3566,1351, # 6118
-1618,3357,2999,1886, 944,4185,3358,4186,3044,3359,4187,7731,3678, 422, 413,1714, # 6134
-3292, 500,2058,2345,4188,2479,7732,1344,1910, 954,7733,1668,7734,7735,3986,2404, # 6150
-4189,3567,3809,4190,7736,2302,1318,2505,3091, 133,3092,2873,4473, 629, 31,2838, # 6166
-2697,3810,4474, 850, 949,4475,3987,2955,1732,2088,4191,1496,1852,7737,3988, 620, # 6182
-3214, 981,1242,3679,3360,1619,3680,1643,3293,2139,2452,1970,1719,3463,2168,7738, # 6198
-3215,7739,7740,3361,1828,7741,1277,4476,1565,2047,7742,1636,3568,3093,7743, 869, # 6214
-2839, 655,3811,3812,3094,3989,3000,3813,1310,3569,4477,7744,7745,7746,1733, 558, # 6230
-4478,3681, 335,1549,3045,1756,4192,3682,1945,3464,1829,1291,1192, 470,2726,2107, # 6246
-2793, 913,1054,3990,7747,1027,7748,3046,3991,4479, 982,2662,3362,3148,3465,3216, # 6262
-3217,1946,2794,7749, 571,4480,7750,1830,7751,3570,2583,1523,2424,7752,2089, 984, # 6278
-4481,3683,1959,7753,3684, 852, 923,2795,3466,3685, 969,1519, 999,2048,2320,1705, # 6294
-7754,3095, 615,1662, 151, 597,3992,2405,2321,1049, 275,4482,3686,4193, 568,3687, # 6310
-3571,2480,4194,3688,7755,2425,2270, 409,3218,7756,1566,2874,3467,1002, 769,2840, # 6326
- 194,2090,3149,3689,2222,3294,4195, 628,1505,7757,7758,1763,2177,3001,3993, 521, # 6342
-1161,2584,1787,2203,2406,4483,3994,1625,4196,4197, 412, 42,3096, 464,7759,2632, # 6358
-4484,3363,1760,1571,2875,3468,2530,1219,2204,3814,2633,2140,2368,4485,4486,3295, # 6374
-1651,3364,3572,7760,7761,3573,2481,3469,7762,3690,7763,7764,2271,2091, 460,7765, # 6390
-4487,7766,3002, 962, 588,3574, 289,3219,2634,1116, 52,7767,3047,1796,7768,7769, # 6406
-7770,1467,7771,1598,1143,3691,4198,1984,1734,1067,4488,1280,3365, 465,4489,1572, # 6422
- 510,7772,1927,2241,1812,1644,3575,7773,4490,3692,7774,7775,2663,1573,1534,7776, # 6438
-7777,4199, 536,1807,1761,3470,3815,3150,2635,7778,7779,7780,4491,3471,2915,1911, # 6454
-2796,7781,3296,1122, 377,3220,7782, 360,7783,7784,4200,1529, 551,7785,2059,3693, # 6470
-1769,2426,7786,2916,4201,3297,3097,2322,2108,2030,4492,1404, 136,1468,1479, 672, # 6486
-1171,3221,2303, 271,3151,7787,2762,7788,2049, 678,2727, 865,1947,4493,7789,2013, # 6502
-3995,2956,7790,2728,2223,1397,3048,3694,4494,4495,1735,2917,3366,3576,7791,3816, # 6518
- 509,2841,2453,2876,3817,7792,7793,3152,3153,4496,4202,2531,4497,2304,1166,1010, # 6534
- 552, 681,1887,7794,7795,2957,2958,3996,1287,1596,1861,3154, 358, 453, 736, 175, # 6550
- 478,1117, 905,1167,1097,7796,1853,1530,7797,1706,7798,2178,3472,2287,3695,3473, # 6566
-3577,4203,2092,4204,7799,3367,1193,2482,4205,1458,2190,2205,1862,1888,1421,3298, # 6582
-2918,3049,2179,3474, 595,2122,7800,3997,7801,7802,4206,1707,2636, 223,3696,1359, # 6598
- 751,3098, 183,3475,7803,2797,3003, 419,2369, 633, 704,3818,2389, 241,7804,7805, # 6614
-7806, 838,3004,3697,2272,2763,2454,3819,1938,2050,3998,1309,3099,2242,1181,7807, # 6630
-1136,2206,3820,2370,1446,4207,2305,4498,7808,7809,4208,1055,2605, 484,3698,7810, # 6646
-3999, 625,4209,2273,3368,1499,4210,4000,7811,4001,4211,3222,2274,2275,3476,7812, # 6662
-7813,2764, 808,2606,3699,3369,4002,4212,3100,2532, 526,3370,3821,4213, 955,7814, # 6678
-1620,4214,2637,2427,7815,1429,3700,1669,1831, 994, 928,7816,3578,1260,7817,7818, # 6694
-7819,1948,2288, 741,2919,1626,4215,2729,2455, 867,1184, 362,3371,1392,7820,7821, # 6710
-4003,4216,1770,1736,3223,2920,4499,4500,1928,2698,1459,1158,7822,3050,3372,2877, # 6726
-1292,1929,2506,2842,3701,1985,1187,2071,2014,2607,4217,7823,2566,2507,2169,3702, # 6742
-2483,3299,7824,3703,4501,7825,7826, 666,1003,3005,1022,3579,4218,7827,4502,1813, # 6758
-2253, 574,3822,1603, 295,1535, 705,3823,4219, 283, 858, 417,7828,7829,3224,4503, # 6774
-4504,3051,1220,1889,1046,2276,2456,4004,1393,1599, 689,2567, 388,4220,7830,2484, # 6790
- 802,7831,2798,3824,2060,1405,2254,7832,4505,3825,2109,1052,1345,3225,1585,7833, # 6806
- 809,7834,7835,7836, 575,2730,3477, 956,1552,1469,1144,2323,7837,2324,1560,2457, # 6822
-3580,3226,4005, 616,2207,3155,2180,2289,7838,1832,7839,3478,4506,7840,1319,3704, # 6838
-3705,1211,3581,1023,3227,1293,2799,7841,7842,7843,3826, 607,2306,3827, 762,2878, # 6854
-1439,4221,1360,7844,1485,3052,7845,4507,1038,4222,1450,2061,2638,4223,1379,4508, # 6870
-2585,7846,7847,4224,1352,1414,2325,2921,1172,7848,7849,3828,3829,7850,1797,1451, # 6886
-7851,7852,7853,7854,2922,4006,4007,2485,2346, 411,4008,4009,3582,3300,3101,4509, # 6902
-1561,2664,1452,4010,1375,7855,7856, 47,2959, 316,7857,1406,1591,2923,3156,7858, # 6918
-1025,2141,3102,3157, 354,2731, 884,2224,4225,2407, 508,3706, 726,3583, 996,2428, # 6934
-3584, 729,7859, 392,2191,1453,4011,4510,3707,7860,7861,2458,3585,2608,1675,2800, # 6950
- 919,2347,2960,2348,1270,4511,4012, 73,7862,7863, 647,7864,3228,2843,2255,1550, # 6966
-1346,3006,7865,1332, 883,3479,7866,7867,7868,7869,3301,2765,7870,1212, 831,1347, # 6982
-4226,4512,2326,3830,1863,3053, 720,3831,4513,4514,3832,7871,4227,7872,7873,4515, # 6998
-7874,7875,1798,4516,3708,2609,4517,3586,1645,2371,7876,7877,2924, 669,2208,2665, # 7014
-2429,7878,2879,7879,7880,1028,3229,7881,4228,2408,7882,2256,1353,7883,7884,4518, # 7030
-3158, 518,7885,4013,7886,4229,1960,7887,2142,4230,7888,7889,3007,2349,2350,3833, # 7046
- 516,1833,1454,4014,2699,4231,4519,2225,2610,1971,1129,3587,7890,2766,7891,2961, # 7062
-1422, 577,1470,3008,1524,3373,7892,7893, 432,4232,3054,3480,7894,2586,1455,2508, # 7078
-2226,1972,1175,7895,1020,2732,4015,3481,4520,7896,2733,7897,1743,1361,3055,3482, # 7094
-2639,4016,4233,4521,2290, 895, 924,4234,2170, 331,2243,3056, 166,1627,3057,1098, # 7110
-7898,1232,2880,2227,3374,4522, 657, 403,1196,2372, 542,3709,3375,1600,4235,3483, # 7126
-7899,4523,2767,3230, 576, 530,1362,7900,4524,2533,2666,3710,4017,7901, 842,3834, # 7142
-7902,2801,2031,1014,4018, 213,2700,3376, 665, 621,4236,7903,3711,2925,2430,7904, # 7158
-2431,3302,3588,3377,7905,4237,2534,4238,4525,3589,1682,4239,3484,1380,7906, 724, # 7174
-2277, 600,1670,7907,1337,1233,4526,3103,2244,7908,1621,4527,7909, 651,4240,7910, # 7190
-1612,4241,2611,7911,2844,7912,2734,2307,3058,7913, 716,2459,3059, 174,1255,2701, # 7206
-4019,3590, 548,1320,1398, 728,4020,1574,7914,1890,1197,3060,4021,7915,3061,3062, # 7222
-3712,3591,3713, 747,7916, 635,4242,4528,7917,7918,7919,4243,7920,7921,4529,7922, # 7238
-3378,4530,2432, 451,7923,3714,2535,2072,4244,2735,4245,4022,7924,1764,4531,7925, # 7254
-4246, 350,7926,2278,2390,2486,7927,4247,4023,2245,1434,4024, 488,4532, 458,4248, # 7270
-4025,3715, 771,1330,2391,3835,2568,3159,2159,2409,1553,2667,3160,4249,7928,2487, # 7286
-2881,2612,1720,2702,4250,3379,4533,7929,2536,4251,7930,3231,4252,2768,7931,2015, # 7302
-2736,7932,1155,1017,3716,3836,7933,3303,2308, 201,1864,4253,1430,7934,4026,7935, # 7318
-7936,7937,7938,7939,4254,1604,7940, 414,1865, 371,2587,4534,4535,3485,2016,3104, # 7334
-4536,1708, 960,4255, 887, 389,2171,1536,1663,1721,7941,2228,4027,2351,2926,1580, # 7350
-7942,7943,7944,1744,7945,2537,4537,4538,7946,4539,7947,2073,7948,7949,3592,3380, # 7366
-2882,4256,7950,4257,2640,3381,2802, 673,2703,2460, 709,3486,4028,3593,4258,7951, # 7382
-1148, 502, 634,7952,7953,1204,4540,3594,1575,4541,2613,3717,7954,3718,3105, 948, # 7398
-3232, 121,1745,3837,1110,7955,4259,3063,2509,3009,4029,3719,1151,1771,3838,1488, # 7414
-4030,1986,7956,2433,3487,7957,7958,2093,7959,4260,3839,1213,1407,2803, 531,2737, # 7430
-2538,3233,1011,1537,7960,2769,4261,3106,1061,7961,3720,3721,1866,2883,7962,2017, # 7446
- 120,4262,4263,2062,3595,3234,2309,3840,2668,3382,1954,4542,7963,7964,3488,1047, # 7462
-2704,1266,7965,1368,4543,2845, 649,3383,3841,2539,2738,1102,2846,2669,7966,7967, # 7478
-1999,7968,1111,3596,2962,7969,2488,3842,3597,2804,1854,3384,3722,7970,7971,3385, # 7494
-2410,2884,3304,3235,3598,7972,2569,7973,3599,2805,4031,1460, 856,7974,3600,7975, # 7510
-2885,2963,7976,2886,3843,7977,4264, 632,2510, 875,3844,1697,3845,2291,7978,7979, # 7526
-4544,3010,1239, 580,4545,4265,7980, 914, 936,2074,1190,4032,1039,2123,7981,7982, # 7542
-7983,3386,1473,7984,1354,4266,3846,7985,2172,3064,4033, 915,3305,4267,4268,3306, # 7558
-1605,1834,7986,2739, 398,3601,4269,3847,4034, 328,1912,2847,4035,3848,1331,4270, # 7574
-3011, 937,4271,7987,3602,4036,4037,3387,2160,4546,3388, 524, 742, 538,3065,1012, # 7590
-7988,7989,3849,2461,7990, 658,1103, 225,3850,7991,7992,4547,7993,4548,7994,3236, # 7606
-1243,7995,4038, 963,2246,4549,7996,2705,3603,3161,7997,7998,2588,2327,7999,4550, # 7622
-8000,8001,8002,3489,3307, 957,3389,2540,2032,1930,2927,2462, 870,2018,3604,1746, # 7638
-2770,2771,2434,2463,8003,3851,8004,3723,3107,3724,3490,3390,3725,8005,1179,3066, # 7654
-8006,3162,2373,4272,3726,2541,3163,3108,2740,4039,8007,3391,1556,2542,2292, 977, # 7670
-2887,2033,4040,1205,3392,8008,1765,3393,3164,2124,1271,1689, 714,4551,3491,8009, # 7686
-2328,3852, 533,4273,3605,2181, 617,8010,2464,3308,3492,2310,8011,8012,3165,8013, # 7702
-8014,3853,1987, 618, 427,2641,3493,3394,8015,8016,1244,1690,8017,2806,4274,4552, # 7718
-8018,3494,8019,8020,2279,1576, 473,3606,4275,3395, 972,8021,3607,8022,3067,8023, # 7734
-8024,4553,4554,8025,3727,4041,4042,8026, 153,4555, 356,8027,1891,2888,4276,2143, # 7750
- 408, 803,2352,8028,3854,8029,4277,1646,2570,2511,4556,4557,3855,8030,3856,4278, # 7766
-8031,2411,3396, 752,8032,8033,1961,2964,8034, 746,3012,2465,8035,4279,3728, 698, # 7782
-4558,1892,4280,3608,2543,4559,3609,3857,8036,3166,3397,8037,1823,1302,4043,2706, # 7798
-3858,1973,4281,8038,4282,3167, 823,1303,1288,1236,2848,3495,4044,3398, 774,3859, # 7814
-8039,1581,4560,1304,2849,3860,4561,8040,2435,2161,1083,3237,4283,4045,4284, 344, # 7830
-1173, 288,2311, 454,1683,8041,8042,1461,4562,4046,2589,8043,8044,4563, 985, 894, # 7846
-8045,3399,3168,8046,1913,2928,3729,1988,8047,2110,1974,8048,4047,8049,2571,1194, # 7862
- 425,8050,4564,3169,1245,3730,4285,8051,8052,2850,8053, 636,4565,1855,3861, 760, # 7878
-1799,8054,4286,2209,1508,4566,4048,1893,1684,2293,8055,8056,8057,4287,4288,2210, # 7894
- 479,8058,8059, 832,8060,4049,2489,8061,2965,2490,3731, 990,3109, 627,1814,2642, # 7910
-4289,1582,4290,2125,2111,3496,4567,8062, 799,4291,3170,8063,4568,2112,1737,3013, # 7926
-1018, 543, 754,4292,3309,1676,4569,4570,4050,8064,1489,8065,3497,8066,2614,2889, # 7942
-4051,8067,8068,2966,8069,8070,8071,8072,3171,4571,4572,2182,1722,8073,3238,3239, # 7958
-1842,3610,1715, 481, 365,1975,1856,8074,8075,1962,2491,4573,8076,2126,3611,3240, # 7974
- 433,1894,2063,2075,8077, 602,2741,8078,8079,8080,8081,8082,3014,1628,3400,8083, # 7990
-3172,4574,4052,2890,4575,2512,8084,2544,2772,8085,8086,8087,3310,4576,2891,8088, # 8006
-4577,8089,2851,4578,4579,1221,2967,4053,2513,8090,8091,8092,1867,1989,8093,8094, # 8022
-8095,1895,8096,8097,4580,1896,4054, 318,8098,2094,4055,4293,8099,8100, 485,8101, # 8038
- 938,3862, 553,2670, 116,8102,3863,3612,8103,3498,2671,2773,3401,3311,2807,8104, # 8054
-3613,2929,4056,1747,2930,2968,8105,8106, 207,8107,8108,2672,4581,2514,8109,3015, # 8070
- 890,3614,3864,8110,1877,3732,3402,8111,2183,2353,3403,1652,8112,8113,8114, 941, # 8086
-2294, 208,3499,4057,2019, 330,4294,3865,2892,2492,3733,4295,8115,8116,8117,8118, # 8102
-#Everything below is of no interest for detection purpose
-2515,1613,4582,8119,3312,3866,2516,8120,4058,8121,1637,4059,2466,4583,3867,8122, # 8118
-2493,3016,3734,8123,8124,2192,8125,8126,2162,8127,8128,8129,8130,8131,8132,8133, # 8134
-8134,8135,8136,8137,8138,8139,8140,8141,8142,8143,8144,8145,8146,8147,8148,8149, # 8150
-8150,8151,8152,8153,8154,8155,8156,8157,8158,8159,8160,8161,8162,8163,8164,8165, # 8166
-8166,8167,8168,8169,8170,8171,8172,8173,8174,8175,8176,8177,8178,8179,8180,8181, # 8182
-8182,8183,8184,8185,8186,8187,8188,8189,8190,8191,8192,8193,8194,8195,8196,8197, # 8198
-8198,8199,8200,8201,8202,8203,8204,8205,8206,8207,8208,8209,8210,8211,8212,8213, # 8214
-8214,8215,8216,8217,8218,8219,8220,8221,8222,8223,8224,8225,8226,8227,8228,8229, # 8230
-8230,8231,8232,8233,8234,8235,8236,8237,8238,8239,8240,8241,8242,8243,8244,8245, # 8246
-8246,8247,8248,8249,8250,8251,8252,8253,8254,8255,8256,8257,8258,8259,8260,8261, # 8262
-8262,8263,8264,8265,8266,8267,8268,8269,8270,8271,8272,8273,8274,8275,8276,8277, # 8278
-8278,8279,8280,8281,8282,8283,8284,8285,8286,8287,8288,8289,8290,8291,8292,8293, # 8294
-8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,8304,8305,8306,8307,8308,8309, # 8310
-8310,8311,8312,8313,8314,8315,8316,8317,8318,8319,8320,8321,8322,8323,8324,8325, # 8326
-8326,8327,8328,8329,8330,8331,8332,8333,8334,8335,8336,8337,8338,8339,8340,8341, # 8342
-8342,8343,8344,8345,8346,8347,8348,8349,8350,8351,8352,8353,8354,8355,8356,8357, # 8358
-8358,8359,8360,8361,8362,8363,8364,8365,8366,8367,8368,8369,8370,8371,8372,8373, # 8374
-8374,8375,8376,8377,8378,8379,8380,8381,8382,8383,8384,8385,8386,8387,8388,8389, # 8390
-8390,8391,8392,8393,8394,8395,8396,8397,8398,8399,8400,8401,8402,8403,8404,8405, # 8406
-8406,8407,8408,8409,8410,8411,8412,8413,8414,8415,8416,8417,8418,8419,8420,8421, # 8422
-8422,8423,8424,8425,8426,8427,8428,8429,8430,8431,8432,8433,8434,8435,8436,8437, # 8438
-8438,8439,8440,8441,8442,8443,8444,8445,8446,8447,8448,8449,8450,8451,8452,8453, # 8454
-8454,8455,8456,8457,8458,8459,8460,8461,8462,8463,8464,8465,8466,8467,8468,8469, # 8470
-8470,8471,8472,8473,8474,8475,8476,8477,8478,8479,8480,8481,8482,8483,8484,8485, # 8486
-8486,8487,8488,8489,8490,8491,8492,8493,8494,8495,8496,8497,8498,8499,8500,8501, # 8502
-8502,8503,8504,8505,8506,8507,8508,8509,8510,8511,8512,8513,8514,8515,8516,8517, # 8518
-8518,8519,8520,8521,8522,8523,8524,8525,8526,8527,8528,8529,8530,8531,8532,8533, # 8534
-8534,8535,8536,8537,8538,8539,8540,8541,8542,8543,8544,8545,8546,8547,8548,8549, # 8550
-8550,8551,8552,8553,8554,8555,8556,8557,8558,8559,8560,8561,8562,8563,8564,8565, # 8566
-8566,8567,8568,8569,8570,8571,8572,8573,8574,8575,8576,8577,8578,8579,8580,8581, # 8582
-8582,8583,8584,8585,8586,8587,8588,8589,8590,8591,8592,8593,8594,8595,8596,8597, # 8598
-8598,8599,8600,8601,8602,8603,8604,8605,8606,8607,8608,8609,8610,8611,8612,8613, # 8614
-8614,8615,8616,8617,8618,8619,8620,8621,8622,8623,8624,8625,8626,8627,8628,8629, # 8630
-8630,8631,8632,8633,8634,8635,8636,8637,8638,8639,8640,8641,8642,8643,8644,8645, # 8646
-8646,8647,8648,8649,8650,8651,8652,8653,8654,8655,8656,8657,8658,8659,8660,8661, # 8662
-8662,8663,8664,8665,8666,8667,8668,8669,8670,8671,8672,8673,8674,8675,8676,8677, # 8678
-8678,8679,8680,8681,8682,8683,8684,8685,8686,8687,8688,8689,8690,8691,8692,8693, # 8694
-8694,8695,8696,8697,8698,8699,8700,8701,8702,8703,8704,8705,8706,8707,8708,8709, # 8710
-8710,8711,8712,8713,8714,8715,8716,8717,8718,8719,8720,8721,8722,8723,8724,8725, # 8726
-8726,8727,8728,8729,8730,8731,8732,8733,8734,8735,8736,8737,8738,8739,8740,8741) # 8742
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euctwprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euctwprober.py
deleted file mode 100644
index fe652fe..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/euctwprober.py
+++ /dev/null
@@ -1,41 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .mbcharsetprober import MultiByteCharSetProber
-from .codingstatemachine import CodingStateMachine
-from .chardistribution import EUCTWDistributionAnalysis
-from .mbcssm import EUCTWSMModel
-
-class EUCTWProber(MultiByteCharSetProber):
- def __init__(self):
- MultiByteCharSetProber.__init__(self)
- self._mCodingSM = CodingStateMachine(EUCTWSMModel)
- self._mDistributionAnalyzer = EUCTWDistributionAnalysis()
- self.reset()
-
- def get_charset_name(self):
- return "EUC-TW"
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/gb2312freq.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/gb2312freq.py
deleted file mode 100644
index 1238f51..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/gb2312freq.py
+++ /dev/null
@@ -1,472 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# GB2312 most frequently used character table
-#
-# Char to FreqOrder table , from hz6763
-
-# 512 --> 0.79 -- 0.79
-# 1024 --> 0.92 -- 0.13
-# 2048 --> 0.98 -- 0.06
-# 6768 --> 1.00 -- 0.02
-#
-# Ideal Distribution Ratio = 0.79135/(1-0.79135) = 3.79
-# Random Distribution Ration = 512 / (3755 - 512) = 0.157
-#
-# Typical Distribution Ratio about 25% of Ideal one, still much higher that RDR
-
-GB2312_TYPICAL_DISTRIBUTION_RATIO = 0.9
-
-GB2312_TABLE_SIZE = 3760
-
-GB2312CharToFreqOrder = (
-1671, 749,1443,2364,3924,3807,2330,3921,1704,3463,2691,1511,1515, 572,3191,2205,
-2361, 224,2558, 479,1711, 963,3162, 440,4060,1905,2966,2947,3580,2647,3961,3842,
-2204, 869,4207, 970,2678,5626,2944,2956,1479,4048, 514,3595, 588,1346,2820,3409,
- 249,4088,1746,1873,2047,1774, 581,1813, 358,1174,3590,1014,1561,4844,2245, 670,
-1636,3112, 889,1286, 953, 556,2327,3060,1290,3141, 613, 185,3477,1367, 850,3820,
-1715,2428,2642,2303,2732,3041,2562,2648,3566,3946,1349, 388,3098,2091,1360,3585,
- 152,1687,1539, 738,1559, 59,1232,2925,2267,1388,1249,1741,1679,2960, 151,1566,
-1125,1352,4271, 924,4296, 385,3166,4459, 310,1245,2850, 70,3285,2729,3534,3575,
-2398,3298,3466,1960,2265, 217,3647, 864,1909,2084,4401,2773,1010,3269,5152, 853,
-3051,3121,1244,4251,1895, 364,1499,1540,2313,1180,3655,2268, 562, 715,2417,3061,
- 544, 336,3768,2380,1752,4075, 950, 280,2425,4382, 183,2759,3272, 333,4297,2155,
-1688,2356,1444,1039,4540, 736,1177,3349,2443,2368,2144,2225, 565, 196,1482,3406,
- 927,1335,4147, 692, 878,1311,1653,3911,3622,1378,4200,1840,2969,3149,2126,1816,
-2534,1546,2393,2760, 737,2494, 13, 447, 245,2747, 38,2765,2129,2589,1079, 606,
- 360, 471,3755,2890, 404, 848, 699,1785,1236, 370,2221,1023,3746,2074,2026,2023,
-2388,1581,2119, 812,1141,3091,2536,1519, 804,2053, 406,1596,1090, 784, 548,4414,
-1806,2264,2936,1100, 343,4114,5096, 622,3358, 743,3668,1510,1626,5020,3567,2513,
-3195,4115,5627,2489,2991, 24,2065,2697,1087,2719, 48,1634, 315, 68, 985,2052,
- 198,2239,1347,1107,1439, 597,2366,2172, 871,3307, 919,2487,2790,1867, 236,2570,
-1413,3794, 906,3365,3381,1701,1982,1818,1524,2924,1205, 616,2586,2072,2004, 575,
- 253,3099, 32,1365,1182, 197,1714,2454,1201, 554,3388,3224,2748, 756,2587, 250,
-2567,1507,1517,3529,1922,2761,2337,3416,1961,1677,2452,2238,3153, 615, 911,1506,
-1474,2495,1265,1906,2749,3756,3280,2161, 898,2714,1759,3450,2243,2444, 563, 26,
-3286,2266,3769,3344,2707,3677, 611,1402, 531,1028,2871,4548,1375, 261,2948, 835,
-1190,4134, 353, 840,2684,1900,3082,1435,2109,1207,1674, 329,1872,2781,4055,2686,
-2104, 608,3318,2423,2957,2768,1108,3739,3512,3271,3985,2203,1771,3520,1418,2054,
-1681,1153, 225,1627,2929, 162,2050,2511,3687,1954, 124,1859,2431,1684,3032,2894,
- 585,4805,3969,2869,2704,2088,2032,2095,3656,2635,4362,2209, 256, 518,2042,2105,
-3777,3657, 643,2298,1148,1779, 190, 989,3544, 414, 11,2135,2063,2979,1471, 403,
-3678, 126, 770,1563, 671,2499,3216,2877, 600,1179, 307,2805,4937,1268,1297,2694,
- 252,4032,1448,1494,1331,1394, 127,2256, 222,1647,1035,1481,3056,1915,1048, 873,
-3651, 210, 33,1608,2516, 200,1520, 415, 102, 0,3389,1287, 817, 91,3299,2940,
- 836,1814, 549,2197,1396,1669,2987,3582,2297,2848,4528,1070, 687, 20,1819, 121,
-1552,1364,1461,1968,2617,3540,2824,2083, 177, 948,4938,2291, 110,4549,2066, 648,
-3359,1755,2110,2114,4642,4845,1693,3937,3308,1257,1869,2123, 208,1804,3159,2992,
-2531,2549,3361,2418,1350,2347,2800,2568,1291,2036,2680, 72, 842,1990, 212,1233,
-1154,1586, 75,2027,3410,4900,1823,1337,2710,2676, 728,2810,1522,3026,4995, 157,
- 755,1050,4022, 710, 785,1936,2194,2085,1406,2777,2400, 150,1250,4049,1206, 807,
-1910, 534, 529,3309,1721,1660, 274, 39,2827, 661,2670,1578, 925,3248,3815,1094,
-4278,4901,4252, 41,1150,3747,2572,2227,4501,3658,4902,3813,3357,3617,2884,2258,
- 887, 538,4187,3199,1294,2439,3042,2329,2343,2497,1255, 107, 543,1527, 521,3478,
-3568, 194,5062, 15, 961,3870,1241,1192,2664, 66,5215,3260,2111,1295,1127,2152,
-3805,4135, 901,1164,1976, 398,1278, 530,1460, 748, 904,1054,1966,1426, 53,2909,
- 509, 523,2279,1534, 536,1019, 239,1685, 460,2353, 673,1065,2401,3600,4298,2272,
-1272,2363, 284,1753,3679,4064,1695, 81, 815,2677,2757,2731,1386, 859, 500,4221,
-2190,2566, 757,1006,2519,2068,1166,1455, 337,2654,3203,1863,1682,1914,3025,1252,
-1409,1366, 847, 714,2834,2038,3209, 964,2970,1901, 885,2553,1078,1756,3049, 301,
-1572,3326, 688,2130,1996,2429,1805,1648,2930,3421,2750,3652,3088, 262,1158,1254,
- 389,1641,1812, 526,1719, 923,2073,1073,1902, 468, 489,4625,1140, 857,2375,3070,
-3319,2863, 380, 116,1328,2693,1161,2244, 273,1212,1884,2769,3011,1775,1142, 461,
-3066,1200,2147,2212, 790, 702,2695,4222,1601,1058, 434,2338,5153,3640, 67,2360,
-4099,2502, 618,3472,1329, 416,1132, 830,2782,1807,2653,3211,3510,1662, 192,2124,
- 296,3979,1739,1611,3684, 23, 118, 324, 446,1239,1225, 293,2520,3814,3795,2535,
-3116, 17,1074, 467,2692,2201, 387,2922, 45,1326,3055,1645,3659,2817, 958, 243,
-1903,2320,1339,2825,1784,3289, 356, 576, 865,2315,2381,3377,3916,1088,3122,1713,
-1655, 935, 628,4689,1034,1327, 441, 800, 720, 894,1979,2183,1528,5289,2702,1071,
-4046,3572,2399,1571,3281, 79, 761,1103, 327, 134, 758,1899,1371,1615, 879, 442,
- 215,2605,2579, 173,2048,2485,1057,2975,3317,1097,2253,3801,4263,1403,1650,2946,
- 814,4968,3487,1548,2644,1567,1285, 2, 295,2636, 97, 946,3576, 832, 141,4257,
-3273, 760,3821,3521,3156,2607, 949,1024,1733,1516,1803,1920,2125,2283,2665,3180,
-1501,2064,3560,2171,1592, 803,3518,1416, 732,3897,4258,1363,1362,2458, 119,1427,
- 602,1525,2608,1605,1639,3175, 694,3064, 10, 465, 76,2000,4846,4208, 444,3781,
-1619,3353,2206,1273,3796, 740,2483, 320,1723,2377,3660,2619,1359,1137,1762,1724,
-2345,2842,1850,1862, 912, 821,1866, 612,2625,1735,2573,3369,1093, 844, 89, 937,
- 930,1424,3564,2413,2972,1004,3046,3019,2011, 711,3171,1452,4178, 428, 801,1943,
- 432, 445,2811, 206,4136,1472, 730, 349, 73, 397,2802,2547, 998,1637,1167, 789,
- 396,3217, 154,1218, 716,1120,1780,2819,4826,1931,3334,3762,2139,1215,2627, 552,
-3664,3628,3232,1405,2383,3111,1356,2652,3577,3320,3101,1703, 640,1045,1370,1246,
-4996, 371,1575,2436,1621,2210, 984,4033,1734,2638, 16,4529, 663,2755,3255,1451,
-3917,2257,1253,1955,2234,1263,2951, 214,1229, 617, 485, 359,1831,1969, 473,2310,
- 750,2058, 165, 80,2864,2419, 361,4344,2416,2479,1134, 796,3726,1266,2943, 860,
-2715, 938, 390,2734,1313,1384, 248, 202, 877,1064,2854, 522,3907, 279,1602, 297,
-2357, 395,3740, 137,2075, 944,4089,2584,1267,3802, 62,1533,2285, 178, 176, 780,
-2440, 201,3707, 590, 478,1560,4354,2117,1075, 30, 74,4643,4004,1635,1441,2745,
- 776,2596, 238,1077,1692,1912,2844, 605, 499,1742,3947, 241,3053, 980,1749, 936,
-2640,4511,2582, 515,1543,2162,5322,2892,2993, 890,2148,1924, 665,1827,3581,1032,
- 968,3163, 339,1044,1896, 270, 583,1791,1720,4367,1194,3488,3669, 43,2523,1657,
- 163,2167, 290,1209,1622,3378, 550, 634,2508,2510, 695,2634,2384,2512,1476,1414,
- 220,1469,2341,2138,2852,3183,2900,4939,2865,3502,1211,3680, 854,3227,1299,2976,
-3172, 186,2998,1459, 443,1067,3251,1495, 321,1932,3054, 909, 753,1410,1828, 436,
-2441,1119,1587,3164,2186,1258, 227, 231,1425,1890,3200,3942, 247, 959, 725,5254,
-2741, 577,2158,2079, 929, 120, 174, 838,2813, 591,1115, 417,2024, 40,3240,1536,
-1037, 291,4151,2354, 632,1298,2406,2500,3535,1825,1846,3451, 205,1171, 345,4238,
- 18,1163, 811, 685,2208,1217, 425,1312,1508,1175,4308,2552,1033, 587,1381,3059,
-2984,3482, 340,1316,4023,3972, 792,3176, 519, 777,4690, 918, 933,4130,2981,3741,
- 90,3360,2911,2200,5184,4550, 609,3079,2030, 272,3379,2736, 363,3881,1130,1447,
- 286, 779, 357,1169,3350,3137,1630,1220,2687,2391, 747,1277,3688,2618,2682,2601,
-1156,3196,5290,4034,3102,1689,3596,3128, 874, 219,2783, 798, 508,1843,2461, 269,
-1658,1776,1392,1913,2983,3287,2866,2159,2372, 829,4076, 46,4253,2873,1889,1894,
- 915,1834,1631,2181,2318, 298, 664,2818,3555,2735, 954,3228,3117, 527,3511,2173,
- 681,2712,3033,2247,2346,3467,1652, 155,2164,3382, 113,1994, 450, 899, 494, 994,
-1237,2958,1875,2336,1926,3727, 545,1577,1550, 633,3473, 204,1305,3072,2410,1956,
-2471, 707,2134, 841,2195,2196,2663,3843,1026,4940, 990,3252,4997, 368,1092, 437,
-3212,3258,1933,1829, 675,2977,2893, 412, 943,3723,4644,3294,3283,2230,2373,5154,
-2389,2241,2661,2323,1404,2524, 593, 787, 677,3008,1275,2059, 438,2709,2609,2240,
-2269,2246,1446, 36,1568,1373,3892,1574,2301,1456,3962, 693,2276,5216,2035,1143,
-2720,1919,1797,1811,2763,4137,2597,1830,1699,1488,1198,2090, 424,1694, 312,3634,
-3390,4179,3335,2252,1214, 561,1059,3243,2295,2561, 975,5155,2321,2751,3772, 472,
-1537,3282,3398,1047,2077,2348,2878,1323,3340,3076, 690,2906, 51, 369, 170,3541,
-1060,2187,2688,3670,2541,1083,1683, 928,3918, 459, 109,4427, 599,3744,4286, 143,
-2101,2730,2490, 82,1588,3036,2121, 281,1860, 477,4035,1238,2812,3020,2716,3312,
-1530,2188,2055,1317, 843, 636,1808,1173,3495, 649, 181,1002, 147,3641,1159,2414,
-3750,2289,2795, 813,3123,2610,1136,4368, 5,3391,4541,2174, 420, 429,1728, 754,
-1228,2115,2219, 347,2223,2733, 735,1518,3003,2355,3134,1764,3948,3329,1888,2424,
-1001,1234,1972,3321,3363,1672,1021,1450,1584, 226, 765, 655,2526,3404,3244,2302,
-3665, 731, 594,2184, 319,1576, 621, 658,2656,4299,2099,3864,1279,2071,2598,2739,
- 795,3086,3699,3908,1707,2352,2402,1382,3136,2475,1465,4847,3496,3865,1085,3004,
-2591,1084, 213,2287,1963,3565,2250, 822, 793,4574,3187,1772,1789,3050, 595,1484,
-1959,2770,1080,2650, 456, 422,2996, 940,3322,4328,4345,3092,2742, 965,2784, 739,
-4124, 952,1358,2498,2949,2565, 332,2698,2378, 660,2260,2473,4194,3856,2919, 535,
-1260,2651,1208,1428,1300,1949,1303,2942, 433,2455,2450,1251,1946, 614,1269, 641,
-1306,1810,2737,3078,2912, 564,2365,1419,1415,1497,4460,2367,2185,1379,3005,1307,
-3218,2175,1897,3063, 682,1157,4040,4005,1712,1160,1941,1399, 394, 402,2952,1573,
-1151,2986,2404, 862, 299,2033,1489,3006, 346, 171,2886,3401,1726,2932, 168,2533,
- 47,2507,1030,3735,1145,3370,1395,1318,1579,3609,4560,2857,4116,1457,2529,1965,
- 504,1036,2690,2988,2405, 745,5871, 849,2397,2056,3081, 863,2359,3857,2096, 99,
-1397,1769,2300,4428,1643,3455,1978,1757,3718,1440, 35,4879,3742,1296,4228,2280,
- 160,5063,1599,2013, 166, 520,3479,1646,3345,3012, 490,1937,1545,1264,2182,2505,
-1096,1188,1369,1436,2421,1667,2792,2460,1270,2122, 727,3167,2143, 806,1706,1012,
-1800,3037, 960,2218,1882, 805, 139,2456,1139,1521, 851,1052,3093,3089, 342,2039,
- 744,5097,1468,1502,1585,2087, 223, 939, 326,2140,2577, 892,2481,1623,4077, 982,
-3708, 135,2131, 87,2503,3114,2326,1106, 876,1616, 547,2997,2831,2093,3441,4530,
-4314, 9,3256,4229,4148, 659,1462,1986,1710,2046,2913,2231,4090,4880,5255,3392,
-3274,1368,3689,4645,1477, 705,3384,3635,1068,1529,2941,1458,3782,1509, 100,1656,
-2548, 718,2339, 408,1590,2780,3548,1838,4117,3719,1345,3530, 717,3442,2778,3220,
-2898,1892,4590,3614,3371,2043,1998,1224,3483, 891, 635, 584,2559,3355, 733,1766,
-1729,1172,3789,1891,2307, 781,2982,2271,1957,1580,5773,2633,2005,4195,3097,1535,
-3213,1189,1934,5693,3262, 586,3118,1324,1598, 517,1564,2217,1868,1893,4445,3728,
-2703,3139,1526,1787,1992,3882,2875,1549,1199,1056,2224,1904,2711,5098,4287, 338,
-1993,3129,3489,2689,1809,2815,1997, 957,1855,3898,2550,3275,3057,1105,1319, 627,
-1505,1911,1883,3526, 698,3629,3456,1833,1431, 746, 77,1261,2017,2296,1977,1885,
- 125,1334,1600, 525,1798,1109,2222,1470,1945, 559,2236,1186,3443,2476,1929,1411,
-2411,3135,1777,3372,2621,1841,1613,3229, 668,1430,1839,2643,2916, 195,1989,2671,
-2358,1387, 629,3205,2293,5256,4439, 123,1310, 888,1879,4300,3021,3605,1003,1162,
-3192,2910,2010, 140,2395,2859, 55,1082,2012,2901, 662, 419,2081,1438, 680,2774,
-4654,3912,1620,1731,1625,5035,4065,2328, 512,1344, 802,5443,2163,2311,2537, 524,
-3399, 98,1155,2103,1918,2606,3925,2816,1393,2465,1504,3773,2177,3963,1478,4346,
- 180,1113,4655,3461,2028,1698, 833,2696,1235,1322,1594,4408,3623,3013,3225,2040,
-3022, 541,2881, 607,3632,2029,1665,1219, 639,1385,1686,1099,2803,3231,1938,3188,
-2858, 427, 676,2772,1168,2025, 454,3253,2486,3556, 230,1950, 580, 791,1991,1280,
-1086,1974,2034, 630, 257,3338,2788,4903,1017, 86,4790, 966,2789,1995,1696,1131,
- 259,3095,4188,1308, 179,1463,5257, 289,4107,1248, 42,3413,1725,2288, 896,1947,
- 774,4474,4254, 604,3430,4264, 392,2514,2588, 452, 237,1408,3018, 988,4531,1970,
-3034,3310, 540,2370,1562,1288,2990, 502,4765,1147, 4,1853,2708, 207, 294,2814,
-4078,2902,2509, 684, 34,3105,3532,2551, 644, 709,2801,2344, 573,1727,3573,3557,
-2021,1081,3100,4315,2100,3681, 199,2263,1837,2385, 146,3484,1195,2776,3949, 997,
-1939,3973,1008,1091,1202,1962,1847,1149,4209,5444,1076, 493, 117,5400,2521, 972,
-1490,2934,1796,4542,2374,1512,2933,2657, 413,2888,1135,2762,2314,2156,1355,2369,
- 766,2007,2527,2170,3124,2491,2593,2632,4757,2437, 234,3125,3591,1898,1750,1376,
-1942,3468,3138, 570,2127,2145,3276,4131, 962, 132,1445,4196, 19, 941,3624,3480,
-3366,1973,1374,4461,3431,2629, 283,2415,2275, 808,2887,3620,2112,2563,1353,3610,
- 955,1089,3103,1053, 96, 88,4097, 823,3808,1583, 399, 292,4091,3313, 421,1128,
- 642,4006, 903,2539,1877,2082, 596, 29,4066,1790, 722,2157, 130, 995,1569, 769,
-1485, 464, 513,2213, 288,1923,1101,2453,4316, 133, 486,2445, 50, 625, 487,2207,
- 57, 423, 481,2962, 159,3729,1558, 491, 303, 482, 501, 240,2837, 112,3648,2392,
-1783, 362, 8,3433,3422, 610,2793,3277,1390,1284,1654, 21,3823, 734, 367, 623,
- 193, 287, 374,1009,1483, 816, 476, 313,2255,2340,1262,2150,2899,1146,2581, 782,
-2116,1659,2018,1880, 255,3586,3314,1110,2867,2137,2564, 986,2767,5185,2006, 650,
- 158, 926, 762, 881,3157,2717,2362,3587, 306,3690,3245,1542,3077,2427,1691,2478,
-2118,2985,3490,2438, 539,2305, 983, 129,1754, 355,4201,2386, 827,2923, 104,1773,
-2838,2771, 411,2905,3919, 376, 767, 122,1114, 828,2422,1817,3506, 266,3460,1007,
-1609,4998, 945,2612,4429,2274, 726,1247,1964,2914,2199,2070,4002,4108, 657,3323,
-1422, 579, 455,2764,4737,1222,2895,1670, 824,1223,1487,2525, 558, 861,3080, 598,
-2659,2515,1967, 752,2583,2376,2214,4180, 977, 704,2464,4999,2622,4109,1210,2961,
- 819,1541, 142,2284, 44, 418, 457,1126,3730,4347,4626,1644,1876,3671,1864, 302,
-1063,5694, 624, 723,1984,3745,1314,1676,2488,1610,1449,3558,3569,2166,2098, 409,
-1011,2325,3704,2306, 818,1732,1383,1824,1844,3757, 999,2705,3497,1216,1423,2683,
-2426,2954,2501,2726,2229,1475,2554,5064,1971,1794,1666,2014,1343, 783, 724, 191,
-2434,1354,2220,5065,1763,2752,2472,4152, 131, 175,2885,3434, 92,1466,4920,2616,
-3871,3872,3866, 128,1551,1632, 669,1854,3682,4691,4125,1230, 188,2973,3290,1302,
-1213, 560,3266, 917, 763,3909,3249,1760, 868,1958, 764,1782,2097, 145,2277,3774,
-4462, 64,1491,3062, 971,2132,3606,2442, 221,1226,1617, 218, 323,1185,3207,3147,
- 571, 619,1473,1005,1744,2281, 449,1887,2396,3685, 275, 375,3816,1743,3844,3731,
- 845,1983,2350,4210,1377, 773, 967,3499,3052,3743,2725,4007,1697,1022,3943,1464,
-3264,2855,2722,1952,1029,2839,2467, 84,4383,2215, 820,1391,2015,2448,3672, 377,
-1948,2168, 797,2545,3536,2578,2645, 94,2874,1678, 405,1259,3071, 771, 546,1315,
- 470,1243,3083, 895,2468, 981, 969,2037, 846,4181, 653,1276,2928, 14,2594, 557,
-3007,2474, 156, 902,1338,1740,2574, 537,2518, 973,2282,2216,2433,1928, 138,2903,
-1293,2631,1612, 646,3457, 839,2935, 111, 496,2191,2847, 589,3186, 149,3994,2060,
-4031,2641,4067,3145,1870, 37,3597,2136,1025,2051,3009,3383,3549,1121,1016,3261,
-1301, 251,2446,2599,2153, 872,3246, 637, 334,3705, 831, 884, 921,3065,3140,4092,
-2198,1944, 246,2964, 108,2045,1152,1921,2308,1031, 203,3173,4170,1907,3890, 810,
-1401,2003,1690, 506, 647,1242,2828,1761,1649,3208,2249,1589,3709,2931,5156,1708,
- 498, 666,2613, 834,3817,1231, 184,2851,1124, 883,3197,2261,3710,1765,1553,2658,
-1178,2639,2351, 93,1193, 942,2538,2141,4402, 235,1821, 870,1591,2192,1709,1871,
-3341,1618,4126,2595,2334, 603, 651, 69, 701, 268,2662,3411,2555,1380,1606, 503,
- 448, 254,2371,2646, 574,1187,2309,1770, 322,2235,1292,1801, 305, 566,1133, 229,
-2067,2057, 706, 167, 483,2002,2672,3295,1820,3561,3067, 316, 378,2746,3452,1112,
- 136,1981, 507,1651,2917,1117, 285,4591, 182,2580,3522,1304, 335,3303,1835,2504,
-1795,1792,2248, 674,1018,2106,2449,1857,2292,2845, 976,3047,1781,2600,2727,1389,
-1281, 52,3152, 153, 265,3950, 672,3485,3951,4463, 430,1183, 365, 278,2169, 27,
-1407,1336,2304, 209,1340,1730,2202,1852,2403,2883, 979,1737,1062, 631,2829,2542,
-3876,2592, 825,2086,2226,3048,3625, 352,1417,3724, 542, 991, 431,1351,3938,1861,
-2294, 826,1361,2927,3142,3503,1738, 463,2462,2723, 582,1916,1595,2808, 400,3845,
-3891,2868,3621,2254, 58,2492,1123, 910,2160,2614,1372,1603,1196,1072,3385,1700,
-3267,1980, 696, 480,2430, 920, 799,1570,2920,1951,2041,4047,2540,1321,4223,2469,
-3562,2228,1271,2602, 401,2833,3351,2575,5157, 907,2312,1256, 410, 263,3507,1582,
- 996, 678,1849,2316,1480, 908,3545,2237, 703,2322, 667,1826,2849,1531,2604,2999,
-2407,3146,2151,2630,1786,3711, 469,3542, 497,3899,2409, 858, 837,4446,3393,1274,
- 786, 620,1845,2001,3311, 484, 308,3367,1204,1815,3691,2332,1532,2557,1842,2020,
-2724,1927,2333,4440, 567, 22,1673,2728,4475,1987,1858,1144,1597, 101,1832,3601,
- 12, 974,3783,4391, 951,1412, 1,3720, 453,4608,4041, 528,1041,1027,3230,2628,
-1129, 875,1051,3291,1203,2262,1069,2860,2799,2149,2615,3278, 144,1758,3040, 31,
- 475,1680, 366,2685,3184, 311,1642,4008,2466,5036,1593,1493,2809, 216,1420,1668,
- 233, 304,2128,3284, 232,1429,1768,1040,2008,3407,2740,2967,2543, 242,2133, 778,
-1565,2022,2620, 505,2189,2756,1098,2273, 372,1614, 708, 553,2846,2094,2278, 169,
-3626,2835,4161, 228,2674,3165, 809,1454,1309, 466,1705,1095, 900,3423, 880,2667,
-3751,5258,2317,3109,2571,4317,2766,1503,1342, 866,4447,1118, 63,2076, 314,1881,
-1348,1061, 172, 978,3515,1747, 532, 511,3970, 6, 601, 905,2699,3300,1751, 276,
-1467,3725,2668, 65,4239,2544,2779,2556,1604, 578,2451,1802, 992,2331,2624,1320,
-3446, 713,1513,1013, 103,2786,2447,1661, 886,1702, 916, 654,3574,2031,1556, 751,
-2178,2821,2179,1498,1538,2176, 271, 914,2251,2080,1325, 638,1953,2937,3877,2432,
-2754, 95,3265,1716, 260,1227,4083, 775, 106,1357,3254, 426,1607, 555,2480, 772,
-1985, 244,2546, 474, 495,1046,2611,1851,2061, 71,2089,1675,2590, 742,3758,2843,
-3222,1433, 267,2180,2576,2826,2233,2092,3913,2435, 956,1745,3075, 856,2113,1116,
- 451, 3,1988,2896,1398, 993,2463,1878,2049,1341,2718,2721,2870,2108, 712,2904,
-4363,2753,2324, 277,2872,2349,2649, 384, 987, 435, 691,3000, 922, 164,3939, 652,
-1500,1184,4153,2482,3373,2165,4848,2335,3775,3508,3154,2806,2830,1554,2102,1664,
-2530,1434,2408, 893,1547,2623,3447,2832,2242,2532,3169,2856,3223,2078, 49,3770,
-3469, 462, 318, 656,2259,3250,3069, 679,1629,2758, 344,1138,1104,3120,1836,1283,
-3115,2154,1437,4448, 934, 759,1999, 794,2862,1038, 533,2560,1722,2342, 855,2626,
-1197,1663,4476,3127, 85,4240,2528, 25,1111,1181,3673, 407,3470,4561,2679,2713,
- 768,1925,2841,3986,1544,1165, 932, 373,1240,2146,1930,2673, 721,4766, 354,4333,
- 391,2963, 187, 61,3364,1442,1102, 330,1940,1767, 341,3809,4118, 393,2496,2062,
-2211, 105, 331, 300, 439, 913,1332, 626, 379,3304,1557, 328, 689,3952, 309,1555,
- 931, 317,2517,3027, 325, 569, 686,2107,3084, 60,1042,1333,2794, 264,3177,4014,
-1628, 258,3712, 7,4464,1176,1043,1778, 683, 114,1975, 78,1492, 383,1886, 510,
- 386, 645,5291,2891,2069,3305,4138,3867,2939,2603,2493,1935,1066,1848,3588,1015,
-1282,1289,4609, 697,1453,3044,2666,3611,1856,2412, 54, 719,1330, 568,3778,2459,
-1748, 788, 492, 551,1191,1000, 488,3394,3763, 282,1799, 348,2016,1523,3155,2390,
-1049, 382,2019,1788,1170, 729,2968,3523, 897,3926,2785,2938,3292, 350,2319,3238,
-1718,1717,2655,3453,3143,4465, 161,2889,2980,2009,1421, 56,1908,1640,2387,2232,
-1917,1874,2477,4921, 148, 83,3438, 592,4245,2882,1822,1055, 741, 115,1496,1624,
- 381,1638,4592,1020, 516,3214, 458, 947,4575,1432, 211,1514,2926,1865,2142, 189,
- 852,1221,1400,1486, 882,2299,4036, 351, 28,1122, 700,6479,6480,6481,6482,6483, # last 512
-#Everything below is of no interest for detection purpose
-5508,6484,3900,3414,3974,4441,4024,3537,4037,5628,5099,3633,6485,3148,6486,3636,
-5509,3257,5510,5973,5445,5872,4941,4403,3174,4627,5873,6276,2286,4230,5446,5874,
-5122,6102,6103,4162,5447,5123,5323,4849,6277,3980,3851,5066,4246,5774,5067,6278,
-3001,2807,5695,3346,5775,5974,5158,5448,6487,5975,5976,5776,3598,6279,5696,4806,
-4211,4154,6280,6488,6489,6490,6281,4212,5037,3374,4171,6491,4562,4807,4722,4827,
-5977,6104,4532,4079,5159,5324,5160,4404,3858,5359,5875,3975,4288,4610,3486,4512,
-5325,3893,5360,6282,6283,5560,2522,4231,5978,5186,5449,2569,3878,6284,5401,3578,
-4415,6285,4656,5124,5979,2506,4247,4449,3219,3417,4334,4969,4329,6492,4576,4828,
-4172,4416,4829,5402,6286,3927,3852,5361,4369,4830,4477,4867,5876,4173,6493,6105,
-4657,6287,6106,5877,5450,6494,4155,4868,5451,3700,5629,4384,6288,6289,5878,3189,
-4881,6107,6290,6495,4513,6496,4692,4515,4723,5100,3356,6497,6291,3810,4080,5561,
-3570,4430,5980,6498,4355,5697,6499,4724,6108,6109,3764,4050,5038,5879,4093,3226,
-6292,5068,5217,4693,3342,5630,3504,4831,4377,4466,4309,5698,4431,5777,6293,5778,
-4272,3706,6110,5326,3752,4676,5327,4273,5403,4767,5631,6500,5699,5880,3475,5039,
-6294,5562,5125,4348,4301,4482,4068,5126,4593,5700,3380,3462,5981,5563,3824,5404,
-4970,5511,3825,4738,6295,6501,5452,4516,6111,5881,5564,6502,6296,5982,6503,4213,
-4163,3454,6504,6112,4009,4450,6113,4658,6297,6114,3035,6505,6115,3995,4904,4739,
-4563,4942,4110,5040,3661,3928,5362,3674,6506,5292,3612,4791,5565,4149,5983,5328,
-5259,5021,4725,4577,4564,4517,4364,6298,5405,4578,5260,4594,4156,4157,5453,3592,
-3491,6507,5127,5512,4709,4922,5984,5701,4726,4289,6508,4015,6116,5128,4628,3424,
-4241,5779,6299,4905,6509,6510,5454,5702,5780,6300,4365,4923,3971,6511,5161,3270,
-3158,5985,4100, 867,5129,5703,6117,5363,3695,3301,5513,4467,6118,6512,5455,4232,
-4242,4629,6513,3959,4478,6514,5514,5329,5986,4850,5162,5566,3846,4694,6119,5456,
-4869,5781,3779,6301,5704,5987,5515,4710,6302,5882,6120,4392,5364,5705,6515,6121,
-6516,6517,3736,5988,5457,5989,4695,2457,5883,4551,5782,6303,6304,6305,5130,4971,
-6122,5163,6123,4870,3263,5365,3150,4871,6518,6306,5783,5069,5706,3513,3498,4409,
-5330,5632,5366,5458,5459,3991,5990,4502,3324,5991,5784,3696,4518,5633,4119,6519,
-4630,5634,4417,5707,4832,5992,3418,6124,5993,5567,4768,5218,6520,4595,3458,5367,
-6125,5635,6126,4202,6521,4740,4924,6307,3981,4069,4385,6308,3883,2675,4051,3834,
-4302,4483,5568,5994,4972,4101,5368,6309,5164,5884,3922,6127,6522,6523,5261,5460,
-5187,4164,5219,3538,5516,4111,3524,5995,6310,6311,5369,3181,3386,2484,5188,3464,
-5569,3627,5708,6524,5406,5165,4677,4492,6312,4872,4851,5885,4468,5996,6313,5709,
-5710,6128,2470,5886,6314,5293,4882,5785,3325,5461,5101,6129,5711,5786,6525,4906,
-6526,6527,4418,5887,5712,4808,2907,3701,5713,5888,6528,3765,5636,5331,6529,6530,
-3593,5889,3637,4943,3692,5714,5787,4925,6315,6130,5462,4405,6131,6132,6316,5262,
-6531,6532,5715,3859,5716,5070,4696,5102,3929,5788,3987,4792,5997,6533,6534,3920,
-4809,5000,5998,6535,2974,5370,6317,5189,5263,5717,3826,6536,3953,5001,4883,3190,
-5463,5890,4973,5999,4741,6133,6134,3607,5570,6000,4711,3362,3630,4552,5041,6318,
-6001,2950,2953,5637,4646,5371,4944,6002,2044,4120,3429,6319,6537,5103,4833,6538,
-6539,4884,4647,3884,6003,6004,4758,3835,5220,5789,4565,5407,6540,6135,5294,4697,
-4852,6320,6321,3206,4907,6541,6322,4945,6542,6136,6543,6323,6005,4631,3519,6544,
-5891,6545,5464,3784,5221,6546,5571,4659,6547,6324,6137,5190,6548,3853,6549,4016,
-4834,3954,6138,5332,3827,4017,3210,3546,4469,5408,5718,3505,4648,5790,5131,5638,
-5791,5465,4727,4318,6325,6326,5792,4553,4010,4698,3439,4974,3638,4335,3085,6006,
-5104,5042,5166,5892,5572,6327,4356,4519,5222,5573,5333,5793,5043,6550,5639,5071,
-4503,6328,6139,6551,6140,3914,3901,5372,6007,5640,4728,4793,3976,3836,4885,6552,
-4127,6553,4451,4102,5002,6554,3686,5105,6555,5191,5072,5295,4611,5794,5296,6556,
-5893,5264,5894,4975,5466,5265,4699,4976,4370,4056,3492,5044,4886,6557,5795,4432,
-4769,4357,5467,3940,4660,4290,6141,4484,4770,4661,3992,6329,4025,4662,5022,4632,
-4835,4070,5297,4663,4596,5574,5132,5409,5895,6142,4504,5192,4664,5796,5896,3885,
-5575,5797,5023,4810,5798,3732,5223,4712,5298,4084,5334,5468,6143,4052,4053,4336,
-4977,4794,6558,5335,4908,5576,5224,4233,5024,4128,5469,5225,4873,6008,5045,4729,
-4742,4633,3675,4597,6559,5897,5133,5577,5003,5641,5719,6330,6560,3017,2382,3854,
-4406,4811,6331,4393,3964,4946,6561,2420,3722,6562,4926,4378,3247,1736,4442,6332,
-5134,6333,5226,3996,2918,5470,4319,4003,4598,4743,4744,4485,3785,3902,5167,5004,
-5373,4394,5898,6144,4874,1793,3997,6334,4085,4214,5106,5642,4909,5799,6009,4419,
-4189,3330,5899,4165,4420,5299,5720,5227,3347,6145,4081,6335,2876,3930,6146,3293,
-3786,3910,3998,5900,5300,5578,2840,6563,5901,5579,6147,3531,5374,6564,6565,5580,
-4759,5375,6566,6148,3559,5643,6336,6010,5517,6337,6338,5721,5902,3873,6011,6339,
-6567,5518,3868,3649,5722,6568,4771,4947,6569,6149,4812,6570,2853,5471,6340,6341,
-5644,4795,6342,6012,5723,6343,5724,6013,4349,6344,3160,6150,5193,4599,4514,4493,
-5168,4320,6345,4927,3666,4745,5169,5903,5005,4928,6346,5725,6014,4730,4203,5046,
-4948,3395,5170,6015,4150,6016,5726,5519,6347,5047,3550,6151,6348,4197,4310,5904,
-6571,5581,2965,6152,4978,3960,4291,5135,6572,5301,5727,4129,4026,5905,4853,5728,
-5472,6153,6349,4533,2700,4505,5336,4678,3583,5073,2994,4486,3043,4554,5520,6350,
-6017,5800,4487,6351,3931,4103,5376,6352,4011,4321,4311,4190,5136,6018,3988,3233,
-4350,5906,5645,4198,6573,5107,3432,4191,3435,5582,6574,4139,5410,6353,5411,3944,
-5583,5074,3198,6575,6354,4358,6576,5302,4600,5584,5194,5412,6577,6578,5585,5413,
-5303,4248,5414,3879,4433,6579,4479,5025,4854,5415,6355,4760,4772,3683,2978,4700,
-3797,4452,3965,3932,3721,4910,5801,6580,5195,3551,5907,3221,3471,3029,6019,3999,
-5908,5909,5266,5267,3444,3023,3828,3170,4796,5646,4979,4259,6356,5647,5337,3694,
-6357,5648,5338,4520,4322,5802,3031,3759,4071,6020,5586,4836,4386,5048,6581,3571,
-4679,4174,4949,6154,4813,3787,3402,3822,3958,3215,3552,5268,4387,3933,4950,4359,
-6021,5910,5075,3579,6358,4234,4566,5521,6359,3613,5049,6022,5911,3375,3702,3178,
-4911,5339,4521,6582,6583,4395,3087,3811,5377,6023,6360,6155,4027,5171,5649,4421,
-4249,2804,6584,2270,6585,4000,4235,3045,6156,5137,5729,4140,4312,3886,6361,4330,
-6157,4215,6158,3500,3676,4929,4331,3713,4930,5912,4265,3776,3368,5587,4470,4855,
-3038,4980,3631,6159,6160,4132,4680,6161,6362,3923,4379,5588,4255,6586,4121,6587,
-6363,4649,6364,3288,4773,4774,6162,6024,6365,3543,6588,4274,3107,3737,5050,5803,
-4797,4522,5589,5051,5730,3714,4887,5378,4001,4523,6163,5026,5522,4701,4175,2791,
-3760,6589,5473,4224,4133,3847,4814,4815,4775,3259,5416,6590,2738,6164,6025,5304,
-3733,5076,5650,4816,5590,6591,6165,6592,3934,5269,6593,3396,5340,6594,5804,3445,
-3602,4042,4488,5731,5732,3525,5591,4601,5196,6166,6026,5172,3642,4612,3202,4506,
-4798,6366,3818,5108,4303,5138,5139,4776,3332,4304,2915,3415,4434,5077,5109,4856,
-2879,5305,4817,6595,5913,3104,3144,3903,4634,5341,3133,5110,5651,5805,6167,4057,
-5592,2945,4371,5593,6596,3474,4182,6367,6597,6168,4507,4279,6598,2822,6599,4777,
-4713,5594,3829,6169,3887,5417,6170,3653,5474,6368,4216,2971,5228,3790,4579,6369,
-5733,6600,6601,4951,4746,4555,6602,5418,5475,6027,3400,4665,5806,6171,4799,6028,
-5052,6172,3343,4800,4747,5006,6370,4556,4217,5476,4396,5229,5379,5477,3839,5914,
-5652,5807,4714,3068,4635,5808,6173,5342,4192,5078,5419,5523,5734,6174,4557,6175,
-4602,6371,6176,6603,5809,6372,5735,4260,3869,5111,5230,6029,5112,6177,3126,4681,
-5524,5915,2706,3563,4748,3130,6178,4018,5525,6604,6605,5478,4012,4837,6606,4534,
-4193,5810,4857,3615,5479,6030,4082,3697,3539,4086,5270,3662,4508,4931,5916,4912,
-5811,5027,3888,6607,4397,3527,3302,3798,2775,2921,2637,3966,4122,4388,4028,4054,
-1633,4858,5079,3024,5007,3982,3412,5736,6608,3426,3236,5595,3030,6179,3427,3336,
-3279,3110,6373,3874,3039,5080,5917,5140,4489,3119,6374,5812,3405,4494,6031,4666,
-4141,6180,4166,6032,5813,4981,6609,5081,4422,4982,4112,3915,5653,3296,3983,6375,
-4266,4410,5654,6610,6181,3436,5082,6611,5380,6033,3819,5596,4535,5231,5306,5113,
-6612,4952,5918,4275,3113,6613,6376,6182,6183,5814,3073,4731,4838,5008,3831,6614,
-4888,3090,3848,4280,5526,5232,3014,5655,5009,5737,5420,5527,6615,5815,5343,5173,
-5381,4818,6616,3151,4953,6617,5738,2796,3204,4360,2989,4281,5739,5174,5421,5197,
-3132,5141,3849,5142,5528,5083,3799,3904,4839,5480,2880,4495,3448,6377,6184,5271,
-5919,3771,3193,6034,6035,5920,5010,6036,5597,6037,6378,6038,3106,5422,6618,5423,
-5424,4142,6619,4889,5084,4890,4313,5740,6620,3437,5175,5307,5816,4199,5198,5529,
-5817,5199,5656,4913,5028,5344,3850,6185,2955,5272,5011,5818,4567,4580,5029,5921,
-3616,5233,6621,6622,6186,4176,6039,6379,6380,3352,5200,5273,2908,5598,5234,3837,
-5308,6623,6624,5819,4496,4323,5309,5201,6625,6626,4983,3194,3838,4167,5530,5922,
-5274,6381,6382,3860,3861,5599,3333,4292,4509,6383,3553,5481,5820,5531,4778,6187,
-3955,3956,4324,4389,4218,3945,4325,3397,2681,5923,4779,5085,4019,5482,4891,5382,
-5383,6040,4682,3425,5275,4094,6627,5310,3015,5483,5657,4398,5924,3168,4819,6628,
-5925,6629,5532,4932,4613,6041,6630,4636,6384,4780,4204,5658,4423,5821,3989,4683,
-5822,6385,4954,6631,5345,6188,5425,5012,5384,3894,6386,4490,4104,6632,5741,5053,
-6633,5823,5926,5659,5660,5927,6634,5235,5742,5824,4840,4933,4820,6387,4859,5928,
-4955,6388,4143,3584,5825,5346,5013,6635,5661,6389,5014,5484,5743,4337,5176,5662,
-6390,2836,6391,3268,6392,6636,6042,5236,6637,4158,6638,5744,5663,4471,5347,3663,
-4123,5143,4293,3895,6639,6640,5311,5929,5826,3800,6189,6393,6190,5664,5348,3554,
-3594,4749,4603,6641,5385,4801,6043,5827,4183,6642,5312,5426,4761,6394,5665,6191,
-4715,2669,6643,6644,5533,3185,5427,5086,5930,5931,5386,6192,6044,6645,4781,4013,
-5745,4282,4435,5534,4390,4267,6045,5746,4984,6046,2743,6193,3501,4087,5485,5932,
-5428,4184,4095,5747,4061,5054,3058,3862,5933,5600,6646,5144,3618,6395,3131,5055,
-5313,6396,4650,4956,3855,6194,3896,5202,4985,4029,4225,6195,6647,5828,5486,5829,
-3589,3002,6648,6397,4782,5276,6649,6196,6650,4105,3803,4043,5237,5830,6398,4096,
-3643,6399,3528,6651,4453,3315,4637,6652,3984,6197,5535,3182,3339,6653,3096,2660,
-6400,6654,3449,5934,4250,4236,6047,6401,5831,6655,5487,3753,4062,5832,6198,6199,
-6656,3766,6657,3403,4667,6048,6658,4338,2897,5833,3880,2797,3780,4326,6659,5748,
-5015,6660,5387,4351,5601,4411,6661,3654,4424,5935,4339,4072,5277,4568,5536,6402,
-6662,5238,6663,5349,5203,6200,5204,6201,5145,4536,5016,5056,4762,5834,4399,4957,
-6202,6403,5666,5749,6664,4340,6665,5936,5177,5667,6666,6667,3459,4668,6404,6668,
-6669,4543,6203,6670,4276,6405,4480,5537,6671,4614,5205,5668,6672,3348,2193,4763,
-6406,6204,5937,5602,4177,5669,3419,6673,4020,6205,4443,4569,5388,3715,3639,6407,
-6049,4058,6206,6674,5938,4544,6050,4185,4294,4841,4651,4615,5488,6207,6408,6051,
-5178,3241,3509,5835,6208,4958,5836,4341,5489,5278,6209,2823,5538,5350,5206,5429,
-6675,4638,4875,4073,3516,4684,4914,4860,5939,5603,5389,6052,5057,3237,5490,3791,
-6676,6409,6677,4821,4915,4106,5351,5058,4243,5539,4244,5604,4842,4916,5239,3028,
-3716,5837,5114,5605,5390,5940,5430,6210,4332,6678,5540,4732,3667,3840,6053,4305,
-3408,5670,5541,6410,2744,5240,5750,6679,3234,5606,6680,5607,5671,3608,4283,4159,
-4400,5352,4783,6681,6411,6682,4491,4802,6211,6412,5941,6413,6414,5542,5751,6683,
-4669,3734,5942,6684,6415,5943,5059,3328,4670,4144,4268,6685,6686,6687,6688,4372,
-3603,6689,5944,5491,4373,3440,6416,5543,4784,4822,5608,3792,4616,5838,5672,3514,
-5391,6417,4892,6690,4639,6691,6054,5673,5839,6055,6692,6056,5392,6212,4038,5544,
-5674,4497,6057,6693,5840,4284,5675,4021,4545,5609,6418,4454,6419,6213,4113,4472,
-5314,3738,5087,5279,4074,5610,4959,4063,3179,4750,6058,6420,6214,3476,4498,4716,
-5431,4960,4685,6215,5241,6694,6421,6216,6695,5841,5945,6422,3748,5946,5179,3905,
-5752,5545,5947,4374,6217,4455,6423,4412,6218,4803,5353,6696,3832,5280,6219,4327,
-4702,6220,6221,6059,4652,5432,6424,3749,4751,6425,5753,4986,5393,4917,5948,5030,
-5754,4861,4733,6426,4703,6697,6222,4671,5949,4546,4961,5180,6223,5031,3316,5281,
-6698,4862,4295,4934,5207,3644,6427,5842,5950,6428,6429,4570,5843,5282,6430,6224,
-5088,3239,6060,6699,5844,5755,6061,6431,2701,5546,6432,5115,5676,4039,3993,3327,
-4752,4425,5315,6433,3941,6434,5677,4617,4604,3074,4581,6225,5433,6435,6226,6062,
-4823,5756,5116,6227,3717,5678,4717,5845,6436,5679,5846,6063,5847,6064,3977,3354,
-6437,3863,5117,6228,5547,5394,4499,4524,6229,4605,6230,4306,4500,6700,5951,6065,
-3693,5952,5089,4366,4918,6701,6231,5548,6232,6702,6438,4704,5434,6703,6704,5953,
-4168,6705,5680,3420,6706,5242,4407,6066,3812,5757,5090,5954,4672,4525,3481,5681,
-4618,5395,5354,5316,5955,6439,4962,6707,4526,6440,3465,4673,6067,6441,5682,6708,
-5435,5492,5758,5683,4619,4571,4674,4804,4893,4686,5493,4753,6233,6068,4269,6442,
-6234,5032,4705,5146,5243,5208,5848,6235,6443,4963,5033,4640,4226,6236,5849,3387,
-6444,6445,4436,4437,5850,4843,5494,4785,4894,6709,4361,6710,5091,5956,3331,6237,
-4987,5549,6069,6711,4342,3517,4473,5317,6070,6712,6071,4706,6446,5017,5355,6713,
-6714,4988,5436,6447,4734,5759,6715,4735,4547,4456,4754,6448,5851,6449,6450,3547,
-5852,5318,6451,6452,5092,4205,6716,6238,4620,4219,5611,6239,6072,4481,5760,5957,
-5958,4059,6240,6453,4227,4537,6241,5761,4030,4186,5244,5209,3761,4457,4876,3337,
-5495,5181,6242,5959,5319,5612,5684,5853,3493,5854,6073,4169,5613,5147,4895,6074,
-5210,6717,5182,6718,3830,6243,2798,3841,6075,6244,5855,5614,3604,4606,5496,5685,
-5118,5356,6719,6454,5960,5357,5961,6720,4145,3935,4621,5119,5962,4261,6721,6455,
-4786,5963,4375,4582,6245,6246,6247,6076,5437,4877,5856,3376,4380,6248,4160,6722,
-5148,6456,5211,6457,6723,4718,6458,6724,6249,5358,4044,3297,6459,6250,5857,5615,
-5497,5245,6460,5498,6725,6251,6252,5550,3793,5499,2959,5396,6461,6462,4572,5093,
-5500,5964,3806,4146,6463,4426,5762,5858,6077,6253,4755,3967,4220,5965,6254,4989,
-5501,6464,4352,6726,6078,4764,2290,5246,3906,5438,5283,3767,4964,2861,5763,5094,
-6255,6256,4622,5616,5859,5860,4707,6727,4285,4708,4824,5617,6257,5551,4787,5212,
-4965,4935,4687,6465,6728,6466,5686,6079,3494,4413,2995,5247,5966,5618,6729,5967,
-5764,5765,5687,5502,6730,6731,6080,5397,6467,4990,6258,6732,4538,5060,5619,6733,
-4719,5688,5439,5018,5149,5284,5503,6734,6081,4607,6259,5120,3645,5861,4583,6260,
-4584,4675,5620,4098,5440,6261,4863,2379,3306,4585,5552,5689,4586,5285,6735,4864,
-6736,5286,6082,6737,4623,3010,4788,4381,4558,5621,4587,4896,3698,3161,5248,4353,
-4045,6262,3754,5183,4588,6738,6263,6739,6740,5622,3936,6741,6468,6742,6264,5095,
-6469,4991,5968,6743,4992,6744,6083,4897,6745,4256,5766,4307,3108,3968,4444,5287,
-3889,4343,6084,4510,6085,4559,6086,4898,5969,6746,5623,5061,4919,5249,5250,5504,
-5441,6265,5320,4878,3242,5862,5251,3428,6087,6747,4237,5624,5442,6266,5553,4539,
-6748,2585,3533,5398,4262,6088,5150,4736,4438,6089,6267,5505,4966,6749,6268,6750,
-6269,5288,5554,3650,6090,6091,4624,6092,5690,6751,5863,4270,5691,4277,5555,5864,
-6752,5692,4720,4865,6470,5151,4688,4825,6753,3094,6754,6471,3235,4653,6755,5213,
-5399,6756,3201,4589,5865,4967,6472,5866,6473,5019,3016,6757,5321,4756,3957,4573,
-6093,4993,5767,4721,6474,6758,5625,6759,4458,6475,6270,6760,5556,4994,5214,5252,
-6271,3875,5768,6094,5034,5506,4376,5769,6761,2120,6476,5253,5770,6762,5771,5970,
-3990,5971,5557,5558,5772,6477,6095,2787,4641,5972,5121,6096,6097,6272,6763,3703,
-5867,5507,6273,4206,6274,4789,6098,6764,3619,3646,3833,3804,2394,3788,4936,3978,
-4866,4899,6099,6100,5559,6478,6765,3599,5868,6101,5869,5870,6275,6766,4527,6767)
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/gb2312prober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/gb2312prober.py
deleted file mode 100644
index 0325a2d..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/gb2312prober.py
+++ /dev/null
@@ -1,41 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .mbcharsetprober import MultiByteCharSetProber
-from .codingstatemachine import CodingStateMachine
-from .chardistribution import GB2312DistributionAnalysis
-from .mbcssm import GB2312SMModel
-
-class GB2312Prober(MultiByteCharSetProber):
- def __init__(self):
- MultiByteCharSetProber.__init__(self)
- self._mCodingSM = CodingStateMachine(GB2312SMModel)
- self._mDistributionAnalyzer = GB2312DistributionAnalysis()
- self.reset()
-
- def get_charset_name(self):
- return "GB2312"
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/hebrewprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/hebrewprober.py
deleted file mode 100644
index ba225c5..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/hebrewprober.py
+++ /dev/null
@@ -1,283 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Universal charset detector code.
-#
-# The Initial Developer of the Original Code is
-# Shy Shalom
-# Portions created by the Initial Developer are Copyright (C) 2005
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .charsetprober import CharSetProber
-from .constants import eNotMe, eDetecting
-from .compat import wrap_ord
-
-# This prober doesn't actually recognize a language or a charset.
-# It is a helper prober for the use of the Hebrew model probers
-
-### General ideas of the Hebrew charset recognition ###
-#
-# Four main charsets exist in Hebrew:
-# "ISO-8859-8" - Visual Hebrew
-# "windows-1255" - Logical Hebrew
-# "ISO-8859-8-I" - Logical Hebrew
-# "x-mac-hebrew" - ?? Logical Hebrew ??
-#
-# Both "ISO" charsets use a completely identical set of code points, whereas
-# "windows-1255" and "x-mac-hebrew" are two different proper supersets of
-# these code points. windows-1255 defines additional characters in the range
-# 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific
-# diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6.
-# x-mac-hebrew defines similar additional code points but with a different
-# mapping.
-#
-# As far as an average Hebrew text with no diacritics is concerned, all four
-# charsets are identical with respect to code points. Meaning that for the
-# main Hebrew alphabet, all four map the same values to all 27 Hebrew letters
-# (including final letters).
-#
-# The dominant difference between these charsets is their directionality.
-# "Visual" directionality means that the text is ordered as if the renderer is
-# not aware of a BIDI rendering algorithm. The renderer sees the text and
-# draws it from left to right. The text itself when ordered naturally is read
-# backwards. A buffer of Visual Hebrew generally looks like so:
-# "[last word of first line spelled backwards] [whole line ordered backwards
-# and spelled backwards] [first word of first line spelled backwards]
-# [end of line] [last word of second line] ... etc' "
-# adding punctuation marks, numbers and English text to visual text is
-# naturally also "visual" and from left to right.
-#
-# "Logical" directionality means the text is ordered "naturally" according to
-# the order it is read. It is the responsibility of the renderer to display
-# the text from right to left. A BIDI algorithm is used to place general
-# punctuation marks, numbers and English text in the text.
-#
-# Texts in x-mac-hebrew are almost impossible to find on the Internet. From
-# what little evidence I could find, it seems that its general directionality
-# is Logical.
-#
-# To sum up all of the above, the Hebrew probing mechanism knows about two
-# charsets:
-# Visual Hebrew - "ISO-8859-8" - backwards text - Words and sentences are
-# backwards while line order is natural. For charset recognition purposes
-# the line order is unimportant (In fact, for this implementation, even
-# word order is unimportant).
-# Logical Hebrew - "windows-1255" - normal, naturally ordered text.
-#
-# "ISO-8859-8-I" is a subset of windows-1255 and doesn't need to be
-# specifically identified.
-# "x-mac-hebrew" is also identified as windows-1255. A text in x-mac-hebrew
-# that contain special punctuation marks or diacritics is displayed with
-# some unconverted characters showing as question marks. This problem might
-# be corrected using another model prober for x-mac-hebrew. Due to the fact
-# that x-mac-hebrew texts are so rare, writing another model prober isn't
-# worth the effort and performance hit.
-#
-#### The Prober ####
-#
-# The prober is divided between two SBCharSetProbers and a HebrewProber,
-# all of which are managed, created, fed data, inquired and deleted by the
-# SBCSGroupProber. The two SBCharSetProbers identify that the text is in
-# fact some kind of Hebrew, Logical or Visual. The final decision about which
-# one is it is made by the HebrewProber by combining final-letter scores
-# with the scores of the two SBCharSetProbers to produce a final answer.
-#
-# The SBCSGroupProber is responsible for stripping the original text of HTML
-# tags, English characters, numbers, low-ASCII punctuation characters, spaces
-# and new lines. It reduces any sequence of such characters to a single space.
-# The buffer fed to each prober in the SBCS group prober is pure text in
-# high-ASCII.
-# The two SBCharSetProbers (model probers) share the same language model:
-# Win1255Model.
-# The first SBCharSetProber uses the model normally as any other
-# SBCharSetProber does, to recognize windows-1255, upon which this model was
-# built. The second SBCharSetProber is told to make the pair-of-letter
-# lookup in the language model backwards. This in practice exactly simulates
-# a visual Hebrew model using the windows-1255 logical Hebrew model.
-#
-# The HebrewProber is not using any language model. All it does is look for
-# final-letter evidence suggesting the text is either logical Hebrew or visual
-# Hebrew. Disjointed from the model probers, the results of the HebrewProber
-# alone are meaningless. HebrewProber always returns 0.00 as confidence
-# since it never identifies a charset by itself. Instead, the pointer to the
-# HebrewProber is passed to the model probers as a helper "Name Prober".
-# When the Group prober receives a positive identification from any prober,
-# it asks for the name of the charset identified. If the prober queried is a
-# Hebrew model prober, the model prober forwards the call to the
-# HebrewProber to make the final decision. In the HebrewProber, the
-# decision is made according to the final-letters scores maintained and Both
-# model probers scores. The answer is returned in the form of the name of the
-# charset identified, either "windows-1255" or "ISO-8859-8".
-
-# windows-1255 / ISO-8859-8 code points of interest
-FINAL_KAF = 0xea
-NORMAL_KAF = 0xeb
-FINAL_MEM = 0xed
-NORMAL_MEM = 0xee
-FINAL_NUN = 0xef
-NORMAL_NUN = 0xf0
-FINAL_PE = 0xf3
-NORMAL_PE = 0xf4
-FINAL_TSADI = 0xf5
-NORMAL_TSADI = 0xf6
-
-# Minimum Visual vs Logical final letter score difference.
-# If the difference is below this, don't rely solely on the final letter score
-# distance.
-MIN_FINAL_CHAR_DISTANCE = 5
-
-# Minimum Visual vs Logical model score difference.
-# If the difference is below this, don't rely at all on the model score
-# distance.
-MIN_MODEL_DISTANCE = 0.01
-
-VISUAL_HEBREW_NAME = "ISO-8859-8"
-LOGICAL_HEBREW_NAME = "windows-1255"
-
-
-class HebrewProber(CharSetProber):
- def __init__(self):
- CharSetProber.__init__(self)
- self._mLogicalProber = None
- self._mVisualProber = None
- self.reset()
-
- def reset(self):
- self._mFinalCharLogicalScore = 0
- self._mFinalCharVisualScore = 0
- # The two last characters seen in the previous buffer,
- # mPrev and mBeforePrev are initialized to space in order to simulate
- # a word delimiter at the beginning of the data
- self._mPrev = ' '
- self._mBeforePrev = ' '
- # These probers are owned by the group prober.
-
- def set_model_probers(self, logicalProber, visualProber):
- self._mLogicalProber = logicalProber
- self._mVisualProber = visualProber
-
- def is_final(self, c):
- return wrap_ord(c) in [FINAL_KAF, FINAL_MEM, FINAL_NUN, FINAL_PE,
- FINAL_TSADI]
-
- def is_non_final(self, c):
- # The normal Tsadi is not a good Non-Final letter due to words like
- # 'lechotet' (to chat) containing an apostrophe after the tsadi. This
- # apostrophe is converted to a space in FilterWithoutEnglishLetters
- # causing the Non-Final tsadi to appear at an end of a word even
- # though this is not the case in the original text.
- # The letters Pe and Kaf rarely display a related behavior of not being
- # a good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak'
- # for example legally end with a Non-Final Pe or Kaf. However, the
- # benefit of these letters as Non-Final letters outweighs the damage
- # since these words are quite rare.
- return wrap_ord(c) in [NORMAL_KAF, NORMAL_MEM, NORMAL_NUN, NORMAL_PE]
-
- def feed(self, aBuf):
- # Final letter analysis for logical-visual decision.
- # Look for evidence that the received buffer is either logical Hebrew
- # or visual Hebrew.
- # The following cases are checked:
- # 1) A word longer than 1 letter, ending with a final letter. This is
- # an indication that the text is laid out "naturally" since the
- # final letter really appears at the end. +1 for logical score.
- # 2) A word longer than 1 letter, ending with a Non-Final letter. In
- # normal Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi,
- # should not end with the Non-Final form of that letter. Exceptions
- # to this rule are mentioned above in isNonFinal(). This is an
- # indication that the text is laid out backwards. +1 for visual
- # score
- # 3) A word longer than 1 letter, starting with a final letter. Final
- # letters should not appear at the beginning of a word. This is an
- # indication that the text is laid out backwards. +1 for visual
- # score.
- #
- # The visual score and logical score are accumulated throughout the
- # text and are finally checked against each other in GetCharSetName().
- # No checking for final letters in the middle of words is done since
- # that case is not an indication for either Logical or Visual text.
- #
- # We automatically filter out all 7-bit characters (replace them with
- # spaces) so the word boundary detection works properly. [MAP]
-
- if self.get_state() == eNotMe:
- # Both model probers say it's not them. No reason to continue.
- return eNotMe
-
- aBuf = self.filter_high_bit_only(aBuf)
-
- for cur in aBuf:
- if cur == ' ':
- # We stand on a space - a word just ended
- if self._mBeforePrev != ' ':
- # next-to-last char was not a space so self._mPrev is not a
- # 1 letter word
- if self.is_final(self._mPrev):
- # case (1) [-2:not space][-1:final letter][cur:space]
- self._mFinalCharLogicalScore += 1
- elif self.is_non_final(self._mPrev):
- # case (2) [-2:not space][-1:Non-Final letter][
- # cur:space]
- self._mFinalCharVisualScore += 1
- else:
- # Not standing on a space
- if ((self._mBeforePrev == ' ') and
- (self.is_final(self._mPrev)) and (cur != ' ')):
- # case (3) [-2:space][-1:final letter][cur:not space]
- self._mFinalCharVisualScore += 1
- self._mBeforePrev = self._mPrev
- self._mPrev = cur
-
- # Forever detecting, till the end or until both model probers return
- # eNotMe (handled above)
- return eDetecting
-
- def get_charset_name(self):
- # Make the decision: is it Logical or Visual?
- # If the final letter score distance is dominant enough, rely on it.
- finalsub = self._mFinalCharLogicalScore - self._mFinalCharVisualScore
- if finalsub >= MIN_FINAL_CHAR_DISTANCE:
- return LOGICAL_HEBREW_NAME
- if finalsub <= -MIN_FINAL_CHAR_DISTANCE:
- return VISUAL_HEBREW_NAME
-
- # It's not dominant enough, try to rely on the model scores instead.
- modelsub = (self._mLogicalProber.get_confidence()
- - self._mVisualProber.get_confidence())
- if modelsub > MIN_MODEL_DISTANCE:
- return LOGICAL_HEBREW_NAME
- if modelsub < -MIN_MODEL_DISTANCE:
- return VISUAL_HEBREW_NAME
-
- # Still no good, back to final letter distance, maybe it'll save the
- # day.
- if finalsub < 0.0:
- return VISUAL_HEBREW_NAME
-
- # (finalsub > 0 - Logical) or (don't know what to do) default to
- # Logical.
- return LOGICAL_HEBREW_NAME
-
- def get_state(self):
- # Remain active as long as any of the model probers are active.
- if (self._mLogicalProber.get_state() == eNotMe) and \
- (self._mVisualProber.get_state() == eNotMe):
- return eNotMe
- return eDetecting
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/jisfreq.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/jisfreq.py
deleted file mode 100644
index 064345b..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/jisfreq.py
+++ /dev/null
@@ -1,569 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# Sampling from about 20M text materials include literature and computer technology
-#
-# Japanese frequency table, applied to both S-JIS and EUC-JP
-# They are sorted in order.
-
-# 128 --> 0.77094
-# 256 --> 0.85710
-# 512 --> 0.92635
-# 1024 --> 0.97130
-# 2048 --> 0.99431
-#
-# Ideal Distribution Ratio = 0.92635 / (1-0.92635) = 12.58
-# Random Distribution Ration = 512 / (2965+62+83+86-512) = 0.191
-#
-# Typical Distribution Ratio, 25% of IDR
-
-JIS_TYPICAL_DISTRIBUTION_RATIO = 3.0
-
-# Char to FreqOrder table ,
-JIS_TABLE_SIZE = 4368
-
-JISCharToFreqOrder = (
- 40, 1, 6, 182, 152, 180, 295,2127, 285, 381,3295,4304,3068,4606,3165,3510, # 16
-3511,1822,2785,4607,1193,2226,5070,4608, 171,2996,1247, 18, 179,5071, 856,1661, # 32
-1262,5072, 619, 127,3431,3512,3230,1899,1700, 232, 228,1294,1298, 284, 283,2041, # 48
-2042,1061,1062, 48, 49, 44, 45, 433, 434,1040,1041, 996, 787,2997,1255,4305, # 64
-2108,4609,1684,1648,5073,5074,5075,5076,5077,5078,3687,5079,4610,5080,3927,3928, # 80
-5081,3296,3432, 290,2285,1471,2187,5082,2580,2825,1303,2140,1739,1445,2691,3375, # 96
-1691,3297,4306,4307,4611, 452,3376,1182,2713,3688,3069,4308,5083,5084,5085,5086, # 112
-5087,5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102, # 128
-5103,5104,5105,5106,5107,5108,5109,5110,5111,5112,4097,5113,5114,5115,5116,5117, # 144
-5118,5119,5120,5121,5122,5123,5124,5125,5126,5127,5128,5129,5130,5131,5132,5133, # 160
-5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148,5149, # 176
-5150,5151,5152,4612,5153,5154,5155,5156,5157,5158,5159,5160,5161,5162,5163,5164, # 192
-5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,1472, 598, 618, 820,1205, # 208
-1309,1412,1858,1307,1692,5176,5177,5178,5179,5180,5181,5182,1142,1452,1234,1172, # 224
-1875,2043,2149,1793,1382,2973, 925,2404,1067,1241, 960,1377,2935,1491, 919,1217, # 240
-1865,2030,1406,1499,2749,4098,5183,5184,5185,5186,5187,5188,2561,4099,3117,1804, # 256
-2049,3689,4309,3513,1663,5189,3166,3118,3298,1587,1561,3433,5190,3119,1625,2998, # 272
-3299,4613,1766,3690,2786,4614,5191,5192,5193,5194,2161, 26,3377, 2,3929, 20, # 288
-3691, 47,4100, 50, 17, 16, 35, 268, 27, 243, 42, 155, 24, 154, 29, 184, # 304
- 4, 91, 14, 92, 53, 396, 33, 289, 9, 37, 64, 620, 21, 39, 321, 5, # 320
- 12, 11, 52, 13, 3, 208, 138, 0, 7, 60, 526, 141, 151,1069, 181, 275, # 336
-1591, 83, 132,1475, 126, 331, 829, 15, 69, 160, 59, 22, 157, 55,1079, 312, # 352
- 109, 38, 23, 25, 10, 19, 79,5195, 61, 382,1124, 8, 30,5196,5197,5198, # 368
-5199,5200,5201,5202,5203,5204,5205,5206, 89, 62, 74, 34,2416, 112, 139, 196, # 384
- 271, 149, 84, 607, 131, 765, 46, 88, 153, 683, 76, 874, 101, 258, 57, 80, # 400
- 32, 364, 121,1508, 169,1547, 68, 235, 145,2999, 41, 360,3027, 70, 63, 31, # 416
- 43, 259, 262,1383, 99, 533, 194, 66, 93, 846, 217, 192, 56, 106, 58, 565, # 432
- 280, 272, 311, 256, 146, 82, 308, 71, 100, 128, 214, 655, 110, 261, 104,1140, # 448
- 54, 51, 36, 87, 67,3070, 185,2618,2936,2020, 28,1066,2390,2059,5207,5208, # 464
-5209,5210,5211,5212,5213,5214,5215,5216,4615,5217,5218,5219,5220,5221,5222,5223, # 480
-5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234,5235,5236,3514,5237,5238, # 496
-5239,5240,5241,5242,5243,5244,2297,2031,4616,4310,3692,5245,3071,5246,3598,5247, # 512
-4617,3231,3515,5248,4101,4311,4618,3808,4312,4102,5249,4103,4104,3599,5250,5251, # 528
-5252,5253,5254,5255,5256,5257,5258,5259,5260,5261,5262,5263,5264,5265,5266,5267, # 544
-5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278,5279,5280,5281,5282,5283, # 560
-5284,5285,5286,5287,5288,5289,5290,5291,5292,5293,5294,5295,5296,5297,5298,5299, # 576
-5300,5301,5302,5303,5304,5305,5306,5307,5308,5309,5310,5311,5312,5313,5314,5315, # 592
-5316,5317,5318,5319,5320,5321,5322,5323,5324,5325,5326,5327,5328,5329,5330,5331, # 608
-5332,5333,5334,5335,5336,5337,5338,5339,5340,5341,5342,5343,5344,5345,5346,5347, # 624
-5348,5349,5350,5351,5352,5353,5354,5355,5356,5357,5358,5359,5360,5361,5362,5363, # 640
-5364,5365,5366,5367,5368,5369,5370,5371,5372,5373,5374,5375,5376,5377,5378,5379, # 656
-5380,5381, 363, 642,2787,2878,2788,2789,2316,3232,2317,3434,2011, 165,1942,3930, # 672
-3931,3932,3933,5382,4619,5383,4620,5384,5385,5386,5387,5388,5389,5390,5391,5392, # 688
-5393,5394,5395,5396,5397,5398,5399,5400,5401,5402,5403,5404,5405,5406,5407,5408, # 704
-5409,5410,5411,5412,5413,5414,5415,5416,5417,5418,5419,5420,5421,5422,5423,5424, # 720
-5425,5426,5427,5428,5429,5430,5431,5432,5433,5434,5435,5436,5437,5438,5439,5440, # 736
-5441,5442,5443,5444,5445,5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456, # 752
-5457,5458,5459,5460,5461,5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472, # 768
-5473,5474,5475,5476,5477,5478,5479,5480,5481,5482,5483,5484,5485,5486,5487,5488, # 784
-5489,5490,5491,5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504, # 800
-5505,5506,5507,5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520, # 816
-5521,5522,5523,5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536, # 832
-5537,5538,5539,5540,5541,5542,5543,5544,5545,5546,5547,5548,5549,5550,5551,5552, # 848
-5553,5554,5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568, # 864
-5569,5570,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584, # 880
-5585,5586,5587,5588,5589,5590,5591,5592,5593,5594,5595,5596,5597,5598,5599,5600, # 896
-5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,5615,5616, # 912
-5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631,5632, # 928
-5633,5634,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646,5647,5648, # 944
-5649,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660,5661,5662,5663,5664, # 960
-5665,5666,5667,5668,5669,5670,5671,5672,5673,5674,5675,5676,5677,5678,5679,5680, # 976
-5681,5682,5683,5684,5685,5686,5687,5688,5689,5690,5691,5692,5693,5694,5695,5696, # 992
-5697,5698,5699,5700,5701,5702,5703,5704,5705,5706,5707,5708,5709,5710,5711,5712, # 1008
-5713,5714,5715,5716,5717,5718,5719,5720,5721,5722,5723,5724,5725,5726,5727,5728, # 1024
-5729,5730,5731,5732,5733,5734,5735,5736,5737,5738,5739,5740,5741,5742,5743,5744, # 1040
-5745,5746,5747,5748,5749,5750,5751,5752,5753,5754,5755,5756,5757,5758,5759,5760, # 1056
-5761,5762,5763,5764,5765,5766,5767,5768,5769,5770,5771,5772,5773,5774,5775,5776, # 1072
-5777,5778,5779,5780,5781,5782,5783,5784,5785,5786,5787,5788,5789,5790,5791,5792, # 1088
-5793,5794,5795,5796,5797,5798,5799,5800,5801,5802,5803,5804,5805,5806,5807,5808, # 1104
-5809,5810,5811,5812,5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824, # 1120
-5825,5826,5827,5828,5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840, # 1136
-5841,5842,5843,5844,5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856, # 1152
-5857,5858,5859,5860,5861,5862,5863,5864,5865,5866,5867,5868,5869,5870,5871,5872, # 1168
-5873,5874,5875,5876,5877,5878,5879,5880,5881,5882,5883,5884,5885,5886,5887,5888, # 1184
-5889,5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904, # 1200
-5905,5906,5907,5908,5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920, # 1216
-5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936, # 1232
-5937,5938,5939,5940,5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,5952, # 1248
-5953,5954,5955,5956,5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968, # 1264
-5969,5970,5971,5972,5973,5974,5975,5976,5977,5978,5979,5980,5981,5982,5983,5984, # 1280
-5985,5986,5987,5988,5989,5990,5991,5992,5993,5994,5995,5996,5997,5998,5999,6000, # 1296
-6001,6002,6003,6004,6005,6006,6007,6008,6009,6010,6011,6012,6013,6014,6015,6016, # 1312
-6017,6018,6019,6020,6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032, # 1328
-6033,6034,6035,6036,6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048, # 1344
-6049,6050,6051,6052,6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064, # 1360
-6065,6066,6067,6068,6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080, # 1376
-6081,6082,6083,6084,6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096, # 1392
-6097,6098,6099,6100,6101,6102,6103,6104,6105,6106,6107,6108,6109,6110,6111,6112, # 1408
-6113,6114,2044,2060,4621, 997,1235, 473,1186,4622, 920,3378,6115,6116, 379,1108, # 1424
-4313,2657,2735,3934,6117,3809, 636,3233, 573,1026,3693,3435,2974,3300,2298,4105, # 1440
- 854,2937,2463, 393,2581,2417, 539, 752,1280,2750,2480, 140,1161, 440, 708,1569, # 1456
- 665,2497,1746,1291,1523,3000, 164,1603, 847,1331, 537,1997, 486, 508,1693,2418, # 1472
-1970,2227, 878,1220, 299,1030, 969, 652,2751, 624,1137,3301,2619, 65,3302,2045, # 1488
-1761,1859,3120,1930,3694,3516, 663,1767, 852, 835,3695, 269, 767,2826,2339,1305, # 1504
- 896,1150, 770,1616,6118, 506,1502,2075,1012,2519, 775,2520,2975,2340,2938,4314, # 1520
-3028,2086,1224,1943,2286,6119,3072,4315,2240,1273,1987,3935,1557, 175, 597, 985, # 1536
-3517,2419,2521,1416,3029, 585, 938,1931,1007,1052,1932,1685,6120,3379,4316,4623, # 1552
- 804, 599,3121,1333,2128,2539,1159,1554,2032,3810, 687,2033,2904, 952, 675,1467, # 1568
-3436,6121,2241,1096,1786,2440,1543,1924, 980,1813,2228, 781,2692,1879, 728,1918, # 1584
-3696,4624, 548,1950,4625,1809,1088,1356,3303,2522,1944, 502, 972, 373, 513,2827, # 1600
- 586,2377,2391,1003,1976,1631,6122,2464,1084, 648,1776,4626,2141, 324, 962,2012, # 1616
-2177,2076,1384, 742,2178,1448,1173,1810, 222, 102, 301, 445, 125,2420, 662,2498, # 1632
- 277, 200,1476,1165,1068, 224,2562,1378,1446, 450,1880, 659, 791, 582,4627,2939, # 1648
-3936,1516,1274, 555,2099,3697,1020,1389,1526,3380,1762,1723,1787,2229, 412,2114, # 1664
-1900,2392,3518, 512,2597, 427,1925,2341,3122,1653,1686,2465,2499, 697, 330, 273, # 1680
- 380,2162, 951, 832, 780, 991,1301,3073, 965,2270,3519, 668,2523,2636,1286, 535, # 1696
-1407, 518, 671, 957,2658,2378, 267, 611,2197,3030,6123, 248,2299, 967,1799,2356, # 1712
- 850,1418,3437,1876,1256,1480,2828,1718,6124,6125,1755,1664,2405,6126,4628,2879, # 1728
-2829, 499,2179, 676,4629, 557,2329,2214,2090, 325,3234, 464, 811,3001, 992,2342, # 1744
-2481,1232,1469, 303,2242, 466,1070,2163, 603,1777,2091,4630,2752,4631,2714, 322, # 1760
-2659,1964,1768, 481,2188,1463,2330,2857,3600,2092,3031,2421,4632,2318,2070,1849, # 1776
-2598,4633,1302,2254,1668,1701,2422,3811,2905,3032,3123,2046,4106,1763,1694,4634, # 1792
-1604, 943,1724,1454, 917, 868,2215,1169,2940, 552,1145,1800,1228,1823,1955, 316, # 1808
-1080,2510, 361,1807,2830,4107,2660,3381,1346,1423,1134,4108,6127, 541,1263,1229, # 1824
-1148,2540, 545, 465,1833,2880,3438,1901,3074,2482, 816,3937, 713,1788,2500, 122, # 1840
-1575, 195,1451,2501,1111,6128, 859, 374,1225,2243,2483,4317, 390,1033,3439,3075, # 1856
-2524,1687, 266, 793,1440,2599, 946, 779, 802, 507, 897,1081, 528,2189,1292, 711, # 1872
-1866,1725,1167,1640, 753, 398,2661,1053, 246, 348,4318, 137,1024,3440,1600,2077, # 1888
-2129, 825,4319, 698, 238, 521, 187,2300,1157,2423,1641,1605,1464,1610,1097,2541, # 1904
-1260,1436, 759,2255,1814,2150, 705,3235, 409,2563,3304, 561,3033,2005,2564, 726, # 1920
-1956,2343,3698,4109, 949,3812,3813,3520,1669, 653,1379,2525, 881,2198, 632,2256, # 1936
-1027, 778,1074, 733,1957, 514,1481,2466, 554,2180, 702,3938,1606,1017,1398,6129, # 1952
-1380,3521, 921, 993,1313, 594, 449,1489,1617,1166, 768,1426,1360, 495,1794,3601, # 1968
-1177,3602,1170,4320,2344, 476, 425,3167,4635,3168,1424, 401,2662,1171,3382,1998, # 1984
-1089,4110, 477,3169, 474,6130,1909, 596,2831,1842, 494, 693,1051,1028,1207,3076, # 2000
- 606,2115, 727,2790,1473,1115, 743,3522, 630, 805,1532,4321,2021, 366,1057, 838, # 2016
- 684,1114,2142,4322,2050,1492,1892,1808,2271,3814,2424,1971,1447,1373,3305,1090, # 2032
-1536,3939,3523,3306,1455,2199, 336, 369,2331,1035, 584,2393, 902, 718,2600,6131, # 2048
-2753, 463,2151,1149,1611,2467, 715,1308,3124,1268, 343,1413,3236,1517,1347,2663, # 2064
-2093,3940,2022,1131,1553,2100,2941,1427,3441,2942,1323,2484,6132,1980, 872,2368, # 2080
-2441,2943, 320,2369,2116,1082, 679,1933,3941,2791,3815, 625,1143,2023, 422,2200, # 2096
-3816,6133, 730,1695, 356,2257,1626,2301,2858,2637,1627,1778, 937, 883,2906,2693, # 2112
-3002,1769,1086, 400,1063,1325,3307,2792,4111,3077, 456,2345,1046, 747,6134,1524, # 2128
- 884,1094,3383,1474,2164,1059, 974,1688,2181,2258,1047, 345,1665,1187, 358, 875, # 2144
-3170, 305, 660,3524,2190,1334,1135,3171,1540,1649,2542,1527, 927, 968,2793, 885, # 2160
-1972,1850, 482, 500,2638,1218,1109,1085,2543,1654,2034, 876, 78,2287,1482,1277, # 2176
- 861,1675,1083,1779, 724,2754, 454, 397,1132,1612,2332, 893, 672,1237, 257,2259, # 2192
-2370, 135,3384, 337,2244, 547, 352, 340, 709,2485,1400, 788,1138,2511, 540, 772, # 2208
-1682,2260,2272,2544,2013,1843,1902,4636,1999,1562,2288,4637,2201,1403,1533, 407, # 2224
- 576,3308,1254,2071, 978,3385, 170, 136,1201,3125,2664,3172,2394, 213, 912, 873, # 2240
-3603,1713,2202, 699,3604,3699, 813,3442, 493, 531,1054, 468,2907,1483, 304, 281, # 2256
-4112,1726,1252,2094, 339,2319,2130,2639, 756,1563,2944, 748, 571,2976,1588,2425, # 2272
-2715,1851,1460,2426,1528,1392,1973,3237, 288,3309, 685,3386, 296, 892,2716,2216, # 2288
-1570,2245, 722,1747,2217, 905,3238,1103,6135,1893,1441,1965, 251,1805,2371,3700, # 2304
-2601,1919,1078, 75,2182,1509,1592,1270,2640,4638,2152,6136,3310,3817, 524, 706, # 2320
-1075, 292,3818,1756,2602, 317, 98,3173,3605,3525,1844,2218,3819,2502, 814, 567, # 2336
- 385,2908,1534,6137, 534,1642,3239, 797,6138,1670,1529, 953,4323, 188,1071, 538, # 2352
- 178, 729,3240,2109,1226,1374,2000,2357,2977, 731,2468,1116,2014,2051,6139,1261, # 2368
-1593, 803,2859,2736,3443, 556, 682, 823,1541,6140,1369,2289,1706,2794, 845, 462, # 2384
-2603,2665,1361, 387, 162,2358,1740, 739,1770,1720,1304,1401,3241,1049, 627,1571, # 2400
-2427,3526,1877,3942,1852,1500, 431,1910,1503, 677, 297,2795, 286,1433,1038,1198, # 2416
-2290,1133,1596,4113,4639,2469,1510,1484,3943,6141,2442, 108, 712,4640,2372, 866, # 2432
-3701,2755,3242,1348, 834,1945,1408,3527,2395,3243,1811, 824, 994,1179,2110,1548, # 2448
-1453, 790,3003, 690,4324,4325,2832,2909,3820,1860,3821, 225,1748, 310, 346,1780, # 2464
-2470, 821,1993,2717,2796, 828, 877,3528,2860,2471,1702,2165,2910,2486,1789, 453, # 2480
- 359,2291,1676, 73,1164,1461,1127,3311, 421, 604, 314,1037, 589, 116,2487, 737, # 2496
- 837,1180, 111, 244, 735,6142,2261,1861,1362, 986, 523, 418, 581,2666,3822, 103, # 2512
- 855, 503,1414,1867,2488,1091, 657,1597, 979, 605,1316,4641,1021,2443,2078,2001, # 2528
-1209, 96, 587,2166,1032, 260,1072,2153, 173, 94, 226,3244, 819,2006,4642,4114, # 2544
-2203, 231,1744, 782, 97,2667, 786,3387, 887, 391, 442,2219,4326,1425,6143,2694, # 2560
- 633,1544,1202, 483,2015, 592,2052,1958,2472,1655, 419, 129,4327,3444,3312,1714, # 2576
-1257,3078,4328,1518,1098, 865,1310,1019,1885,1512,1734, 469,2444, 148, 773, 436, # 2592
-1815,1868,1128,1055,4329,1245,2756,3445,2154,1934,1039,4643, 579,1238, 932,2320, # 2608
- 353, 205, 801, 115,2428, 944,2321,1881, 399,2565,1211, 678, 766,3944, 335,2101, # 2624
-1459,1781,1402,3945,2737,2131,1010, 844, 981,1326,1013, 550,1816,1545,2620,1335, # 2640
-1008, 371,2881, 936,1419,1613,3529,1456,1395,2273,1834,2604,1317,2738,2503, 416, # 2656
-1643,4330, 806,1126, 229, 591,3946,1314,1981,1576,1837,1666, 347,1790, 977,3313, # 2672
- 764,2861,1853, 688,2429,1920,1462, 77, 595, 415,2002,3034, 798,1192,4115,6144, # 2688
-2978,4331,3035,2695,2582,2072,2566, 430,2430,1727, 842,1396,3947,3702, 613, 377, # 2704
- 278, 236,1417,3388,3314,3174, 757,1869, 107,3530,6145,1194, 623,2262, 207,1253, # 2720
-2167,3446,3948, 492,1117,1935, 536,1838,2757,1246,4332, 696,2095,2406,1393,1572, # 2736
-3175,1782, 583, 190, 253,1390,2230, 830,3126,3389, 934,3245,1703,1749,2979,1870, # 2752
-2545,1656,2204, 869,2346,4116,3176,1817, 496,1764,4644, 942,1504, 404,1903,1122, # 2768
-1580,3606,2945,1022, 515, 372,1735, 955,2431,3036,6146,2797,1110,2302,2798, 617, # 2784
-6147, 441, 762,1771,3447,3607,3608,1904, 840,3037, 86, 939,1385, 572,1370,2445, # 2800
-1336, 114,3703, 898, 294, 203,3315, 703,1583,2274, 429, 961,4333,1854,1951,3390, # 2816
-2373,3704,4334,1318,1381, 966,1911,2322,1006,1155, 309, 989, 458,2718,1795,1372, # 2832
-1203, 252,1689,1363,3177, 517,1936, 168,1490, 562, 193,3823,1042,4117,1835, 551, # 2848
- 470,4645, 395, 489,3448,1871,1465,2583,2641, 417,1493, 279,1295, 511,1236,1119, # 2864
- 72,1231,1982,1812,3004, 871,1564, 984,3449,1667,2696,2096,4646,2347,2833,1673, # 2880
-3609, 695,3246,2668, 807,1183,4647, 890, 388,2333,1801,1457,2911,1765,1477,1031, # 2896
-3316,3317,1278,3391,2799,2292,2526, 163,3450,4335,2669,1404,1802,6148,2323,2407, # 2912
-1584,1728,1494,1824,1269, 298, 909,3318,1034,1632, 375, 776,1683,2061, 291, 210, # 2928
-1123, 809,1249,1002,2642,3038, 206,1011,2132, 144, 975, 882,1565, 342, 667, 754, # 2944
-1442,2143,1299,2303,2062, 447, 626,2205,1221,2739,2912,1144,1214,2206,2584, 760, # 2960
-1715, 614, 950,1281,2670,2621, 810, 577,1287,2546,4648, 242,2168, 250,2643, 691, # 2976
- 123,2644, 647, 313,1029, 689,1357,2946,1650, 216, 771,1339,1306, 808,2063, 549, # 2992
- 913,1371,2913,2914,6149,1466,1092,1174,1196,1311,2605,2396,1783,1796,3079, 406, # 3008
-2671,2117,3949,4649, 487,1825,2220,6150,2915, 448,2348,1073,6151,2397,1707, 130, # 3024
- 900,1598, 329, 176,1959,2527,1620,6152,2275,4336,3319,1983,2191,3705,3610,2155, # 3040
-3706,1912,1513,1614,6153,1988, 646, 392,2304,1589,3320,3039,1826,1239,1352,1340, # 3056
-2916, 505,2567,1709,1437,2408,2547, 906,6154,2672, 384,1458,1594,1100,1329, 710, # 3072
- 423,3531,2064,2231,2622,1989,2673,1087,1882, 333, 841,3005,1296,2882,2379, 580, # 3088
-1937,1827,1293,2585, 601, 574, 249,1772,4118,2079,1120, 645, 901,1176,1690, 795, # 3104
-2207, 478,1434, 516,1190,1530, 761,2080, 930,1264, 355, 435,1552, 644,1791, 987, # 3120
- 220,1364,1163,1121,1538, 306,2169,1327,1222, 546,2645, 218, 241, 610,1704,3321, # 3136
-1984,1839,1966,2528, 451,6155,2586,3707,2568, 907,3178, 254,2947, 186,1845,4650, # 3152
- 745, 432,1757, 428,1633, 888,2246,2221,2489,3611,2118,1258,1265, 956,3127,1784, # 3168
-4337,2490, 319, 510, 119, 457,3612, 274,2035,2007,4651,1409,3128, 970,2758, 590, # 3184
-2800, 661,2247,4652,2008,3950,1420,1549,3080,3322,3951,1651,1375,2111, 485,2491, # 3200
-1429,1156,6156,2548,2183,1495, 831,1840,2529,2446, 501,1657, 307,1894,3247,1341, # 3216
- 666, 899,2156,1539,2549,1559, 886, 349,2208,3081,2305,1736,3824,2170,2759,1014, # 3232
-1913,1386, 542,1397,2948, 490, 368, 716, 362, 159, 282,2569,1129,1658,1288,1750, # 3248
-2674, 276, 649,2016, 751,1496, 658,1818,1284,1862,2209,2087,2512,3451, 622,2834, # 3264
- 376, 117,1060,2053,1208,1721,1101,1443, 247,1250,3179,1792,3952,2760,2398,3953, # 3280
-6157,2144,3708, 446,2432,1151,2570,3452,2447,2761,2835,1210,2448,3082, 424,2222, # 3296
-1251,2449,2119,2836, 504,1581,4338, 602, 817, 857,3825,2349,2306, 357,3826,1470, # 3312
-1883,2883, 255, 958, 929,2917,3248, 302,4653,1050,1271,1751,2307,1952,1430,2697, # 3328
-2719,2359, 354,3180, 777, 158,2036,4339,1659,4340,4654,2308,2949,2248,1146,2232, # 3344
-3532,2720,1696,2623,3827,6158,3129,1550,2698,1485,1297,1428, 637, 931,2721,2145, # 3360
- 914,2550,2587, 81,2450, 612, 827,2646,1242,4655,1118,2884, 472,1855,3181,3533, # 3376
-3534, 569,1353,2699,1244,1758,2588,4119,2009,2762,2171,3709,1312,1531,6159,1152, # 3392
-1938, 134,1830, 471,3710,2276,1112,1535,3323,3453,3535, 982,1337,2950, 488, 826, # 3408
- 674,1058,1628,4120,2017, 522,2399, 211, 568,1367,3454, 350, 293,1872,1139,3249, # 3424
-1399,1946,3006,1300,2360,3324, 588, 736,6160,2606, 744, 669,3536,3828,6161,1358, # 3440
- 199, 723, 848, 933, 851,1939,1505,1514,1338,1618,1831,4656,1634,3613, 443,2740, # 3456
-3829, 717,1947, 491,1914,6162,2551,1542,4121,1025,6163,1099,1223, 198,3040,2722, # 3472
- 370, 410,1905,2589, 998,1248,3182,2380, 519,1449,4122,1710, 947, 928,1153,4341, # 3488
-2277, 344,2624,1511, 615, 105, 161,1212,1076,1960,3130,2054,1926,1175,1906,2473, # 3504
- 414,1873,2801,6164,2309, 315,1319,3325, 318,2018,2146,2157, 963, 631, 223,4342, # 3520
-4343,2675, 479,3711,1197,2625,3712,2676,2361,6165,4344,4123,6166,2451,3183,1886, # 3536
-2184,1674,1330,1711,1635,1506, 799, 219,3250,3083,3954,1677,3713,3326,2081,3614, # 3552
-1652,2073,4657,1147,3041,1752, 643,1961, 147,1974,3955,6167,1716,2037, 918,3007, # 3568
-1994, 120,1537, 118, 609,3184,4345, 740,3455,1219, 332,1615,3830,6168,1621,2980, # 3584
-1582, 783, 212, 553,2350,3714,1349,2433,2082,4124, 889,6169,2310,1275,1410, 973, # 3600
- 166,1320,3456,1797,1215,3185,2885,1846,2590,2763,4658, 629, 822,3008, 763, 940, # 3616
-1990,2862, 439,2409,1566,1240,1622, 926,1282,1907,2764, 654,2210,1607, 327,1130, # 3632
-3956,1678,1623,6170,2434,2192, 686, 608,3831,3715, 903,3957,3042,6171,2741,1522, # 3648
-1915,1105,1555,2552,1359, 323,3251,4346,3457, 738,1354,2553,2311,2334,1828,2003, # 3664
-3832,1753,2351,1227,6172,1887,4125,1478,6173,2410,1874,1712,1847, 520,1204,2607, # 3680
- 264,4659, 836,2677,2102, 600,4660,3833,2278,3084,6174,4347,3615,1342, 640, 532, # 3696
- 543,2608,1888,2400,2591,1009,4348,1497, 341,1737,3616,2723,1394, 529,3252,1321, # 3712
- 983,4661,1515,2120, 971,2592, 924, 287,1662,3186,4349,2700,4350,1519, 908,1948, # 3728
-2452, 156, 796,1629,1486,2223,2055, 694,4126,1259,1036,3392,1213,2249,2742,1889, # 3744
-1230,3958,1015, 910, 408, 559,3617,4662, 746, 725, 935,4663,3959,3009,1289, 563, # 3760
- 867,4664,3960,1567,2981,2038,2626, 988,2263,2381,4351, 143,2374, 704,1895,6175, # 3776
-1188,3716,2088, 673,3085,2362,4352, 484,1608,1921,2765,2918, 215, 904,3618,3537, # 3792
- 894, 509, 976,3043,2701,3961,4353,2837,2982, 498,6176,6177,1102,3538,1332,3393, # 3808
-1487,1636,1637, 233, 245,3962, 383, 650, 995,3044, 460,1520,1206,2352, 749,3327, # 3824
- 530, 700, 389,1438,1560,1773,3963,2264, 719,2951,2724,3834, 870,1832,1644,1000, # 3840
- 839,2474,3717, 197,1630,3394, 365,2886,3964,1285,2133, 734, 922, 818,1106, 732, # 3856
- 480,2083,1774,3458, 923,2279,1350, 221,3086, 85,2233,2234,3835,1585,3010,2147, # 3872
-1387,1705,2382,1619,2475, 133, 239,2802,1991,1016,2084,2383, 411,2838,1113, 651, # 3888
-1985,1160,3328, 990,1863,3087,1048,1276,2647, 265,2627,1599,3253,2056, 150, 638, # 3904
-2019, 656, 853, 326,1479, 680,1439,4354,1001,1759, 413,3459,3395,2492,1431, 459, # 3920
-4355,1125,3329,2265,1953,1450,2065,2863, 849, 351,2678,3131,3254,3255,1104,1577, # 3936
- 227,1351,1645,2453,2193,1421,2887, 812,2121, 634, 95,2435, 201,2312,4665,1646, # 3952
-1671,2743,1601,2554,2702,2648,2280,1315,1366,2089,3132,1573,3718,3965,1729,1189, # 3968
- 328,2679,1077,1940,1136, 558,1283, 964,1195, 621,2074,1199,1743,3460,3619,1896, # 3984
-1916,1890,3836,2952,1154,2112,1064, 862, 378,3011,2066,2113,2803,1568,2839,6178, # 4000
-3088,2919,1941,1660,2004,1992,2194, 142, 707,1590,1708,1624,1922,1023,1836,1233, # 4016
-1004,2313, 789, 741,3620,6179,1609,2411,1200,4127,3719,3720,4666,2057,3721, 593, # 4032
-2840, 367,2920,1878,6180,3461,1521, 628,1168, 692,2211,2649, 300, 720,2067,2571, # 4048
-2953,3396, 959,2504,3966,3539,3462,1977, 701,6181, 954,1043, 800, 681, 183,3722, # 4064
-1803,1730,3540,4128,2103, 815,2314, 174, 467, 230,2454,1093,2134, 755,3541,3397, # 4080
-1141,1162,6182,1738,2039, 270,3256,2513,1005,1647,2185,3837, 858,1679,1897,1719, # 4096
-2954,2324,1806, 402, 670, 167,4129,1498,2158,2104, 750,6183, 915, 189,1680,1551, # 4112
- 455,4356,1501,2455, 405,1095,2955, 338,1586,1266,1819, 570, 641,1324, 237,1556, # 4128
-2650,1388,3723,6184,1368,2384,1343,1978,3089,2436, 879,3724, 792,1191, 758,3012, # 4144
-1411,2135,1322,4357, 240,4667,1848,3725,1574,6185, 420,3045,1546,1391, 714,4358, # 4160
-1967, 941,1864, 863, 664, 426, 560,1731,2680,1785,2864,1949,2363, 403,3330,1415, # 4176
-1279,2136,1697,2335, 204, 721,2097,3838, 90,6186,2085,2505, 191,3967, 124,2148, # 4192
-1376,1798,1178,1107,1898,1405, 860,4359,1243,1272,2375,2983,1558,2456,1638, 113, # 4208
-3621, 578,1923,2609, 880, 386,4130, 784,2186,2266,1422,2956,2172,1722, 497, 263, # 4224
-2514,1267,2412,2610, 177,2703,3542, 774,1927,1344, 616,1432,1595,1018, 172,4360, # 4240
-2325, 911,4361, 438,1468,3622, 794,3968,2024,2173,1681,1829,2957, 945, 895,3090, # 4256
- 575,2212,2476, 475,2401,2681, 785,2744,1745,2293,2555,1975,3133,2865, 394,4668, # 4272
-3839, 635,4131, 639, 202,1507,2195,2766,1345,1435,2572,3726,1908,1184,1181,2457, # 4288
-3727,3134,4362, 843,2611, 437, 916,4669, 234, 769,1884,3046,3047,3623, 833,6187, # 4304
-1639,2250,2402,1355,1185,2010,2047, 999, 525,1732,1290,1488,2612, 948,1578,3728, # 4320
-2413,2477,1216,2725,2159, 334,3840,1328,3624,2921,1525,4132, 564,1056, 891,4363, # 4336
-1444,1698,2385,2251,3729,1365,2281,2235,1717,6188, 864,3841,2515, 444, 527,2767, # 4352
-2922,3625, 544, 461,6189, 566, 209,2437,3398,2098,1065,2068,3331,3626,3257,2137, # 4368 #last 512
-#Everything below is of no interest for detection purpose
-2138,2122,3730,2888,1995,1820,1044,6190,6191,6192,6193,6194,6195,6196,6197,6198, # 4384
-6199,6200,6201,6202,6203,6204,6205,4670,6206,6207,6208,6209,6210,6211,6212,6213, # 4400
-6214,6215,6216,6217,6218,6219,6220,6221,6222,6223,6224,6225,6226,6227,6228,6229, # 4416
-6230,6231,6232,6233,6234,6235,6236,6237,3187,6238,6239,3969,6240,6241,6242,6243, # 4432
-6244,4671,6245,6246,4672,6247,6248,4133,6249,6250,4364,6251,2923,2556,2613,4673, # 4448
-4365,3970,6252,6253,6254,6255,4674,6256,6257,6258,2768,2353,4366,4675,4676,3188, # 4464
-4367,3463,6259,4134,4677,4678,6260,2267,6261,3842,3332,4368,3543,6262,6263,6264, # 4480
-3013,1954,1928,4135,4679,6265,6266,2478,3091,6267,4680,4369,6268,6269,1699,6270, # 4496
-3544,4136,4681,6271,4137,6272,4370,2804,6273,6274,2593,3971,3972,4682,6275,2236, # 4512
-4683,6276,6277,4684,6278,6279,4138,3973,4685,6280,6281,3258,6282,6283,6284,6285, # 4528
-3974,4686,2841,3975,6286,6287,3545,6288,6289,4139,4687,4140,6290,4141,6291,4142, # 4544
-6292,6293,3333,6294,6295,6296,4371,6297,3399,6298,6299,4372,3976,6300,6301,6302, # 4560
-4373,6303,6304,3843,3731,6305,4688,4374,6306,6307,3259,2294,6308,3732,2530,4143, # 4576
-6309,4689,6310,6311,6312,3048,6313,6314,4690,3733,2237,6315,6316,2282,3334,6317, # 4592
-6318,3844,6319,6320,4691,6321,3400,4692,6322,4693,6323,3049,6324,4375,6325,3977, # 4608
-6326,6327,6328,3546,6329,4694,3335,6330,4695,4696,6331,6332,6333,6334,4376,3978, # 4624
-6335,4697,3979,4144,6336,3980,4698,6337,6338,6339,6340,6341,4699,4700,4701,6342, # 4640
-6343,4702,6344,6345,4703,6346,6347,4704,6348,4705,4706,3135,6349,4707,6350,4708, # 4656
-6351,4377,6352,4709,3734,4145,6353,2506,4710,3189,6354,3050,4711,3981,6355,3547, # 4672
-3014,4146,4378,3735,2651,3845,3260,3136,2224,1986,6356,3401,6357,4712,2594,3627, # 4688
-3137,2573,3736,3982,4713,3628,4714,4715,2682,3629,4716,6358,3630,4379,3631,6359, # 4704
-6360,6361,3983,6362,6363,6364,6365,4147,3846,4717,6366,6367,3737,2842,6368,4718, # 4720
-2628,6369,3261,6370,2386,6371,6372,3738,3984,4719,3464,4720,3402,6373,2924,3336, # 4736
-4148,2866,6374,2805,3262,4380,2704,2069,2531,3138,2806,2984,6375,2769,6376,4721, # 4752
-4722,3403,6377,6378,3548,6379,6380,2705,3092,1979,4149,2629,3337,2889,6381,3338, # 4768
-4150,2557,3339,4381,6382,3190,3263,3739,6383,4151,4723,4152,2558,2574,3404,3191, # 4784
-6384,6385,4153,6386,4724,4382,6387,6388,4383,6389,6390,4154,6391,4725,3985,6392, # 4800
-3847,4155,6393,6394,6395,6396,6397,3465,6398,4384,6399,6400,6401,6402,6403,6404, # 4816
-4156,6405,6406,6407,6408,2123,6409,6410,2326,3192,4726,6411,6412,6413,6414,4385, # 4832
-4157,6415,6416,4158,6417,3093,3848,6418,3986,6419,6420,3849,6421,6422,6423,4159, # 4848
-6424,6425,4160,6426,3740,6427,6428,6429,6430,3987,6431,4727,6432,2238,6433,6434, # 4864
-4386,3988,6435,6436,3632,6437,6438,2843,6439,6440,6441,6442,3633,6443,2958,6444, # 4880
-6445,3466,6446,2364,4387,3850,6447,4388,2959,3340,6448,3851,6449,4728,6450,6451, # 4896
-3264,4729,6452,3193,6453,4389,4390,2706,3341,4730,6454,3139,6455,3194,6456,3051, # 4912
-2124,3852,1602,4391,4161,3853,1158,3854,4162,3989,4392,3990,4731,4732,4393,2040, # 4928
-4163,4394,3265,6457,2807,3467,3855,6458,6459,6460,3991,3468,4733,4734,6461,3140, # 4944
-2960,6462,4735,6463,6464,6465,6466,4736,4737,4738,4739,6467,6468,4164,2403,3856, # 4960
-6469,6470,2770,2844,6471,4740,6472,6473,6474,6475,6476,6477,6478,3195,6479,4741, # 4976
-4395,6480,2867,6481,4742,2808,6482,2493,4165,6483,6484,6485,6486,2295,4743,6487, # 4992
-6488,6489,3634,6490,6491,6492,6493,6494,6495,6496,2985,4744,6497,6498,4745,6499, # 5008
-6500,2925,3141,4166,6501,6502,4746,6503,6504,4747,6505,6506,6507,2890,6508,6509, # 5024
-6510,6511,6512,6513,6514,6515,6516,6517,6518,6519,3469,4167,6520,6521,6522,4748, # 5040
-4396,3741,4397,4749,4398,3342,2125,4750,6523,4751,4752,4753,3052,6524,2961,4168, # 5056
-6525,4754,6526,4755,4399,2926,4169,6527,3857,6528,4400,4170,6529,4171,6530,6531, # 5072
-2595,6532,6533,6534,6535,3635,6536,6537,6538,6539,6540,6541,6542,4756,6543,6544, # 5088
-6545,6546,6547,6548,4401,6549,6550,6551,6552,4402,3405,4757,4403,6553,6554,6555, # 5104
-4172,3742,6556,6557,6558,3992,3636,6559,6560,3053,2726,6561,3549,4173,3054,4404, # 5120
-6562,6563,3993,4405,3266,3550,2809,4406,6564,6565,6566,4758,4759,6567,3743,6568, # 5136
-4760,3744,4761,3470,6569,6570,6571,4407,6572,3745,4174,6573,4175,2810,4176,3196, # 5152
-4762,6574,4177,6575,6576,2494,2891,3551,6577,6578,3471,6579,4408,6580,3015,3197, # 5168
-6581,3343,2532,3994,3858,6582,3094,3406,4409,6583,2892,4178,4763,4410,3016,4411, # 5184
-6584,3995,3142,3017,2683,6585,4179,6586,6587,4764,4412,6588,6589,4413,6590,2986, # 5200
-6591,2962,3552,6592,2963,3472,6593,6594,4180,4765,6595,6596,2225,3267,4414,6597, # 5216
-3407,3637,4766,6598,6599,3198,6600,4415,6601,3859,3199,6602,3473,4767,2811,4416, # 5232
-1856,3268,3200,2575,3996,3997,3201,4417,6603,3095,2927,6604,3143,6605,2268,6606, # 5248
-3998,3860,3096,2771,6607,6608,3638,2495,4768,6609,3861,6610,3269,2745,4769,4181, # 5264
-3553,6611,2845,3270,6612,6613,6614,3862,6615,6616,4770,4771,6617,3474,3999,4418, # 5280
-4419,6618,3639,3344,6619,4772,4182,6620,2126,6621,6622,6623,4420,4773,6624,3018, # 5296
-6625,4774,3554,6626,4183,2025,3746,6627,4184,2707,6628,4421,4422,3097,1775,4185, # 5312
-3555,6629,6630,2868,6631,6632,4423,6633,6634,4424,2414,2533,2928,6635,4186,2387, # 5328
-6636,4775,6637,4187,6638,1891,4425,3202,3203,6639,6640,4776,6641,3345,6642,6643, # 5344
-3640,6644,3475,3346,3641,4000,6645,3144,6646,3098,2812,4188,3642,3204,6647,3863, # 5360
-3476,6648,3864,6649,4426,4001,6650,6651,6652,2576,6653,4189,4777,6654,6655,6656, # 5376
-2846,6657,3477,3205,4002,6658,4003,6659,3347,2252,6660,6661,6662,4778,6663,6664, # 5392
-6665,6666,6667,6668,6669,4779,4780,2048,6670,3478,3099,6671,3556,3747,4004,6672, # 5408
-6673,6674,3145,4005,3748,6675,6676,6677,6678,6679,3408,6680,6681,6682,6683,3206, # 5424
-3207,6684,6685,4781,4427,6686,4782,4783,4784,6687,6688,6689,4190,6690,6691,3479, # 5440
-6692,2746,6693,4428,6694,6695,6696,6697,6698,6699,4785,6700,6701,3208,2727,6702, # 5456
-3146,6703,6704,3409,2196,6705,4429,6706,6707,6708,2534,1996,6709,6710,6711,2747, # 5472
-6712,6713,6714,4786,3643,6715,4430,4431,6716,3557,6717,4432,4433,6718,6719,6720, # 5488
-6721,3749,6722,4006,4787,6723,6724,3644,4788,4434,6725,6726,4789,2772,6727,6728, # 5504
-6729,6730,6731,2708,3865,2813,4435,6732,6733,4790,4791,3480,6734,6735,6736,6737, # 5520
-4436,3348,6738,3410,4007,6739,6740,4008,6741,6742,4792,3411,4191,6743,6744,6745, # 5536
-6746,6747,3866,6748,3750,6749,6750,6751,6752,6753,6754,6755,3867,6756,4009,6757, # 5552
-4793,4794,6758,2814,2987,6759,6760,6761,4437,6762,6763,6764,6765,3645,6766,6767, # 5568
-3481,4192,6768,3751,6769,6770,2174,6771,3868,3752,6772,6773,6774,4193,4795,4438, # 5584
-3558,4796,4439,6775,4797,6776,6777,4798,6778,4799,3559,4800,6779,6780,6781,3482, # 5600
-6782,2893,6783,6784,4194,4801,4010,6785,6786,4440,6787,4011,6788,6789,6790,6791, # 5616
-6792,6793,4802,6794,6795,6796,4012,6797,6798,6799,6800,3349,4803,3483,6801,4804, # 5632
-4195,6802,4013,6803,6804,4196,6805,4014,4015,6806,2847,3271,2848,6807,3484,6808, # 5648
-6809,6810,4441,6811,4442,4197,4443,3272,4805,6812,3412,4016,1579,6813,6814,4017, # 5664
-6815,3869,6816,2964,6817,4806,6818,6819,4018,3646,6820,6821,4807,4019,4020,6822, # 5680
-6823,3560,6824,6825,4021,4444,6826,4198,6827,6828,4445,6829,6830,4199,4808,6831, # 5696
-6832,6833,3870,3019,2458,6834,3753,3413,3350,6835,4809,3871,4810,3561,4446,6836, # 5712
-6837,4447,4811,4812,6838,2459,4448,6839,4449,6840,6841,4022,3872,6842,4813,4814, # 5728
-6843,6844,4815,4200,4201,4202,6845,4023,6846,6847,4450,3562,3873,6848,6849,4816, # 5744
-4817,6850,4451,4818,2139,6851,3563,6852,6853,3351,6854,6855,3352,4024,2709,3414, # 5760
-4203,4452,6856,4204,6857,6858,3874,3875,6859,6860,4819,6861,6862,6863,6864,4453, # 5776
-3647,6865,6866,4820,6867,6868,6869,6870,4454,6871,2869,6872,6873,4821,6874,3754, # 5792
-6875,4822,4205,6876,6877,6878,3648,4206,4455,6879,4823,6880,4824,3876,6881,3055, # 5808
-4207,6882,3415,6883,6884,6885,4208,4209,6886,4210,3353,6887,3354,3564,3209,3485, # 5824
-2652,6888,2728,6889,3210,3755,6890,4025,4456,6891,4825,6892,6893,6894,6895,4211, # 5840
-6896,6897,6898,4826,6899,6900,4212,6901,4827,6902,2773,3565,6903,4828,6904,6905, # 5856
-6906,6907,3649,3650,6908,2849,3566,6909,3567,3100,6910,6911,6912,6913,6914,6915, # 5872
-4026,6916,3355,4829,3056,4457,3756,6917,3651,6918,4213,3652,2870,6919,4458,6920, # 5888
-2438,6921,6922,3757,2774,4830,6923,3356,4831,4832,6924,4833,4459,3653,2507,6925, # 5904
-4834,2535,6926,6927,3273,4027,3147,6928,3568,6929,6930,6931,4460,6932,3877,4461, # 5920
-2729,3654,6933,6934,6935,6936,2175,4835,2630,4214,4028,4462,4836,4215,6937,3148, # 5936
-4216,4463,4837,4838,4217,6938,6939,2850,4839,6940,4464,6941,6942,6943,4840,6944, # 5952
-4218,3274,4465,6945,6946,2710,6947,4841,4466,6948,6949,2894,6950,6951,4842,6952, # 5968
-4219,3057,2871,6953,6954,6955,6956,4467,6957,2711,6958,6959,6960,3275,3101,4843, # 5984
-6961,3357,3569,6962,4844,6963,6964,4468,4845,3570,6965,3102,4846,3758,6966,4847, # 6000
-3878,4848,4849,4029,6967,2929,3879,4850,4851,6968,6969,1733,6970,4220,6971,6972, # 6016
-6973,6974,6975,6976,4852,6977,6978,6979,6980,6981,6982,3759,6983,6984,6985,3486, # 6032
-3487,6986,3488,3416,6987,6988,6989,6990,6991,6992,6993,6994,6995,6996,6997,4853, # 6048
-6998,6999,4030,7000,7001,3211,7002,7003,4221,7004,7005,3571,4031,7006,3572,7007, # 6064
-2614,4854,2577,7008,7009,2965,3655,3656,4855,2775,3489,3880,4222,4856,3881,4032, # 6080
-3882,3657,2730,3490,4857,7010,3149,7011,4469,4858,2496,3491,4859,2283,7012,7013, # 6096
-7014,2365,4860,4470,7015,7016,3760,7017,7018,4223,1917,7019,7020,7021,4471,7022, # 6112
-2776,4472,7023,7024,7025,7026,4033,7027,3573,4224,4861,4034,4862,7028,7029,1929, # 6128
-3883,4035,7030,4473,3058,7031,2536,3761,3884,7032,4036,7033,2966,2895,1968,4474, # 6144
-3276,4225,3417,3492,4226,2105,7034,7035,1754,2596,3762,4227,4863,4475,3763,4864, # 6160
-3764,2615,2777,3103,3765,3658,3418,4865,2296,3766,2815,7036,7037,7038,3574,2872, # 6176
-3277,4476,7039,4037,4477,7040,7041,4038,7042,7043,7044,7045,7046,7047,2537,7048, # 6192
-7049,7050,7051,7052,7053,7054,4478,7055,7056,3767,3659,4228,3575,7057,7058,4229, # 6208
-7059,7060,7061,3660,7062,3212,7063,3885,4039,2460,7064,7065,7066,7067,7068,7069, # 6224
-7070,7071,7072,7073,7074,4866,3768,4867,7075,7076,7077,7078,4868,3358,3278,2653, # 6240
-7079,7080,4479,3886,7081,7082,4869,7083,7084,7085,7086,7087,7088,2538,7089,7090, # 6256
-7091,4040,3150,3769,4870,4041,2896,3359,4230,2930,7092,3279,7093,2967,4480,3213, # 6272
-4481,3661,7094,7095,7096,7097,7098,7099,7100,7101,7102,2461,3770,7103,7104,4231, # 6288
-3151,7105,7106,7107,4042,3662,7108,7109,4871,3663,4872,4043,3059,7110,7111,7112, # 6304
-3493,2988,7113,4873,7114,7115,7116,3771,4874,7117,7118,4232,4875,7119,3576,2336, # 6320
-4876,7120,4233,3419,4044,4877,4878,4482,4483,4879,4484,4234,7121,3772,4880,1045, # 6336
-3280,3664,4881,4882,7122,7123,7124,7125,4883,7126,2778,7127,4485,4486,7128,4884, # 6352
-3214,3887,7129,7130,3215,7131,4885,4045,7132,7133,4046,7134,7135,7136,7137,7138, # 6368
-7139,7140,7141,7142,7143,4235,7144,4886,7145,7146,7147,4887,7148,7149,7150,4487, # 6384
-4047,4488,7151,7152,4888,4048,2989,3888,7153,3665,7154,4049,7155,7156,7157,7158, # 6400
-7159,7160,2931,4889,4890,4489,7161,2631,3889,4236,2779,7162,7163,4891,7164,3060, # 6416
-7165,1672,4892,7166,4893,4237,3281,4894,7167,7168,3666,7169,3494,7170,7171,4050, # 6432
-7172,7173,3104,3360,3420,4490,4051,2684,4052,7174,4053,7175,7176,7177,2253,4054, # 6448
-7178,7179,4895,7180,3152,3890,3153,4491,3216,7181,7182,7183,2968,4238,4492,4055, # 6464
-7184,2990,7185,2479,7186,7187,4493,7188,7189,7190,7191,7192,4896,7193,4897,2969, # 6480
-4494,4898,7194,3495,7195,7196,4899,4495,7197,3105,2731,7198,4900,7199,7200,7201, # 6496
-4056,7202,3361,7203,7204,4496,4901,4902,7205,4497,7206,7207,2315,4903,7208,4904, # 6512
-7209,4905,2851,7210,7211,3577,7212,3578,4906,7213,4057,3667,4907,7214,4058,2354, # 6528
-3891,2376,3217,3773,7215,7216,7217,7218,7219,4498,7220,4908,3282,2685,7221,3496, # 6544
-4909,2632,3154,4910,7222,2337,7223,4911,7224,7225,7226,4912,4913,3283,4239,4499, # 6560
-7227,2816,7228,7229,7230,7231,7232,7233,7234,4914,4500,4501,7235,7236,7237,2686, # 6576
-7238,4915,7239,2897,4502,7240,4503,7241,2516,7242,4504,3362,3218,7243,7244,7245, # 6592
-4916,7246,7247,4505,3363,7248,7249,7250,7251,3774,4506,7252,7253,4917,7254,7255, # 6608
-3284,2991,4918,4919,3219,3892,4920,3106,3497,4921,7256,7257,7258,4922,7259,4923, # 6624
-3364,4507,4508,4059,7260,4240,3498,7261,7262,4924,7263,2992,3893,4060,3220,7264, # 6640
-7265,7266,7267,7268,7269,4509,3775,7270,2817,7271,4061,4925,4510,3776,7272,4241, # 6656
-4511,3285,7273,7274,3499,7275,7276,7277,4062,4512,4926,7278,3107,3894,7279,7280, # 6672
-4927,7281,4513,7282,7283,3668,7284,7285,4242,4514,4243,7286,2058,4515,4928,4929, # 6688
-4516,7287,3286,4244,7288,4517,7289,7290,7291,3669,7292,7293,4930,4931,4932,2355, # 6704
-4933,7294,2633,4518,7295,4245,7296,7297,4519,7298,7299,4520,4521,4934,7300,4246, # 6720
-4522,7301,7302,7303,3579,7304,4247,4935,7305,4936,7306,7307,7308,7309,3777,7310, # 6736
-4523,7311,7312,7313,4248,3580,7314,4524,3778,4249,7315,3581,7316,3287,7317,3221, # 6752
-7318,4937,7319,7320,7321,7322,7323,7324,4938,4939,7325,4525,7326,7327,7328,4063, # 6768
-7329,7330,4940,7331,7332,4941,7333,4526,7334,3500,2780,1741,4942,2026,1742,7335, # 6784
-7336,3582,4527,2388,7337,7338,7339,4528,7340,4250,4943,7341,7342,7343,4944,7344, # 6800
-7345,7346,3020,7347,4945,7348,7349,7350,7351,3895,7352,3896,4064,3897,7353,7354, # 6816
-7355,4251,7356,7357,3898,7358,3779,7359,3780,3288,7360,7361,4529,7362,4946,4530, # 6832
-2027,7363,3899,4531,4947,3222,3583,7364,4948,7365,7366,7367,7368,4949,3501,4950, # 6848
-3781,4951,4532,7369,2517,4952,4252,4953,3155,7370,4954,4955,4253,2518,4533,7371, # 6864
-7372,2712,4254,7373,7374,7375,3670,4956,3671,7376,2389,3502,4065,7377,2338,7378, # 6880
-7379,7380,7381,3061,7382,4957,7383,7384,7385,7386,4958,4534,7387,7388,2993,7389, # 6896
-3062,7390,4959,7391,7392,7393,4960,3108,4961,7394,4535,7395,4962,3421,4536,7396, # 6912
-4963,7397,4964,1857,7398,4965,7399,7400,2176,3584,4966,7401,7402,3422,4537,3900, # 6928
-3585,7403,3782,7404,2852,7405,7406,7407,4538,3783,2654,3423,4967,4539,7408,3784, # 6944
-3586,2853,4540,4541,7409,3901,7410,3902,7411,7412,3785,3109,2327,3903,7413,7414, # 6960
-2970,4066,2932,7415,7416,7417,3904,3672,3424,7418,4542,4543,4544,7419,4968,7420, # 6976
-7421,4255,7422,7423,7424,7425,7426,4067,7427,3673,3365,4545,7428,3110,2559,3674, # 6992
-7429,7430,3156,7431,7432,3503,7433,3425,4546,7434,3063,2873,7435,3223,4969,4547, # 7008
-4548,2898,4256,4068,7436,4069,3587,3786,2933,3787,4257,4970,4971,3788,7437,4972, # 7024
-3064,7438,4549,7439,7440,7441,7442,7443,4973,3905,7444,2874,7445,7446,7447,7448, # 7040
-3021,7449,4550,3906,3588,4974,7450,7451,3789,3675,7452,2578,7453,4070,7454,7455, # 7056
-7456,4258,3676,7457,4975,7458,4976,4259,3790,3504,2634,4977,3677,4551,4260,7459, # 7072
-7460,7461,7462,3907,4261,4978,7463,7464,7465,7466,4979,4980,7467,7468,2213,4262, # 7088
-7469,7470,7471,3678,4981,7472,2439,7473,4263,3224,3289,7474,3908,2415,4982,7475, # 7104
-4264,7476,4983,2655,7477,7478,2732,4552,2854,2875,7479,7480,4265,7481,4553,4984, # 7120
-7482,7483,4266,7484,3679,3366,3680,2818,2781,2782,3367,3589,4554,3065,7485,4071, # 7136
-2899,7486,7487,3157,2462,4072,4555,4073,4985,4986,3111,4267,2687,3368,4556,4074, # 7152
-3791,4268,7488,3909,2783,7489,2656,1962,3158,4557,4987,1963,3159,3160,7490,3112, # 7168
-4988,4989,3022,4990,4991,3792,2855,7491,7492,2971,4558,7493,7494,4992,7495,7496, # 7184
-7497,7498,4993,7499,3426,4559,4994,7500,3681,4560,4269,4270,3910,7501,4075,4995, # 7200
-4271,7502,7503,4076,7504,4996,7505,3225,4997,4272,4077,2819,3023,7506,7507,2733, # 7216
-4561,7508,4562,7509,3369,3793,7510,3590,2508,7511,7512,4273,3113,2994,2616,7513, # 7232
-7514,7515,7516,7517,7518,2820,3911,4078,2748,7519,7520,4563,4998,7521,7522,7523, # 7248
-7524,4999,4274,7525,4564,3682,2239,4079,4565,7526,7527,7528,7529,5000,7530,7531, # 7264
-5001,4275,3794,7532,7533,7534,3066,5002,4566,3161,7535,7536,4080,7537,3162,7538, # 7280
-7539,4567,7540,7541,7542,7543,7544,7545,5003,7546,4568,7547,7548,7549,7550,7551, # 7296
-7552,7553,7554,7555,7556,5004,7557,7558,7559,5005,7560,3795,7561,4569,7562,7563, # 7312
-7564,2821,3796,4276,4277,4081,7565,2876,7566,5006,7567,7568,2900,7569,3797,3912, # 7328
-7570,7571,7572,4278,7573,7574,7575,5007,7576,7577,5008,7578,7579,4279,2934,7580, # 7344
-7581,5009,7582,4570,7583,4280,7584,7585,7586,4571,4572,3913,7587,4573,3505,7588, # 7360
-5010,7589,7590,7591,7592,3798,4574,7593,7594,5011,7595,4281,7596,7597,7598,4282, # 7376
-5012,7599,7600,5013,3163,7601,5014,7602,3914,7603,7604,2734,4575,4576,4577,7605, # 7392
-7606,7607,7608,7609,3506,5015,4578,7610,4082,7611,2822,2901,2579,3683,3024,4579, # 7408
-3507,7612,4580,7613,3226,3799,5016,7614,7615,7616,7617,7618,7619,7620,2995,3290, # 7424
-7621,4083,7622,5017,7623,7624,7625,7626,7627,4581,3915,7628,3291,7629,5018,7630, # 7440
-7631,7632,7633,4084,7634,7635,3427,3800,7636,7637,4582,7638,5019,4583,5020,7639, # 7456
-3916,7640,3801,5021,4584,4283,7641,7642,3428,3591,2269,7643,2617,7644,4585,3592, # 7472
-7645,4586,2902,7646,7647,3227,5022,7648,4587,7649,4284,7650,7651,7652,4588,2284, # 7488
-7653,5023,7654,7655,7656,4589,5024,3802,7657,7658,5025,3508,4590,7659,7660,7661, # 7504
-1969,5026,7662,7663,3684,1821,2688,7664,2028,2509,4285,7665,2823,1841,7666,2689, # 7520
-3114,7667,3917,4085,2160,5027,5028,2972,7668,5029,7669,7670,7671,3593,4086,7672, # 7536
-4591,4087,5030,3803,7673,7674,7675,7676,7677,7678,7679,4286,2366,4592,4593,3067, # 7552
-2328,7680,7681,4594,3594,3918,2029,4287,7682,5031,3919,3370,4288,4595,2856,7683, # 7568
-3509,7684,7685,5032,5033,7686,7687,3804,2784,7688,7689,7690,7691,3371,7692,7693, # 7584
-2877,5034,7694,7695,3920,4289,4088,7696,7697,7698,5035,7699,5036,4290,5037,5038, # 7600
-5039,7700,7701,7702,5040,5041,3228,7703,1760,7704,5042,3229,4596,2106,4089,7705, # 7616
-4597,2824,5043,2107,3372,7706,4291,4090,5044,7707,4091,7708,5045,3025,3805,4598, # 7632
-4292,4293,4294,3373,7709,4599,7710,5046,7711,7712,5047,5048,3806,7713,7714,7715, # 7648
-5049,7716,7717,7718,7719,4600,5050,7720,7721,7722,5051,7723,4295,3429,7724,7725, # 7664
-7726,7727,3921,7728,3292,5052,4092,7729,7730,7731,7732,7733,7734,7735,5053,5054, # 7680
-7736,7737,7738,7739,3922,3685,7740,7741,7742,7743,2635,5055,7744,5056,4601,7745, # 7696
-7746,2560,7747,7748,7749,7750,3923,7751,7752,7753,7754,7755,4296,2903,7756,7757, # 7712
-7758,7759,7760,3924,7761,5057,4297,7762,7763,5058,4298,7764,4093,7765,7766,5059, # 7728
-3925,7767,7768,7769,7770,7771,7772,7773,7774,7775,7776,3595,7777,4299,5060,4094, # 7744
-7778,3293,5061,7779,7780,4300,7781,7782,4602,7783,3596,7784,7785,3430,2367,7786, # 7760
-3164,5062,5063,4301,7787,7788,4095,5064,5065,7789,3374,3115,7790,7791,7792,7793, # 7776
-7794,7795,7796,3597,4603,7797,7798,3686,3116,3807,5066,7799,7800,5067,7801,7802, # 7792
-4604,4302,5068,4303,4096,7803,7804,3294,7805,7806,5069,4605,2690,7807,3026,7808, # 7808
-7809,7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,7824, # 7824
-7825,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,7840, # 7840
-7841,7842,7843,7844,7845,7846,7847,7848,7849,7850,7851,7852,7853,7854,7855,7856, # 7856
-7857,7858,7859,7860,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870,7871,7872, # 7872
-7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886,7887,7888, # 7888
-7889,7890,7891,7892,7893,7894,7895,7896,7897,7898,7899,7900,7901,7902,7903,7904, # 7904
-7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919,7920, # 7920
-7921,7922,7923,7924,3926,7925,7926,7927,7928,7929,7930,7931,7932,7933,7934,7935, # 7936
-7936,7937,7938,7939,7940,7941,7942,7943,7944,7945,7946,7947,7948,7949,7950,7951, # 7952
-7952,7953,7954,7955,7956,7957,7958,7959,7960,7961,7962,7963,7964,7965,7966,7967, # 7968
-7968,7969,7970,7971,7972,7973,7974,7975,7976,7977,7978,7979,7980,7981,7982,7983, # 7984
-7984,7985,7986,7987,7988,7989,7990,7991,7992,7993,7994,7995,7996,7997,7998,7999, # 8000
-8000,8001,8002,8003,8004,8005,8006,8007,8008,8009,8010,8011,8012,8013,8014,8015, # 8016
-8016,8017,8018,8019,8020,8021,8022,8023,8024,8025,8026,8027,8028,8029,8030,8031, # 8032
-8032,8033,8034,8035,8036,8037,8038,8039,8040,8041,8042,8043,8044,8045,8046,8047, # 8048
-8048,8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063, # 8064
-8064,8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079, # 8080
-8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095, # 8096
-8096,8097,8098,8099,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110,8111, # 8112
-8112,8113,8114,8115,8116,8117,8118,8119,8120,8121,8122,8123,8124,8125,8126,8127, # 8128
-8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141,8142,8143, # 8144
-8144,8145,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155,8156,8157,8158,8159, # 8160
-8160,8161,8162,8163,8164,8165,8166,8167,8168,8169,8170,8171,8172,8173,8174,8175, # 8176
-8176,8177,8178,8179,8180,8181,8182,8183,8184,8185,8186,8187,8188,8189,8190,8191, # 8192
-8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207, # 8208
-8208,8209,8210,8211,8212,8213,8214,8215,8216,8217,8218,8219,8220,8221,8222,8223, # 8224
-8224,8225,8226,8227,8228,8229,8230,8231,8232,8233,8234,8235,8236,8237,8238,8239, # 8240
-8240,8241,8242,8243,8244,8245,8246,8247,8248,8249,8250,8251,8252,8253,8254,8255, # 8256
-8256,8257,8258,8259,8260,8261,8262,8263,8264,8265,8266,8267,8268,8269,8270,8271) # 8272
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langbulgarianmodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langbulgarianmodel.py
deleted file mode 100644
index e5788fc..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langbulgarianmodel.py
+++ /dev/null
@@ -1,229 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# 255: Control characters that usually does not exist in any text
-# 254: Carriage/Return
-# 253: symbol (punctuation) that does not belong to word
-# 252: 0 - 9
-
-# Character Mapping Table:
-# this table is modified base on win1251BulgarianCharToOrderMap, so
-# only number <64 is sure valid
-
-Latin5_BulgarianCharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253, 77, 90, 99,100, 72,109,107,101, 79,185, 81,102, 76, 94, 82, # 40
-110,186,108, 91, 74,119, 84, 96,111,187,115,253,253,253,253,253, # 50
-253, 65, 69, 70, 66, 63, 68,112,103, 92,194,104, 95, 86, 87, 71, # 60
-116,195, 85, 93, 97,113,196,197,198,199,200,253,253,253,253,253, # 70
-194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209, # 80
-210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225, # 90
- 81,226,227,228,229,230,105,231,232,233,234,235,236, 45,237,238, # a0
- 31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30, # b0
- 39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61,239, 67,240, 60, 56, # c0
- 1, 18, 9, 20, 11, 3, 23, 15, 2, 26, 12, 10, 14, 6, 4, 13, # d0
- 7, 8, 5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52,241, 42, 16, # e0
- 62,242,243,244, 58,245, 98,246,247,248,249,250,251, 91,252,253, # f0
-)
-
-win1251BulgarianCharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253, 77, 90, 99,100, 72,109,107,101, 79,185, 81,102, 76, 94, 82, # 40
-110,186,108, 91, 74,119, 84, 96,111,187,115,253,253,253,253,253, # 50
-253, 65, 69, 70, 66, 63, 68,112,103, 92,194,104, 95, 86, 87, 71, # 60
-116,195, 85, 93, 97,113,196,197,198,199,200,253,253,253,253,253, # 70
-206,207,208,209,210,211,212,213,120,214,215,216,217,218,219,220, # 80
-221, 78, 64, 83,121, 98,117,105,222,223,224,225,226,227,228,229, # 90
- 88,230,231,232,233,122, 89,106,234,235,236,237,238, 45,239,240, # a0
- 73, 80,118,114,241,242,243,244,245, 62, 58,246,247,248,249,250, # b0
- 31, 32, 35, 43, 37, 44, 55, 47, 40, 59, 33, 46, 38, 36, 41, 30, # c0
- 39, 28, 34, 51, 48, 49, 53, 50, 54, 57, 61,251, 67,252, 60, 56, # d0
- 1, 18, 9, 20, 11, 3, 23, 15, 2, 26, 12, 10, 14, 6, 4, 13, # e0
- 7, 8, 5, 19, 29, 25, 22, 21, 27, 24, 17, 75, 52,253, 42, 16, # f0
-)
-
-# Model Table:
-# total sequences: 100%
-# first 512 sequences: 96.9392%
-# first 1024 sequences:3.0618%
-# rest sequences: 0.2992%
-# negative sequences: 0.0020%
-BulgarianLangModel = (
-0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,3,3,3,3,3,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,2,2,3,2,2,1,2,2,
-3,1,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,0,1,
-0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,3,3,0,3,1,0,
-0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-3,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,2,3,3,3,3,3,3,3,3,0,3,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,2,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,1,3,2,3,3,3,3,3,3,3,3,0,3,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,3,2,3,2,2,1,3,3,3,3,2,2,2,1,1,2,0,1,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,3,3,2,3,2,2,3,3,1,1,2,3,3,2,3,3,3,3,2,1,2,0,2,0,3,0,0,
-0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,3,3,1,3,3,3,3,3,2,3,2,3,3,3,3,3,2,3,3,1,3,0,3,0,2,0,0,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,3,3,3,1,3,3,2,3,3,3,1,3,3,2,3,2,2,2,0,0,2,0,2,0,2,0,0,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,3,3,3,3,0,3,3,3,2,2,3,3,3,1,2,2,3,2,1,1,2,0,2,0,0,0,0,
-1,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,3,3,2,3,3,1,2,3,2,2,2,3,3,3,3,3,2,2,3,1,2,0,2,1,2,0,0,
-0,0,0,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,1,3,3,3,3,3,2,3,3,3,2,3,3,2,3,2,2,2,3,1,2,0,1,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,3,3,3,3,3,3,1,1,1,2,2,1,3,1,3,2,2,3,0,0,1,0,1,0,1,0,0,
-0,0,0,1,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,2,2,3,2,2,3,1,2,1,1,1,2,3,1,3,1,2,2,0,1,1,1,1,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,1,3,2,2,3,3,1,2,3,1,1,3,3,3,3,1,2,2,1,1,1,0,2,0,2,0,1,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,2,2,3,3,3,2,2,1,1,2,0,2,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
-3,0,1,2,1,3,3,2,3,3,3,3,3,2,3,2,1,0,3,1,2,1,2,1,2,3,2,1,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,1,1,2,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,1,3,3,2,3,3,2,2,2,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,3,3,3,3,0,3,3,3,3,3,2,1,1,2,1,3,3,0,3,1,1,1,1,3,2,0,1,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
-3,3,2,2,2,3,3,3,3,3,3,3,3,3,3,3,1,1,3,1,3,3,2,3,2,2,2,3,0,2,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,2,3,3,2,2,3,2,1,1,1,1,1,3,1,3,1,1,0,0,0,1,0,0,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,2,3,2,0,3,2,0,3,0,2,0,0,2,1,3,1,0,0,1,0,0,0,1,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,2,1,1,1,1,2,1,1,2,1,1,1,2,2,1,2,1,1,1,0,1,1,0,1,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,2,1,3,1,1,2,1,3,2,1,1,0,1,2,3,2,1,1,1,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,3,3,3,3,2,2,1,0,1,0,0,1,0,0,0,2,1,0,3,0,0,1,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,2,3,2,3,3,1,3,2,1,1,1,2,1,1,2,1,3,0,1,0,0,0,1,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,1,1,2,2,3,3,2,3,2,2,2,3,1,2,2,1,1,2,1,1,2,2,0,1,1,0,1,0,2,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,2,1,3,1,0,2,2,1,3,2,1,0,0,2,0,2,0,1,0,0,0,0,0,0,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,3,1,2,0,2,3,1,2,3,2,0,1,3,1,2,1,1,1,0,0,1,0,0,2,2,2,3,
-2,2,2,2,1,2,1,1,2,2,1,1,2,0,1,1,1,0,0,1,1,0,0,1,1,0,0,0,1,1,0,1,
-3,3,3,3,3,2,1,2,2,1,2,0,2,0,1,0,1,2,1,2,1,1,0,0,0,1,0,1,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,
-3,3,2,3,3,1,1,3,1,0,3,2,1,0,0,0,1,2,0,2,0,1,0,0,0,1,0,1,2,1,2,2,
-1,1,1,1,1,1,1,2,2,2,1,1,1,1,1,1,1,0,1,2,1,1,1,0,0,0,0,0,1,1,0,0,
-3,1,0,1,0,2,3,2,2,2,3,2,2,2,2,2,1,0,2,1,2,1,1,1,0,1,2,1,2,2,2,1,
-1,1,2,2,2,2,1,2,1,1,0,1,2,1,2,2,2,1,1,1,0,1,1,1,1,2,0,1,0,0,0,0,
-2,3,2,3,3,0,0,2,1,0,2,1,0,0,0,0,2,3,0,2,0,0,0,0,0,1,0,0,2,0,1,2,
-2,1,2,1,2,2,1,1,1,2,1,1,1,0,1,2,2,1,1,1,1,1,0,1,1,1,0,0,1,2,0,0,
-3,3,2,2,3,0,2,3,1,1,2,0,0,0,1,0,0,2,0,2,0,0,0,1,0,1,0,1,2,0,2,2,
-1,1,1,1,2,1,0,1,2,2,2,1,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,0,1,1,0,0,
-2,3,2,3,3,0,0,3,0,1,1,0,1,0,0,0,2,2,1,2,0,0,0,0,0,0,0,0,2,0,1,2,
-2,2,1,1,1,1,1,2,2,2,1,0,2,0,1,0,1,0,0,1,0,1,0,0,1,0,0,0,0,1,0,0,
-3,3,3,3,2,2,2,2,2,0,2,1,1,1,1,2,1,2,1,1,0,2,0,1,0,1,0,0,2,0,1,2,
-1,1,1,1,1,1,1,2,2,1,1,0,2,0,1,0,2,0,0,1,1,1,0,0,2,0,0,0,1,1,0,0,
-2,3,3,3,3,1,0,0,0,0,0,0,0,0,0,0,2,0,0,1,1,0,0,0,0,0,0,1,2,0,1,2,
-2,2,2,1,1,2,1,1,2,2,2,1,2,0,1,1,1,1,1,1,0,1,1,1,1,0,0,1,1,1,0,0,
-2,3,3,3,3,0,2,2,0,2,1,0,0,0,1,1,1,2,0,2,0,0,0,3,0,0,0,0,2,0,2,2,
-1,1,1,2,1,2,1,1,2,2,2,1,2,0,1,1,1,0,1,1,1,1,0,2,1,0,0,0,1,1,0,0,
-2,3,3,3,3,0,2,1,0,0,2,0,0,0,0,0,1,2,0,2,0,0,0,0,0,0,0,0,2,0,1,2,
-1,1,1,2,1,1,1,1,2,2,2,0,1,0,1,1,1,0,0,1,1,1,0,0,1,0,0,0,0,1,0,0,
-3,3,2,2,3,0,1,0,1,0,0,0,0,0,0,0,1,1,0,3,0,0,0,0,0,0,0,0,1,0,2,2,
-1,1,1,1,1,2,1,1,2,2,1,2,2,1,0,1,1,1,1,1,0,1,0,0,1,0,0,0,1,1,0,0,
-3,1,0,1,0,2,2,2,2,3,2,1,1,1,2,3,0,0,1,0,2,1,1,0,1,1,1,1,2,1,1,1,
-1,2,2,1,2,1,2,2,1,1,0,1,2,1,2,2,1,1,1,0,0,1,1,1,2,1,0,1,0,0,0,0,
-2,1,0,1,0,3,1,2,2,2,2,1,2,2,1,1,1,0,2,1,2,2,1,1,2,1,1,0,2,1,1,1,
-1,2,2,2,2,2,2,2,1,2,0,1,1,0,2,1,1,1,1,1,0,0,1,1,1,1,0,1,0,0,0,0,
-2,1,1,1,1,2,2,2,2,1,2,2,2,1,2,2,1,1,2,1,2,3,2,2,1,1,1,1,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,2,2,3,2,0,1,2,0,1,2,1,1,0,1,0,1,2,1,2,0,0,0,1,1,0,0,0,1,0,0,2,
-1,1,0,0,1,1,0,1,1,1,1,0,2,0,1,1,1,0,0,1,1,0,0,0,0,1,0,0,0,1,0,0,
-2,0,0,0,0,1,2,2,2,2,2,2,2,1,2,1,1,1,1,1,1,1,0,1,1,1,1,1,2,1,1,1,
-1,2,2,2,2,1,1,2,1,2,1,1,1,0,2,1,2,1,1,1,0,2,1,1,1,1,0,1,0,0,0,0,
-3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,
-1,1,0,1,0,1,1,1,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,2,2,3,2,0,0,0,0,1,0,0,0,0,0,0,1,1,0,2,0,0,0,0,0,0,0,0,1,0,1,2,
-1,1,1,1,1,1,0,0,2,2,2,2,2,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0,1,1,0,1,
-2,3,1,2,1,0,1,1,0,2,2,2,0,0,1,0,0,1,1,1,1,0,0,0,0,0,0,0,1,0,1,2,
-1,1,1,1,2,1,1,1,1,1,1,1,1,0,1,1,0,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0,
-2,2,2,2,2,0,0,2,0,0,2,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,2,0,2,2,
-1,1,1,1,1,0,0,1,2,1,1,0,1,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
-1,2,2,2,2,0,0,2,0,1,1,0,0,0,1,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,1,1,
-0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
-1,2,2,3,2,0,0,1,0,0,1,0,0,0,0,0,0,1,0,2,0,0,0,1,0,0,0,0,0,0,0,2,
-1,1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
-2,1,2,2,2,1,2,1,2,2,1,1,2,1,1,1,0,1,1,1,1,2,0,1,0,1,1,1,1,0,1,1,
-1,1,2,1,1,1,1,1,1,0,0,1,2,1,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,
-1,0,0,1,3,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,2,2,2,1,0,0,1,0,2,0,0,0,0,0,1,1,1,0,1,0,0,0,0,0,0,0,0,2,0,0,1,
-0,2,0,1,0,0,1,1,2,0,1,0,1,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
-1,2,2,2,2,0,1,1,0,2,1,0,1,1,1,0,0,1,0,2,0,1,0,0,0,0,0,0,0,0,0,1,
-0,1,0,0,1,0,0,0,1,1,0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
-2,2,2,2,2,0,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,
-0,1,0,1,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
-2,0,1,0,0,1,2,1,1,1,1,1,1,2,2,1,0,0,1,0,1,0,0,0,0,1,1,1,1,0,0,0,
-1,1,2,1,1,1,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,2,1,2,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,
-0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,0,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,
-0,1,1,0,1,1,1,0,0,1,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,
-1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,2,0,0,2,0,1,0,0,1,0,0,1,
-1,1,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,
-1,1,1,1,1,1,1,2,0,0,0,0,0,0,2,1,0,1,1,0,0,1,1,1,0,1,0,0,0,0,0,0,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,1,1,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-)
-
-Latin5BulgarianModel = {
- 'charToOrderMap': Latin5_BulgarianCharToOrderMap,
- 'precedenceMatrix': BulgarianLangModel,
- 'mTypicalPositiveRatio': 0.969392,
- 'keepEnglishLetter': False,
- 'charsetName': "ISO-8859-5"
-}
-
-Win1251BulgarianModel = {
- 'charToOrderMap': win1251BulgarianCharToOrderMap,
- 'precedenceMatrix': BulgarianLangModel,
- 'mTypicalPositiveRatio': 0.969392,
- 'keepEnglishLetter': False,
- 'charsetName': "windows-1251"
-}
-
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langcyrillicmodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langcyrillicmodel.py
deleted file mode 100644
index a86f54b..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langcyrillicmodel.py
+++ /dev/null
@@ -1,329 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# KOI8-R language model
-# Character Mapping Table:
-KOI8R_CharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
-155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
-253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
- 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
-191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206, # 80
-207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222, # 90
-223,224,225, 68,226,227,228,229,230,231,232,233,234,235,236,237, # a0
-238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253, # b0
- 27, 3, 21, 28, 13, 2, 39, 19, 26, 4, 23, 11, 8, 12, 5, 1, # c0
- 15, 16, 9, 7, 6, 14, 24, 10, 17, 18, 20, 25, 30, 29, 22, 54, # d0
- 59, 37, 44, 58, 41, 48, 53, 46, 55, 42, 60, 36, 49, 38, 31, 34, # e0
- 35, 43, 45, 32, 40, 52, 56, 33, 61, 62, 51, 57, 47, 63, 50, 70, # f0
-)
-
-win1251_CharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
-155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
-253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
- 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
-191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
-207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
-223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
-239,240,241,242,243,244,245,246, 68,247,248,249,250,251,252,253,
- 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
- 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
- 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
- 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16,
-)
-
-latin5_CharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
-155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
-253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
- 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
-191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
-207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
-223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
- 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
- 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
- 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
- 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16,
-239, 68,240,241,242,243,244,245,246,247,248,249,250,251,252,255,
-)
-
-macCyrillic_CharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
-155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
-253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
- 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
- 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
- 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
-191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
-207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
-223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
-239,240,241,242,243,244,245,246,247,248,249,250,251,252, 68, 16,
- 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
- 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27,255,
-)
-
-IBM855_CharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
-155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
-253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
- 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
-191,192,193,194, 68,195,196,197,198,199,200,201,202,203,204,205,
-206,207,208,209,210,211,212,213,214,215,216,217, 27, 59, 54, 70,
- 3, 37, 21, 44, 28, 58, 13, 41, 2, 48, 39, 53, 19, 46,218,219,
-220,221,222,223,224, 26, 55, 4, 42,225,226,227,228, 23, 60,229,
-230,231,232,233,234,235, 11, 36,236,237,238,239,240,241,242,243,
- 8, 49, 12, 38, 5, 31, 1, 34, 15,244,245,246,247, 35, 16,248,
- 43, 9, 45, 7, 32, 6, 40, 14, 52, 24, 56, 10, 33, 17, 61,249,
-250, 18, 62, 20, 51, 25, 57, 30, 47, 29, 63, 22, 50,251,252,255,
-)
-
-IBM866_CharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253,142,143,144,145,146,147,148,149,150,151,152, 74,153, 75,154, # 40
-155,156,157,158,159,160,161,162,163,164,165,253,253,253,253,253, # 50
-253, 71,172, 66,173, 65,174, 76,175, 64,176,177, 77, 72,178, 69, # 60
- 67,179, 78, 73,180,181, 79,182,183,184,185,253,253,253,253,253, # 70
- 37, 44, 33, 46, 41, 48, 56, 51, 42, 60, 36, 49, 38, 31, 34, 35,
- 45, 32, 40, 52, 53, 55, 58, 50, 57, 63, 70, 62, 61, 47, 59, 43,
- 3, 21, 10, 19, 13, 2, 24, 20, 4, 23, 11, 8, 12, 5, 1, 15,
-191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,
-207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,
-223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,
- 9, 7, 6, 14, 39, 26, 28, 22, 25, 29, 54, 18, 17, 30, 27, 16,
-239, 68,240,241,242,243,244,245,246,247,248,249,250,251,252,255,
-)
-
-# Model Table:
-# total sequences: 100%
-# first 512 sequences: 97.6601%
-# first 1024 sequences: 2.3389%
-# rest sequences: 0.1237%
-# negative sequences: 0.0009%
-RussianLangModel = (
-0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3,3,1,3,3,3,2,3,2,3,3,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,0,3,2,2,2,2,2,0,0,2,
-3,3,3,2,3,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,3,2,3,2,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,2,2,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,2,3,3,1,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,2,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,0,0,3,3,3,3,3,3,3,3,3,3,3,2,1,
-0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,0,0,3,3,3,3,3,3,3,3,3,3,3,2,1,
-0,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,2,2,2,3,1,3,3,1,3,3,3,3,2,2,3,0,2,2,2,3,3,2,1,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,2,3,3,3,3,3,2,2,3,2,3,3,3,2,1,2,2,0,1,2,2,2,2,2,2,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,3,0,2,2,3,3,2,1,2,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,2,3,3,1,2,3,2,2,3,2,3,3,3,3,2,2,3,0,3,2,2,3,1,1,1,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,2,3,3,3,3,2,2,2,0,3,3,3,2,2,2,2,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,2,3,2,2,0,1,3,2,1,2,2,1,0,
-0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,3,2,1,1,3,0,1,1,1,1,2,1,1,0,2,2,2,1,2,0,1,0,
-0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,2,3,3,2,2,2,2,1,3,2,3,2,3,2,1,2,2,0,1,1,2,1,2,1,2,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,2,3,3,3,2,2,2,2,0,2,2,2,2,3,1,1,0,
-0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
-3,2,3,2,2,3,3,3,3,3,3,3,3,3,1,3,2,0,0,3,3,3,3,2,3,3,3,3,2,3,2,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,3,3,3,3,3,2,2,3,3,0,2,1,0,3,2,3,2,3,0,0,1,2,0,0,1,0,1,2,1,1,0,
-0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,3,0,2,3,3,3,3,2,3,3,3,3,1,2,2,0,0,2,3,2,2,2,3,2,3,2,2,3,0,0,
-0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,2,3,0,2,3,2,3,0,1,2,3,3,2,0,2,3,0,0,2,3,2,2,0,1,3,1,3,2,2,1,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,1,3,0,2,3,3,3,3,3,3,3,3,2,1,3,2,0,0,2,2,3,3,3,2,3,3,0,2,2,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,2,2,3,3,2,2,2,3,3,0,0,1,1,1,1,1,2,0,0,1,1,1,1,0,1,0,
-0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,2,2,3,3,3,3,3,3,3,0,3,2,3,3,2,3,2,0,2,1,0,1,1,0,1,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,2,3,3,3,2,2,2,2,3,1,3,2,3,1,1,2,1,0,2,2,2,2,1,3,1,0,
-0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
-2,2,3,3,3,3,3,1,2,2,1,3,1,0,3,0,0,3,0,0,0,1,1,0,1,2,1,0,0,0,0,0,
-0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,2,2,1,1,3,3,3,2,2,1,2,2,3,1,1,2,0,0,2,2,1,3,0,0,2,1,1,2,1,1,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,2,3,3,3,3,1,2,2,2,1,2,1,3,3,1,1,2,1,2,1,2,2,0,2,0,0,1,1,0,1,0,
-0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,3,3,3,3,3,2,1,3,2,2,3,2,0,3,2,0,3,0,1,0,1,1,0,0,1,1,1,1,0,1,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,2,3,3,3,2,2,2,3,3,1,2,1,2,1,0,1,0,1,1,0,1,0,0,2,1,1,1,0,1,0,
-0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
-3,1,1,2,1,2,3,3,2,2,1,2,2,3,0,2,1,0,0,2,2,3,2,1,2,2,2,2,2,3,1,0,
-0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,1,1,0,1,1,2,2,1,1,3,0,0,1,3,1,1,1,0,0,0,1,0,1,1,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,1,3,3,3,2,0,0,0,2,1,0,1,0,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,0,1,0,0,2,3,2,2,2,1,2,2,2,1,2,1,0,0,1,1,1,0,2,0,1,1,1,0,0,1,1,
-1,0,0,0,0,0,1,2,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,
-2,3,3,3,3,0,0,0,0,1,0,0,0,0,3,0,1,2,1,0,0,0,0,0,0,0,1,1,0,0,1,1,
-1,0,1,0,1,2,0,0,1,1,2,1,0,1,1,1,1,0,1,1,1,1,0,1,0,0,1,0,0,1,1,0,
-2,2,3,2,2,2,3,1,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,0,1,0,1,1,1,0,2,1,
-1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,0,1,1,1,0,1,1,0,
-3,3,3,2,2,2,2,3,2,2,1,1,2,2,2,2,1,1,3,1,2,1,2,0,0,1,1,0,1,0,2,1,
-1,1,1,1,1,2,1,0,1,1,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,0,0,0,1,1,0,
-2,0,0,1,0,3,2,2,2,2,1,2,1,2,1,2,0,0,0,2,1,2,2,1,1,2,2,0,1,1,0,2,
-1,1,1,1,1,0,1,1,1,2,1,1,1,2,1,0,1,2,1,1,1,1,0,1,1,1,0,0,1,0,0,1,
-1,3,2,2,2,1,1,1,2,3,0,0,0,0,2,0,2,2,1,0,0,0,0,0,0,1,0,0,0,0,1,1,
-1,0,1,1,0,1,0,1,1,0,1,1,0,2,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,
-2,3,2,3,2,1,2,2,2,2,1,0,0,0,2,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,2,1,
-1,1,2,1,0,2,0,0,1,0,1,0,0,1,0,0,1,1,0,1,1,0,0,0,0,0,1,0,0,0,0,0,
-3,0,0,1,0,2,2,2,3,2,2,2,2,2,2,2,0,0,0,2,1,2,1,1,1,2,2,0,0,0,1,2,
-1,1,1,1,1,0,1,2,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0,0,1,
-2,3,2,3,3,2,0,1,1,1,0,0,1,0,2,0,1,1,3,1,0,0,0,0,0,0,0,1,0,0,2,1,
-1,1,1,1,1,1,1,0,1,0,1,1,1,1,0,1,1,1,0,0,1,1,0,1,0,0,0,0,0,0,1,0,
-2,3,3,3,3,1,2,2,2,2,0,1,1,0,2,1,1,1,2,1,0,1,1,0,0,1,0,1,0,0,2,0,
-0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,3,3,3,2,0,0,1,1,2,2,1,0,0,2,0,1,1,3,0,0,1,0,0,0,0,0,1,0,1,2,1,
-1,1,2,0,1,1,1,0,1,0,1,1,0,1,0,1,1,1,1,0,1,0,0,0,0,0,0,1,0,1,1,0,
-1,3,2,3,2,1,0,0,2,2,2,0,1,0,2,0,1,1,1,0,1,0,0,0,3,0,1,1,0,0,2,1,
-1,1,1,0,1,1,0,0,0,0,1,1,0,1,0,0,2,1,1,0,1,0,0,0,1,0,1,0,0,1,1,0,
-3,1,2,1,1,2,2,2,2,2,2,1,2,2,1,1,0,0,0,2,2,2,0,0,0,1,2,1,0,1,0,1,
-2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,2,1,1,1,0,1,0,1,1,0,1,1,1,0,0,1,
-3,0,0,0,0,2,0,1,1,1,1,1,1,1,0,1,0,0,0,1,1,1,0,1,0,1,1,0,0,1,0,1,
-1,1,0,0,1,0,0,0,1,0,1,1,0,0,1,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,1,
-1,3,3,2,2,0,0,0,2,2,0,0,0,1,2,0,1,1,2,0,0,0,0,0,0,0,0,1,0,0,2,1,
-0,1,1,0,0,1,1,0,0,0,1,1,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,
-2,3,2,3,2,0,0,0,0,1,1,0,0,0,2,0,2,0,2,0,0,0,0,0,1,0,0,1,0,0,1,1,
-1,1,2,0,1,2,1,0,1,1,2,1,1,1,1,1,2,1,1,0,1,0,0,1,1,1,1,1,0,1,1,0,
-1,3,2,2,2,1,0,0,2,2,1,0,1,2,2,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,
-0,0,1,1,0,1,1,0,0,1,1,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
-1,0,0,1,0,2,3,1,2,2,2,2,2,2,1,1,0,0,0,1,0,1,0,2,1,1,1,0,0,0,0,1,
-1,1,0,1,1,0,1,1,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,
-2,0,2,0,0,1,0,3,2,1,2,1,2,2,0,1,0,0,0,2,1,0,0,2,1,1,1,1,0,2,0,2,
-2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,0,1,1,1,1,0,0,0,1,1,1,1,0,1,0,0,1,
-1,2,2,2,2,1,0,0,1,0,0,0,0,0,2,0,1,1,1,1,0,0,0,0,1,0,1,2,0,0,2,0,
-1,0,1,1,1,2,1,0,1,0,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,0,1,0,1,1,0,
-2,1,2,2,2,0,3,0,1,1,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-0,0,0,1,1,1,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,
-1,2,2,3,2,2,0,0,1,1,2,0,1,2,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,
-0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,
-2,2,1,1,2,1,2,2,2,2,2,1,2,2,0,1,0,0,0,1,2,2,2,1,2,1,1,1,1,1,2,1,
-1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,0,1,
-1,2,2,2,2,0,1,0,2,2,0,0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,
-0,0,1,0,0,1,0,0,0,0,1,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
-0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,2,2,2,2,0,0,0,2,2,2,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,
-0,1,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,2,2,2,2,0,0,0,0,1,0,0,1,1,2,0,0,0,0,1,0,1,0,0,1,0,0,2,0,0,0,1,
-0,0,1,0,0,1,0,0,0,1,1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,
-1,2,2,2,1,1,2,0,2,1,1,1,1,0,2,2,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,
-0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
-1,0,2,1,2,0,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,
-0,0,1,0,1,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,
-1,0,0,0,0,2,0,1,2,1,0,1,1,1,0,1,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,1,
-0,0,0,0,0,1,0,0,1,1,0,0,1,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,
-2,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-1,1,1,0,1,0,1,0,0,1,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,
-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-1,1,0,1,1,0,1,0,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,1,0,1,1,0,1,0,0,0,
-0,1,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,
-)
-
-Koi8rModel = {
- 'charToOrderMap': KOI8R_CharToOrderMap,
- 'precedenceMatrix': RussianLangModel,
- 'mTypicalPositiveRatio': 0.976601,
- 'keepEnglishLetter': False,
- 'charsetName': "KOI8-R"
-}
-
-Win1251CyrillicModel = {
- 'charToOrderMap': win1251_CharToOrderMap,
- 'precedenceMatrix': RussianLangModel,
- 'mTypicalPositiveRatio': 0.976601,
- 'keepEnglishLetter': False,
- 'charsetName': "windows-1251"
-}
-
-Latin5CyrillicModel = {
- 'charToOrderMap': latin5_CharToOrderMap,
- 'precedenceMatrix': RussianLangModel,
- 'mTypicalPositiveRatio': 0.976601,
- 'keepEnglishLetter': False,
- 'charsetName': "ISO-8859-5"
-}
-
-MacCyrillicModel = {
- 'charToOrderMap': macCyrillic_CharToOrderMap,
- 'precedenceMatrix': RussianLangModel,
- 'mTypicalPositiveRatio': 0.976601,
- 'keepEnglishLetter': False,
- 'charsetName': "MacCyrillic"
-};
-
-Ibm866Model = {
- 'charToOrderMap': IBM866_CharToOrderMap,
- 'precedenceMatrix': RussianLangModel,
- 'mTypicalPositiveRatio': 0.976601,
- 'keepEnglishLetter': False,
- 'charsetName': "IBM866"
-}
-
-Ibm855Model = {
- 'charToOrderMap': IBM855_CharToOrderMap,
- 'precedenceMatrix': RussianLangModel,
- 'mTypicalPositiveRatio': 0.976601,
- 'keepEnglishLetter': False,
- 'charsetName': "IBM855"
-}
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langgreekmodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langgreekmodel.py
deleted file mode 100644
index ddb5837..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langgreekmodel.py
+++ /dev/null
@@ -1,225 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# 255: Control characters that usually does not exist in any text
-# 254: Carriage/Return
-# 253: symbol (punctuation) that does not belong to word
-# 252: 0 - 9
-
-# Character Mapping Table:
-Latin7_CharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253, 82,100,104, 94, 98,101,116,102,111,187,117, 92, 88,113, 85, # 40
- 79,118,105, 83, 67,114,119, 95, 99,109,188,253,253,253,253,253, # 50
-253, 72, 70, 80, 81, 60, 96, 93, 89, 68,120, 97, 77, 86, 69, 55, # 60
- 78,115, 65, 66, 58, 76,106,103, 87,107,112,253,253,253,253,253, # 70
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 80
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 90
-253,233, 90,253,253,253,253,253,253,253,253,253,253, 74,253,253, # a0
-253,253,253,253,247,248, 61, 36, 46, 71, 73,253, 54,253,108,123, # b0
-110, 31, 51, 43, 41, 34, 91, 40, 52, 47, 44, 53, 38, 49, 59, 39, # c0
- 35, 48,250, 37, 33, 45, 56, 50, 84, 57,120,121, 17, 18, 22, 15, # d0
-124, 1, 29, 20, 21, 3, 32, 13, 25, 5, 11, 16, 10, 6, 30, 4, # e0
- 9, 8, 14, 7, 2, 12, 28, 23, 42, 24, 64, 75, 19, 26, 27,253, # f0
-)
-
-win1253_CharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253, 82,100,104, 94, 98,101,116,102,111,187,117, 92, 88,113, 85, # 40
- 79,118,105, 83, 67,114,119, 95, 99,109,188,253,253,253,253,253, # 50
-253, 72, 70, 80, 81, 60, 96, 93, 89, 68,120, 97, 77, 86, 69, 55, # 60
- 78,115, 65, 66, 58, 76,106,103, 87,107,112,253,253,253,253,253, # 70
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 80
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 90
-253,233, 61,253,253,253,253,253,253,253,253,253,253, 74,253,253, # a0
-253,253,253,253,247,253,253, 36, 46, 71, 73,253, 54,253,108,123, # b0
-110, 31, 51, 43, 41, 34, 91, 40, 52, 47, 44, 53, 38, 49, 59, 39, # c0
- 35, 48,250, 37, 33, 45, 56, 50, 84, 57,120,121, 17, 18, 22, 15, # d0
-124, 1, 29, 20, 21, 3, 32, 13, 25, 5, 11, 16, 10, 6, 30, 4, # e0
- 9, 8, 14, 7, 2, 12, 28, 23, 42, 24, 64, 75, 19, 26, 27,253, # f0
-)
-
-# Model Table:
-# total sequences: 100%
-# first 512 sequences: 98.2851%
-# first 1024 sequences:1.7001%
-# rest sequences: 0.0359%
-# negative sequences: 0.0148%
-GreekLangModel = (
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,3,2,2,3,3,3,3,3,3,3,3,1,3,3,3,0,2,2,3,3,0,3,0,3,2,0,3,3,3,0,
-3,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,3,0,3,3,0,3,2,3,3,0,3,2,3,3,3,0,0,3,0,3,0,3,3,2,0,0,0,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,
-0,2,3,2,2,3,3,3,3,3,3,3,3,0,3,3,3,3,0,2,3,3,0,3,3,3,3,2,3,3,3,0,
-2,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,2,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,0,2,1,3,3,3,3,2,3,3,2,3,3,2,0,
-0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,0,3,3,3,3,3,3,0,3,3,0,3,3,3,3,3,3,3,3,3,3,0,3,2,3,3,0,
-2,0,1,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
-0,3,3,3,3,3,2,3,0,0,0,0,3,3,0,3,1,3,3,3,0,3,3,0,3,3,3,3,0,0,0,0,
-2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,3,0,3,0,3,3,3,3,3,0,3,2,2,2,3,0,2,3,3,3,3,3,2,3,3,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,3,3,2,2,2,3,3,3,3,0,3,1,3,3,3,3,2,3,3,3,3,3,3,3,2,2,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,3,2,0,3,0,0,0,3,3,2,3,3,3,3,3,0,0,3,2,3,0,2,3,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,0,3,3,3,3,0,0,3,3,0,2,3,0,3,0,3,3,3,0,0,3,0,3,0,2,2,3,3,0,0,
-0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,3,2,0,3,2,3,3,3,3,0,3,3,3,3,3,0,3,3,2,3,2,3,3,2,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,2,3,2,3,3,3,3,3,3,0,2,3,2,3,2,2,2,3,2,3,3,2,3,0,2,2,2,3,0,
-2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,3,0,0,0,3,3,3,2,3,3,0,0,3,0,3,0,0,0,3,2,0,3,0,3,0,0,2,0,2,0,
-0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,0,3,3,3,3,3,3,0,3,3,0,3,0,0,0,3,3,0,3,3,3,0,0,1,2,3,0,
-3,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,3,2,0,0,3,2,2,3,3,0,3,3,3,3,3,2,1,3,0,3,2,3,3,2,1,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,3,3,0,2,3,3,3,3,3,3,0,0,3,0,3,0,0,0,3,3,0,3,2,3,0,0,3,3,3,0,
-3,0,0,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,0,3,3,3,3,3,3,0,0,3,0,3,0,0,0,3,2,0,3,2,3,0,0,3,2,3,0,
-2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,3,1,2,2,3,3,3,3,3,3,0,2,3,0,3,0,0,0,3,3,0,3,0,2,0,0,2,3,1,0,
-2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,0,3,3,3,3,0,3,0,3,3,2,3,0,3,3,3,3,3,3,0,3,3,3,0,2,3,0,0,3,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,0,3,3,3,0,0,3,0,0,0,3,3,0,3,0,2,3,3,0,0,3,0,3,0,3,3,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,3,0,0,0,3,3,3,3,3,3,0,0,3,0,2,0,0,0,3,3,0,3,0,3,0,0,2,0,2,0,
-0,0,0,0,1,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,3,3,0,3,0,2,0,3,2,0,3,2,3,2,3,0,0,3,2,3,2,3,3,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,3,0,0,2,3,3,3,3,3,0,0,0,3,0,2,1,0,0,3,2,2,2,0,3,0,0,2,2,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,0,3,3,3,2,0,3,0,3,0,3,3,0,2,1,2,3,3,0,0,3,0,3,0,3,3,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,2,3,3,3,0,3,3,3,3,3,3,0,2,3,0,3,0,0,0,2,1,0,2,2,3,0,0,2,2,2,0,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,3,0,0,2,3,3,3,2,3,0,0,1,3,0,2,0,0,0,0,3,0,1,0,2,0,0,1,1,1,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,3,1,0,3,0,0,0,3,2,0,3,2,3,3,3,0,0,3,0,3,2,2,2,1,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,0,3,3,3,0,0,3,0,0,0,0,2,0,2,3,3,2,2,2,2,3,0,2,0,2,2,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,3,3,3,2,0,0,0,0,0,0,2,3,0,2,0,2,3,2,0,0,3,0,3,0,3,1,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,3,2,3,3,2,2,3,0,2,0,3,0,0,0,2,0,0,0,0,1,2,0,2,0,2,0,
-0,2,0,2,0,2,2,0,0,1,0,2,2,2,0,2,2,2,0,2,2,2,0,0,2,0,0,1,0,0,0,0,
-0,2,0,3,3,2,0,0,0,0,0,0,1,3,0,2,0,2,2,2,0,0,2,0,3,0,0,2,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,0,2,3,2,0,2,2,0,2,0,2,2,0,2,0,2,2,2,0,0,0,0,0,0,2,3,0,0,0,2,
-0,1,2,0,0,0,0,2,2,0,0,0,2,1,0,2,2,0,0,0,0,0,0,1,0,2,0,0,0,0,0,0,
-0,0,2,1,0,2,3,2,2,3,2,3,2,0,0,3,3,3,0,0,3,2,0,0,0,1,1,0,2,0,2,2,
-0,2,0,2,0,2,2,0,0,2,0,2,2,2,0,2,2,2,2,0,0,2,0,0,0,2,0,1,0,0,0,0,
-0,3,0,3,3,2,2,0,3,0,0,0,2,2,0,2,2,2,1,2,0,0,1,2,2,0,0,3,0,0,0,2,
-0,1,2,0,0,0,1,2,0,0,0,0,0,0,0,2,2,0,1,0,0,2,0,0,0,2,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,2,3,3,2,2,0,0,0,2,0,2,3,3,0,2,0,0,0,0,0,0,2,2,2,0,2,2,0,2,0,2,
-0,2,2,0,0,2,2,2,2,1,0,0,2,2,0,2,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,
-0,2,0,3,2,3,0,0,0,3,0,0,2,2,0,2,0,2,2,2,0,0,2,0,0,0,0,0,0,0,0,2,
-0,0,2,2,0,0,2,2,2,0,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,2,0,0,3,2,0,2,2,2,2,2,0,0,0,2,0,0,0,0,2,0,1,0,0,2,0,1,0,0,0,
-0,2,2,2,0,2,2,0,1,2,0,2,2,2,0,2,2,2,2,1,2,2,0,0,2,0,0,0,0,0,0,0,
-0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
-0,2,0,2,0,2,2,0,0,0,0,1,2,1,0,0,2,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,3,2,3,0,0,2,0,0,0,2,2,0,2,0,0,0,1,0,0,2,0,2,0,2,2,0,0,0,0,
-0,0,2,0,0,0,0,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,
-0,2,2,3,2,2,0,0,0,0,0,0,1,3,0,2,0,2,2,0,0,0,1,0,2,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,2,0,2,0,3,2,0,2,0,0,0,0,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-0,0,2,0,0,0,0,1,1,0,0,2,1,2,0,2,2,0,1,0,0,1,0,0,0,2,0,0,0,0,0,0,
-0,3,0,2,2,2,0,0,2,0,0,0,2,0,0,0,2,3,0,2,0,0,0,0,0,0,2,2,0,0,0,2,
-0,1,2,0,0,0,1,2,2,1,0,0,0,2,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,2,1,2,0,2,2,0,2,0,0,2,0,0,0,0,1,2,1,0,2,1,0,0,0,0,0,0,0,0,0,0,
-0,0,2,0,0,0,3,1,2,2,0,2,0,0,0,0,2,0,0,0,2,0,0,3,0,0,0,0,2,2,2,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,2,1,0,2,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,0,0,2,
-0,2,2,0,0,2,2,2,2,2,0,1,2,0,0,0,2,2,0,1,0,2,0,0,2,2,0,0,0,0,0,0,
-0,0,0,0,1,0,0,0,0,0,0,0,3,0,0,2,0,0,0,0,0,0,0,0,2,0,2,0,0,0,0,2,
-0,1,2,0,0,0,0,2,2,1,0,1,0,1,0,2,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,
-0,2,0,1,2,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,0,0,0,0,1,0,0,0,0,0,0,2,
-0,2,2,0,0,0,0,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0,0,
-0,2,2,2,2,0,0,0,3,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,1,
-0,0,2,0,0,0,0,1,2,0,0,0,0,0,0,2,2,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,
-0,2,0,2,2,2,0,0,2,0,0,0,0,0,0,0,2,2,2,0,0,0,2,0,0,0,0,0,0,0,0,2,
-0,0,1,0,0,0,0,2,1,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,
-0,3,0,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,2,
-0,0,2,0,0,0,0,2,2,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,2,0,2,2,1,0,0,0,0,0,0,2,0,0,2,0,2,2,2,0,0,0,0,0,0,2,0,0,0,0,2,
-0,0,2,0,0,2,0,2,2,0,0,0,0,2,0,2,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,
-0,0,3,0,0,0,2,2,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,0,0,0,0,0,
-0,2,2,2,2,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,
-0,0,0,0,0,0,0,2,1,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,2,2,0,0,0,0,0,2,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
-0,2,0,0,0,2,0,0,0,0,0,1,0,0,0,0,2,2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,2,0,0,0,
-0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,2,0,2,0,0,0,
-0,0,0,0,0,0,0,0,2,1,0,0,0,0,0,0,2,0,0,0,1,2,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-)
-
-Latin7GreekModel = {
- 'charToOrderMap': Latin7_CharToOrderMap,
- 'precedenceMatrix': GreekLangModel,
- 'mTypicalPositiveRatio': 0.982851,
- 'keepEnglishLetter': False,
- 'charsetName': "ISO-8859-7"
-}
-
-Win1253GreekModel = {
- 'charToOrderMap': win1253_CharToOrderMap,
- 'precedenceMatrix': GreekLangModel,
- 'mTypicalPositiveRatio': 0.982851,
- 'keepEnglishLetter': False,
- 'charsetName': "windows-1253"
-}
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langhebrewmodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langhebrewmodel.py
deleted file mode 100644
index 75f2bc7..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langhebrewmodel.py
+++ /dev/null
@@ -1,201 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Universal charset detector code.
-#
-# The Initial Developer of the Original Code is
-# Simon Montagu
-# Portions created by the Initial Developer are Copyright (C) 2005
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-# Shy Shalom - original C code
-# Shoshannah Forbes - original C code (?)
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# 255: Control characters that usually does not exist in any text
-# 254: Carriage/Return
-# 253: symbol (punctuation) that does not belong to word
-# 252: 0 - 9
-
-# Windows-1255 language model
-# Character Mapping Table:
-win1255_CharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253, 69, 91, 79, 80, 92, 89, 97, 90, 68,111,112, 82, 73, 95, 85, # 40
- 78,121, 86, 71, 67,102,107, 84,114,103,115,253,253,253,253,253, # 50
-253, 50, 74, 60, 61, 42, 76, 70, 64, 53,105, 93, 56, 65, 54, 49, # 60
- 66,110, 51, 43, 44, 63, 81, 77, 98, 75,108,253,253,253,253,253, # 70
-124,202,203,204,205, 40, 58,206,207,208,209,210,211,212,213,214,
-215, 83, 52, 47, 46, 72, 32, 94,216,113,217,109,218,219,220,221,
- 34,116,222,118,100,223,224,117,119,104,125,225,226, 87, 99,227,
-106,122,123,228, 55,229,230,101,231,232,120,233, 48, 39, 57,234,
- 30, 59, 41, 88, 33, 37, 36, 31, 29, 35,235, 62, 28,236,126,237,
-238, 38, 45,239,240,241,242,243,127,244,245,246,247,248,249,250,
- 9, 8, 20, 16, 3, 2, 24, 14, 22, 1, 25, 15, 4, 11, 6, 23,
- 12, 19, 13, 26, 18, 27, 21, 17, 7, 10, 5,251,252,128, 96,253,
-)
-
-# Model Table:
-# total sequences: 100%
-# first 512 sequences: 98.4004%
-# first 1024 sequences: 1.5981%
-# rest sequences: 0.087%
-# negative sequences: 0.0015%
-HebrewLangModel = (
-0,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,3,2,1,2,0,1,0,0,
-3,0,3,1,0,0,1,3,2,0,1,1,2,0,2,2,2,1,1,1,1,2,1,1,1,2,0,0,2,2,0,1,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,
-1,2,1,2,1,2,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,
-1,2,1,3,1,1,0,0,2,0,0,0,1,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,0,1,2,2,1,3,
-1,2,1,1,2,2,0,0,2,2,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,2,2,2,3,2,
-1,2,1,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,2,2,3,2,2,2,1,2,2,2,2,
-1,2,1,1,2,2,0,1,2,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0,2,2,2,2,2,
-0,2,0,2,2,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,0,2,2,2,
-0,2,1,2,2,2,0,0,2,1,0,0,0,0,1,0,1,0,0,0,0,0,0,2,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,2,3,2,2,2,
-1,2,1,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0,
-3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,1,0,2,0,2,
-0,2,1,2,2,2,0,0,1,2,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,2,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,2,2,3,2,1,2,1,1,1,
-0,1,1,1,1,1,3,0,1,0,0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
-3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,0,1,0,0,1,0,0,0,0,
-0,0,1,0,0,0,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,
-0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,2,3,3,3,2,1,2,3,3,2,3,3,3,3,2,3,2,1,2,0,2,1,2,
-0,2,0,2,2,2,0,0,1,2,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,
-3,3,3,3,3,3,3,3,3,2,3,3,3,1,2,2,3,3,2,3,2,3,2,2,3,1,2,2,0,2,2,2,
-0,2,1,2,2,2,0,0,1,2,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,2,2,2,3,3,3,3,1,3,2,2,2,
-0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,3,3,2,3,2,2,2,1,2,2,0,2,2,2,2,
-0,2,0,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,1,3,2,3,3,2,3,3,2,2,1,2,2,2,2,2,2,
-0,2,1,2,1,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,2,3,2,3,3,2,3,3,3,3,2,3,2,3,3,3,3,3,2,2,2,2,2,2,2,1,
-0,2,0,1,2,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,2,1,2,3,3,3,3,3,3,3,2,3,2,3,2,1,2,3,0,2,1,2,2,
-0,2,1,1,2,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,2,0,
-3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,1,3,1,2,2,2,1,2,3,3,1,2,1,2,2,2,2,
-0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,0,2,3,3,3,1,3,3,3,1,2,2,2,2,1,1,2,2,2,2,2,2,
-0,2,0,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,2,3,3,3,2,2,3,3,3,2,1,2,3,2,3,2,2,2,2,1,2,1,1,1,2,2,
-0,2,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
-3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0,0,0,0,
-1,0,1,0,0,0,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,2,3,3,2,3,1,2,2,2,2,3,2,3,1,1,2,2,1,2,2,1,1,0,2,2,2,2,
-0,1,0,1,2,2,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,
-3,0,0,1,1,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,0,
-0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,1,0,1,0,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,
-0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
-3,2,2,1,2,2,2,2,2,2,2,1,2,2,1,2,2,1,1,1,1,1,1,1,1,2,1,1,0,3,3,3,
-0,3,0,2,2,2,2,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
-2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,1,2,2,2,1,1,1,2,0,1,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,0,0,0,0,0,0,
-0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,3,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,1,0,2,1,0,
-0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
-0,3,1,1,2,2,2,2,2,1,2,2,2,1,1,2,2,2,2,2,2,2,1,2,2,1,0,1,1,1,1,0,
-0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,2,1,1,1,1,2,1,1,2,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0,
-0,0,2,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,0,0,
-2,1,1,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,1,2,1,2,1,1,1,1,0,0,0,0,
-0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,2,1,2,2,2,2,2,2,2,2,2,2,1,2,1,2,1,1,2,1,1,1,2,1,2,1,2,0,1,0,1,
-0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,3,1,2,2,2,1,2,2,2,2,2,2,2,2,1,2,1,1,1,1,1,1,2,1,2,1,1,0,1,0,1,
-0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,1,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,
-0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
-3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,1,1,1,1,1,1,1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,2,0,1,1,1,0,1,0,0,0,1,1,0,1,1,0,0,0,0,0,1,1,0,0,
-0,1,1,1,2,1,2,2,2,0,2,0,2,0,1,1,2,1,1,1,1,2,1,0,1,1,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,0,1,0,0,0,0,0,1,0,1,2,2,0,1,0,0,1,1,2,2,1,2,0,2,0,0,0,1,2,0,1,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,2,0,2,1,2,0,2,0,0,1,1,1,1,1,1,0,1,0,0,0,1,0,0,1,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,1,0,0,0,0,0,1,0,2,1,1,0,1,0,0,1,1,1,2,2,0,0,1,0,0,0,1,0,0,1,
-1,1,2,1,0,1,1,1,0,1,0,1,1,1,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,2,2,1,
-0,2,0,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,1,0,0,1,0,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,1,1,1,1,1,1,1,1,2,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,1,
-2,0,1,0,1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,0,1,1,2,1,1,2,0,1,0,0,0,1,1,0,1,
-1,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,0,0,2,1,1,2,0,2,0,0,0,1,1,0,1,
-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,1,0,2,1,1,0,1,0,0,2,2,1,2,1,1,0,1,0,0,0,1,1,0,1,
-2,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,1,2,2,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,1,0,1,
-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,1,2,2,0,0,0,0,2,1,1,1,0,2,1,1,0,0,0,2,1,0,1,
-1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,1,1,0,2,1,1,0,1,0,0,0,1,1,0,1,
-2,2,1,1,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,1,0,2,1,1,0,1,0,0,1,1,0,1,2,1,0,2,0,0,0,1,1,0,1,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,
-0,1,0,0,2,0,2,1,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,1,1,1,0,1,0,0,1,0,0,0,1,0,0,1,
-1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,0,0,0,0,0,0,0,1,0,1,1,0,0,1,0,0,2,1,1,1,1,1,0,1,0,0,0,0,1,0,1,
-0,1,1,1,2,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,1,2,1,0,0,0,0,0,1,1,1,1,1,0,1,0,0,0,1,1,0,0,
-)
-
-Win1255HebrewModel = {
- 'charToOrderMap': win1255_CharToOrderMap,
- 'precedenceMatrix': HebrewLangModel,
- 'mTypicalPositiveRatio': 0.984004,
- 'keepEnglishLetter': False,
- 'charsetName': "windows-1255"
-}
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langhungarianmodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langhungarianmodel.py
deleted file mode 100644
index 49d2f0f..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langhungarianmodel.py
+++ /dev/null
@@ -1,225 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# 255: Control characters that usually does not exist in any text
-# 254: Carriage/Return
-# 253: symbol (punctuation) that does not belong to word
-# 252: 0 - 9
-
-# Character Mapping Table:
-Latin2_HungarianCharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253, 28, 40, 54, 45, 32, 50, 49, 38, 39, 53, 36, 41, 34, 35, 47,
- 46, 71, 43, 33, 37, 57, 48, 64, 68, 55, 52,253,253,253,253,253,
-253, 2, 18, 26, 17, 1, 27, 12, 20, 9, 22, 7, 6, 13, 4, 8,
- 23, 67, 10, 5, 3, 21, 19, 65, 62, 16, 11,253,253,253,253,253,
-159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,
-175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,
-191,192,193,194,195,196,197, 75,198,199,200,201,202,203,204,205,
- 79,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,
-221, 51, 81,222, 78,223,224,225,226, 44,227,228,229, 61,230,231,
-232,233,234, 58,235, 66, 59,236,237,238, 60, 69, 63,239,240,241,
- 82, 14, 74,242, 70, 80,243, 72,244, 15, 83, 77, 84, 30, 76, 85,
-245,246,247, 25, 73, 42, 24,248,249,250, 31, 56, 29,251,252,253,
-)
-
-win1250HungarianCharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253, 28, 40, 54, 45, 32, 50, 49, 38, 39, 53, 36, 41, 34, 35, 47,
- 46, 72, 43, 33, 37, 57, 48, 64, 68, 55, 52,253,253,253,253,253,
-253, 2, 18, 26, 17, 1, 27, 12, 20, 9, 22, 7, 6, 13, 4, 8,
- 23, 67, 10, 5, 3, 21, 19, 65, 62, 16, 11,253,253,253,253,253,
-161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,
-177,178,179,180, 78,181, 69,182,183,184,185,186,187,188,189,190,
-191,192,193,194,195,196,197, 76,198,199,200,201,202,203,204,205,
- 81,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,
-221, 51, 83,222, 80,223,224,225,226, 44,227,228,229, 61,230,231,
-232,233,234, 58,235, 66, 59,236,237,238, 60, 70, 63,239,240,241,
- 84, 14, 75,242, 71, 82,243, 73,244, 15, 85, 79, 86, 30, 77, 87,
-245,246,247, 25, 74, 42, 24,248,249,250, 31, 56, 29,251,252,253,
-)
-
-# Model Table:
-# total sequences: 100%
-# first 512 sequences: 94.7368%
-# first 1024 sequences:5.2623%
-# rest sequences: 0.8894%
-# negative sequences: 0.0009%
-HungarianLangModel = (
-0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
-3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,2,2,3,3,1,1,2,2,2,2,2,1,2,
-3,2,2,3,3,3,3,3,2,3,3,3,3,3,3,1,2,3,3,3,3,2,3,3,1,1,3,3,0,1,1,1,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,
-3,2,1,3,3,3,3,3,2,3,3,3,3,3,1,1,2,3,3,3,3,3,3,3,1,1,3,2,0,1,1,1,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,1,1,2,3,3,3,1,3,3,3,3,3,1,3,3,2,2,0,3,2,3,
-0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,
-3,3,3,3,3,3,2,3,3,3,2,3,3,2,3,3,3,3,3,2,3,3,2,2,3,2,3,2,0,3,2,2,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,
-3,3,3,3,3,3,2,3,3,3,3,3,2,3,3,3,1,2,3,2,2,3,1,2,3,3,2,2,0,3,3,3,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,3,2,3,3,3,3,2,3,3,3,3,0,2,3,2,
-0,0,0,1,1,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,3,3,3,1,1,1,3,3,2,1,3,2,2,3,2,1,3,2,2,1,0,3,3,1,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,2,2,3,3,3,3,3,1,2,3,3,3,3,1,2,1,3,3,3,3,2,2,3,1,1,3,2,0,1,1,1,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,2,2,3,3,3,3,3,2,1,3,3,3,3,3,2,2,1,3,3,3,0,1,1,2,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,
-3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,2,3,3,3,2,0,3,2,3,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,1,0,
-3,3,3,3,3,3,2,3,3,3,2,3,2,3,3,3,1,3,2,2,2,3,1,1,3,3,1,1,0,3,3,2,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,2,3,3,3,2,3,2,3,3,3,2,3,3,3,3,3,1,2,3,2,2,0,2,2,2,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,3,3,2,2,2,3,1,3,3,2,2,1,3,3,3,1,1,3,1,2,3,2,3,2,2,2,1,0,2,2,2,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,
-3,1,1,3,3,3,3,3,1,2,3,3,3,3,1,2,1,3,3,3,2,2,3,2,1,0,3,2,0,1,1,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,1,1,3,3,3,3,3,1,2,3,3,3,3,1,1,0,3,3,3,3,0,2,3,0,0,2,1,0,1,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,2,2,3,3,2,2,2,2,3,3,0,1,2,3,2,3,2,2,3,2,1,2,0,2,2,2,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,
-3,3,3,3,3,3,1,2,3,3,3,2,1,2,3,3,2,2,2,3,2,3,3,1,3,3,1,1,0,2,3,2,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,3,3,1,2,2,2,2,3,3,3,1,1,1,3,3,1,1,3,1,1,3,2,1,2,3,1,1,0,2,2,2,
-0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,3,3,2,1,2,1,1,3,3,1,1,1,1,3,3,1,1,2,2,1,2,1,1,2,2,1,1,0,2,2,1,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,3,3,1,1,2,1,1,3,3,1,0,1,1,3,3,2,0,1,1,2,3,1,0,2,2,1,0,0,1,3,2,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,2,1,3,3,3,3,3,1,2,3,2,3,3,2,1,1,3,2,3,2,1,2,2,0,1,2,1,0,0,1,1,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,
-3,3,3,3,2,2,2,2,3,1,2,2,1,1,3,3,0,3,2,1,2,3,2,1,3,3,1,1,0,2,1,3,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,3,3,2,2,2,3,2,3,3,3,2,1,1,3,3,1,1,1,2,2,3,2,3,2,2,2,1,0,2,2,1,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-1,0,0,3,3,3,3,3,0,0,3,3,2,3,0,0,0,2,3,3,1,0,1,2,0,0,1,1,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,1,2,3,3,3,3,3,1,2,3,3,2,2,1,1,0,3,3,2,2,1,2,2,1,0,2,2,0,1,1,1,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,2,2,1,3,1,2,3,3,2,2,1,1,2,2,1,1,1,1,3,2,1,1,1,1,2,1,0,1,2,1,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,
-2,3,3,1,1,1,1,1,3,3,3,0,1,1,3,3,1,1,1,1,1,2,2,0,3,1,1,2,0,2,1,1,
-0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
-3,1,0,1,2,1,2,2,0,1,2,3,1,2,0,0,0,2,1,1,1,1,1,2,0,0,1,1,0,0,0,0,
-1,2,1,2,2,2,1,2,1,2,0,2,0,2,2,1,1,2,1,1,2,1,1,1,0,1,0,0,0,1,1,0,
-1,1,1,2,3,2,3,3,0,1,2,2,3,1,0,1,0,2,1,2,2,0,1,1,0,0,1,1,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,0,0,3,3,2,2,1,0,0,3,2,3,2,0,0,0,1,1,3,0,0,1,1,0,0,2,1,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,1,1,2,2,3,3,1,0,1,3,2,3,1,1,1,0,1,1,1,1,1,3,1,0,0,2,2,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,1,1,1,2,2,2,1,0,1,2,3,3,2,0,0,0,2,1,1,1,2,1,1,1,0,1,1,1,0,0,0,
-1,2,2,2,2,2,1,1,1,2,0,2,1,1,1,1,1,2,1,1,1,1,1,1,0,1,1,1,0,0,1,1,
-3,2,2,1,0,0,1,1,2,2,0,3,0,1,2,1,1,0,0,1,1,1,0,1,1,1,1,0,2,1,1,1,
-2,2,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,1,1,2,3,1,1,1,1,1,1,1,1,1,0,1,
-2,3,3,0,1,0,0,0,3,3,1,0,0,1,2,2,1,0,0,0,0,2,0,0,1,1,1,0,2,1,1,1,
-2,1,1,1,1,1,1,2,1,1,0,1,1,0,1,1,1,0,1,2,1,1,0,1,1,1,1,1,1,1,0,1,
-2,3,3,0,1,0,0,0,2,2,0,0,0,0,1,2,2,0,0,0,0,1,0,0,1,1,0,0,2,0,1,0,
-2,1,1,1,1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,2,0,1,1,1,1,1,0,1,
-3,2,2,0,1,0,1,0,2,3,2,0,0,1,2,2,1,0,0,1,1,1,0,0,2,1,0,1,2,2,1,1,
-2,1,1,1,1,1,1,2,1,1,1,1,1,1,0,2,1,0,1,1,0,1,1,1,0,1,1,2,1,1,0,1,
-2,2,2,0,0,1,0,0,2,2,1,1,0,0,2,1,1,0,0,0,1,2,0,0,2,1,0,0,2,1,1,1,
-2,1,1,1,1,2,1,2,1,1,1,2,2,1,1,2,1,1,1,2,1,1,1,1,1,1,1,1,1,1,0,1,
-1,2,3,0,0,0,1,0,3,2,1,0,0,1,2,1,1,0,0,0,0,2,1,0,1,1,0,0,2,1,2,1,
-1,1,0,0,0,1,0,1,1,1,1,1,2,0,0,1,0,0,0,2,0,0,1,1,1,1,1,1,1,1,0,1,
-3,0,0,2,1,2,2,1,0,0,2,1,2,2,0,0,0,2,1,1,1,0,1,1,0,0,1,1,2,0,0,0,
-1,2,1,2,2,1,1,2,1,2,0,1,1,1,1,1,1,1,1,1,2,1,1,0,0,1,1,1,1,0,0,1,
-1,3,2,0,0,0,1,0,2,2,2,0,0,0,2,2,1,0,0,0,0,3,1,1,1,1,0,0,2,1,1,1,
-2,1,0,1,1,1,0,1,1,1,1,1,1,1,0,2,1,0,0,1,0,1,1,0,1,1,1,1,1,1,0,1,
-2,3,2,0,0,0,1,0,2,2,0,0,0,0,2,1,1,0,0,0,0,2,1,0,1,1,0,0,2,1,1,0,
-2,1,1,1,1,2,1,2,1,2,0,1,1,1,0,2,1,1,1,2,1,1,1,1,0,1,1,1,1,1,0,1,
-3,1,1,2,2,2,3,2,1,1,2,2,1,1,0,1,0,2,2,1,1,1,1,1,0,0,1,1,0,1,1,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,2,2,0,0,0,0,0,2,2,0,0,0,0,2,2,1,0,0,0,1,1,0,0,1,2,0,0,2,1,1,1,
-2,2,1,1,1,2,1,2,1,1,0,1,1,1,1,2,1,1,1,2,1,1,1,1,0,1,2,1,1,1,0,1,
-1,0,0,1,2,3,2,1,0,0,2,0,1,1,0,0,0,1,1,1,1,0,1,1,0,0,1,0,0,0,0,0,
-1,2,1,2,1,2,1,1,1,2,0,2,1,1,1,0,1,2,0,0,1,1,1,0,0,0,0,0,0,0,0,0,
-2,3,2,0,0,0,0,0,1,1,2,1,0,0,1,1,1,0,0,0,0,2,0,0,1,1,0,0,2,1,1,1,
-2,1,1,1,1,1,1,2,1,0,1,1,1,1,0,2,1,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,
-1,2,2,0,1,1,1,0,2,2,2,0,0,0,3,2,1,0,0,0,1,1,0,0,1,1,0,1,1,1,0,0,
-1,1,0,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,2,1,1,1,0,0,1,1,1,0,1,0,1,
-2,1,0,2,1,1,2,2,1,1,2,1,1,1,0,0,0,1,1,0,1,1,1,1,0,0,1,1,1,0,0,0,
-1,2,2,2,2,2,1,1,1,2,0,2,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,1,0,
-1,2,3,0,0,0,1,0,2,2,0,0,0,0,2,2,0,0,0,0,0,1,0,0,1,0,0,0,2,0,1,0,
-2,1,1,1,1,1,0,2,0,0,0,1,2,1,1,1,1,0,1,2,0,1,0,1,0,1,1,1,0,1,0,1,
-2,2,2,0,0,0,1,0,2,1,2,0,0,0,1,1,2,0,0,0,0,1,0,0,1,1,0,0,2,1,0,1,
-2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,0,1,1,1,1,1,0,1,
-1,2,2,0,0,0,1,0,2,2,2,0,0,0,1,1,0,0,0,0,0,1,1,0,2,0,0,1,1,1,0,1,
-1,0,1,1,1,1,1,1,0,1,1,1,1,0,0,1,0,0,1,1,0,1,0,1,1,1,1,1,0,0,0,1,
-1,0,0,1,0,1,2,1,0,0,1,1,1,2,0,0,0,1,1,0,1,0,1,1,0,0,1,0,0,0,0,0,
-0,2,1,2,1,1,1,1,1,2,0,2,0,1,1,0,1,2,1,0,1,1,1,0,0,0,0,0,0,1,0,0,
-2,1,1,0,1,2,0,0,1,1,1,0,0,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,2,1,0,1,
-2,2,1,1,1,1,1,2,1,1,0,1,1,1,1,2,1,1,1,2,1,1,0,1,0,1,1,1,1,1,0,1,
-1,2,2,0,0,0,0,0,1,1,0,0,0,0,2,1,0,0,0,0,0,2,0,0,2,2,0,0,2,0,0,1,
-2,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,1,
-1,1,2,0,0,3,1,0,2,1,1,1,0,0,1,1,1,0,0,0,1,1,0,0,0,1,0,0,1,0,1,0,
-1,2,1,0,1,1,1,2,1,1,0,1,1,1,1,1,0,0,0,1,1,1,1,1,0,1,0,0,0,1,0,0,
-2,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,2,0,0,0,
-2,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,2,1,1,0,0,1,1,1,1,1,0,1,
-2,1,1,1,2,1,1,1,0,1,1,2,1,0,0,0,0,1,1,1,1,0,1,0,0,0,0,1,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,1,0,1,1,1,1,1,0,0,1,1,2,1,0,0,0,1,1,0,0,0,1,1,0,0,1,0,1,0,0,0,
-1,2,1,1,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,
-2,0,0,0,1,1,1,1,0,0,1,1,0,0,0,0,0,1,1,1,2,0,0,1,0,0,1,0,1,0,0,0,
-0,1,1,1,1,1,1,1,1,2,0,1,1,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,
-1,0,0,1,1,1,1,1,0,0,2,1,0,1,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,
-0,1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0,
-1,0,0,1,1,1,0,0,0,0,1,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
-0,1,1,1,1,1,0,0,1,1,0,1,0,1,0,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,
-0,0,0,1,0,0,0,0,0,0,1,1,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,1,1,1,0,1,0,0,1,1,0,1,0,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,
-2,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,1,0,0,1,0,1,0,1,1,1,0,0,1,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,0,0,1,1,1,1,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,
-0,1,1,1,1,1,1,0,1,1,0,1,0,1,0,0,1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,
-)
-
-Latin2HungarianModel = {
- 'charToOrderMap': Latin2_HungarianCharToOrderMap,
- 'precedenceMatrix': HungarianLangModel,
- 'mTypicalPositiveRatio': 0.947368,
- 'keepEnglishLetter': True,
- 'charsetName': "ISO-8859-2"
-}
-
-Win1250HungarianModel = {
- 'charToOrderMap': win1250HungarianCharToOrderMap,
- 'precedenceMatrix': HungarianLangModel,
- 'mTypicalPositiveRatio': 0.947368,
- 'keepEnglishLetter': True,
- 'charsetName': "windows-1250"
-}
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langthaimodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langthaimodel.py
deleted file mode 100644
index 0508b1b..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/langthaimodel.py
+++ /dev/null
@@ -1,200 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Communicator client code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-# 255: Control characters that usually does not exist in any text
-# 254: Carriage/Return
-# 253: symbol (punctuation) that does not belong to word
-# 252: 0 - 9
-
-# The following result for thai was collected from a limited sample (1M).
-
-# Character Mapping Table:
-TIS620CharToOrderMap = (
-255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, # 00
-255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, # 10
-253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, # 20
-252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, # 30
-253,182,106,107,100,183,184,185,101, 94,186,187,108,109,110,111, # 40
-188,189,190, 89, 95,112,113,191,192,193,194,253,253,253,253,253, # 50
-253, 64, 72, 73,114, 74,115,116,102, 81,201,117, 90,103, 78, 82, # 60
- 96,202, 91, 79, 84,104,105, 97, 98, 92,203,253,253,253,253,253, # 70
-209,210,211,212,213, 88,214,215,216,217,218,219,220,118,221,222,
-223,224, 99, 85, 83,225,226,227,228,229,230,231,232,233,234,235,
-236, 5, 30,237, 24,238, 75, 8, 26, 52, 34, 51,119, 47, 58, 57,
- 49, 53, 55, 43, 20, 19, 44, 14, 48, 3, 17, 25, 39, 62, 31, 54,
- 45, 9, 16, 2, 61, 15,239, 12, 42, 46, 18, 21, 76, 4, 66, 63,
- 22, 10, 1, 36, 23, 13, 40, 27, 32, 35, 86,240,241,242,243,244,
- 11, 28, 41, 29, 33,245, 50, 37, 6, 7, 67, 77, 38, 93,246,247,
- 68, 56, 59, 65, 69, 60, 70, 80, 71, 87,248,249,250,251,252,253,
-)
-
-# Model Table:
-# total sequences: 100%
-# first 512 sequences: 92.6386%
-# first 1024 sequences:7.3177%
-# rest sequences: 1.0230%
-# negative sequences: 0.0436%
-ThaiLangModel = (
-0,1,3,3,3,3,0,0,3,3,0,3,3,0,3,3,3,3,3,3,3,3,0,0,3,3,3,0,3,3,3,3,
-0,3,3,0,0,0,1,3,0,3,3,2,3,3,0,1,2,3,3,3,3,0,2,0,2,0,0,3,2,1,2,2,
-3,0,3,3,2,3,0,0,3,3,0,3,3,0,3,3,3,3,3,3,3,3,3,0,3,2,3,0,2,2,2,3,
-0,2,3,0,0,0,0,1,0,1,2,3,1,1,3,2,2,0,1,1,0,0,1,0,0,0,0,0,0,0,1,1,
-3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,3,3,2,3,2,3,3,2,2,2,
-3,1,2,3,0,3,3,2,2,1,2,3,3,1,2,0,1,3,0,1,0,0,1,0,0,0,0,0,0,0,1,1,
-3,3,2,2,3,3,3,3,1,2,3,3,3,3,3,2,2,2,2,3,3,2,2,3,3,2,2,3,2,3,2,2,
-3,3,1,2,3,1,2,2,3,3,1,0,2,1,0,0,3,1,2,1,0,0,1,0,0,0,0,0,0,1,0,1,
-3,3,3,3,3,3,2,2,3,3,3,3,2,3,2,2,3,3,2,2,3,2,2,2,2,1,1,3,1,2,1,1,
-3,2,1,0,2,1,0,1,0,1,1,0,1,1,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,
-3,3,3,2,3,2,3,3,2,2,3,2,3,3,2,3,1,1,2,3,2,2,2,3,2,2,2,2,2,1,2,1,
-2,2,1,1,3,3,2,1,0,1,2,2,0,1,3,0,0,0,1,1,0,0,0,0,0,2,3,0,0,2,1,1,
-3,3,2,3,3,2,0,0,3,3,0,3,3,0,2,2,3,1,2,2,1,1,1,0,2,2,2,0,2,2,1,1,
-0,2,1,0,2,0,0,2,0,1,0,0,1,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,0,
-3,3,2,3,3,2,0,0,3,3,0,2,3,0,2,1,2,2,2,2,1,2,0,0,2,2,2,0,2,2,1,1,
-0,2,1,0,2,0,0,2,0,1,1,0,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,
-3,3,2,3,2,3,2,0,2,2,1,3,2,1,3,2,1,2,3,2,2,3,0,2,3,2,2,1,2,2,2,2,
-1,2,2,0,0,0,0,2,0,1,2,0,1,1,1,0,1,0,3,1,1,0,0,0,0,0,0,0,0,0,1,0,
-3,3,2,3,3,2,3,2,2,2,3,2,2,3,2,2,1,2,3,2,2,3,1,3,2,2,2,3,2,2,2,3,
-3,2,1,3,0,1,1,1,0,2,1,1,1,1,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,2,0,0,
-1,0,0,3,0,3,3,3,3,3,0,0,3,0,2,2,3,3,3,3,3,0,0,0,1,1,3,0,0,0,0,2,
-0,0,1,0,0,0,0,0,0,0,2,3,0,0,0,3,0,2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,
-2,0,3,3,3,3,0,0,2,3,0,0,3,0,3,3,2,3,3,3,3,3,0,0,3,3,3,0,0,0,3,3,
-0,0,3,0,0,0,0,2,0,0,2,1,1,3,0,0,1,0,0,2,3,0,1,0,0,0,0,0,0,0,1,0,
-3,3,3,3,2,3,3,3,3,3,3,3,1,2,1,3,3,2,2,1,2,2,2,3,1,1,2,0,2,1,2,1,
-2,2,1,0,0,0,1,1,0,1,0,1,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,
-3,0,2,1,2,3,3,3,0,2,0,2,2,0,2,1,3,2,2,1,2,1,0,0,2,2,1,0,2,1,2,2,
-0,1,1,0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,2,1,3,3,1,1,3,0,2,3,1,1,3,2,1,1,2,0,2,2,3,2,1,1,1,1,1,2,
-3,0,0,1,3,1,2,1,2,0,3,0,0,0,1,0,3,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,
-3,3,1,1,3,2,3,3,3,1,3,2,1,3,2,1,3,2,2,2,2,1,3,3,1,2,1,3,1,2,3,0,
-2,1,1,3,2,2,2,1,2,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,
-3,3,2,3,2,3,3,2,3,2,3,2,3,3,2,1,0,3,2,2,2,1,2,2,2,1,2,2,1,2,1,1,
-2,2,2,3,0,1,3,1,1,1,1,0,1,1,0,2,1,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,2,3,2,2,1,1,3,2,3,2,3,2,0,3,2,2,1,2,0,2,2,2,1,2,2,2,2,1,
-3,2,1,2,2,1,0,2,0,1,0,0,1,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,1,
-3,3,3,3,3,2,3,1,2,3,3,2,2,3,0,1,1,2,0,3,3,2,2,3,0,1,1,3,0,0,0,0,
-3,1,0,3,3,0,2,0,2,1,0,0,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,2,3,2,3,3,0,1,3,1,1,2,1,2,1,1,3,1,1,0,2,3,1,1,1,1,1,1,1,1,
-3,1,1,2,2,2,2,1,1,1,0,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-3,2,2,1,1,2,1,3,3,2,3,2,2,3,2,2,3,1,2,2,1,2,0,3,2,1,2,2,2,2,2,1,
-3,2,1,2,2,2,1,1,1,1,0,0,1,1,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,3,3,3,3,1,3,3,0,2,1,0,3,2,0,0,3,1,0,1,1,0,1,0,0,0,0,0,1,
-1,0,0,1,0,3,2,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,2,2,2,3,0,0,1,3,0,3,2,0,3,2,2,3,3,3,3,3,1,0,2,2,2,0,2,2,1,2,
-0,2,3,0,0,0,0,1,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
-3,0,2,3,1,3,3,2,3,3,0,3,3,0,3,2,2,3,2,3,3,3,0,0,2,2,3,0,1,1,1,3,
-0,0,3,0,0,0,2,2,0,1,3,0,1,2,2,2,3,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,
-3,2,3,3,2,0,3,3,2,2,3,1,3,2,1,3,2,0,1,2,2,0,2,3,2,1,0,3,0,0,0,0,
-3,0,0,2,3,1,3,0,0,3,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,1,3,2,2,2,1,2,0,1,3,1,1,3,1,3,0,0,2,1,1,1,1,2,1,1,1,0,2,1,0,1,
-1,2,0,0,0,3,1,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,0,0,0,3,1,0,0,0,1,0,
-3,3,3,3,2,2,2,2,2,1,3,1,1,1,2,0,1,1,2,1,2,1,3,2,0,0,3,1,1,1,1,1,
-3,1,0,2,3,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,2,3,0,3,3,0,2,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
-0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,2,3,1,3,0,0,1,2,0,0,2,0,3,3,2,3,3,3,2,3,0,0,2,2,2,0,0,0,2,2,
-0,0,1,0,0,0,0,3,0,0,0,0,2,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
-0,0,0,3,0,2,0,0,0,0,0,0,0,0,0,0,1,2,3,1,3,3,0,0,1,0,3,0,0,0,0,0,
-0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,1,2,3,1,2,3,1,0,3,0,2,2,1,0,2,1,1,2,0,1,0,0,1,1,1,1,0,1,0,0,
-1,0,0,0,0,1,1,0,3,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,3,3,2,1,0,1,1,1,3,1,2,2,2,2,2,2,1,1,1,1,0,3,1,0,1,3,1,1,1,1,
-1,1,0,2,0,1,3,1,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,1,
-3,0,2,2,1,3,3,2,3,3,0,1,1,0,2,2,1,2,1,3,3,1,0,0,3,2,0,0,0,0,2,1,
-0,1,0,0,0,0,1,2,0,1,1,3,1,1,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,
-0,0,3,0,0,1,0,0,0,3,0,0,3,0,3,1,0,1,1,1,3,2,0,0,0,3,0,0,0,0,2,0,
-0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,
-3,3,1,3,2,1,3,3,1,2,2,0,1,2,1,0,1,2,0,0,0,0,0,3,0,0,0,3,0,0,0,0,
-3,0,0,1,1,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,1,2,0,3,3,3,2,2,0,1,1,0,1,3,0,0,0,2,2,0,0,0,0,3,1,0,1,0,0,0,
-0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,2,3,1,2,0,0,2,1,0,3,1,0,1,2,0,1,1,1,1,3,0,0,3,1,1,0,2,2,1,1,
-0,2,0,0,0,0,0,1,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,0,3,1,2,0,0,2,2,0,1,2,0,1,0,1,3,1,2,1,0,0,0,2,0,3,0,0,0,1,0,
-0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,1,1,2,2,0,0,0,2,0,2,1,0,1,1,0,1,1,1,2,1,0,0,1,1,1,0,2,1,1,1,
-0,1,1,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,1,
-0,0,0,2,0,1,3,1,1,1,1,0,0,0,0,3,2,0,1,0,0,0,1,2,0,0,0,1,0,0,0,0,
-0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,3,3,3,3,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,0,2,3,2,2,0,0,0,1,0,0,0,0,2,3,2,1,2,2,3,0,0,0,2,3,1,0,0,0,1,1,
-0,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,
-3,3,2,2,0,1,0,0,0,0,2,0,2,0,1,0,0,0,1,1,0,0,0,2,1,0,1,0,1,1,0,0,
-0,1,0,2,0,0,1,0,3,0,1,0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,1,0,0,1,0,0,0,0,0,1,1,2,0,0,0,0,1,0,0,1,3,1,0,0,0,0,1,1,0,0,
-0,1,0,0,0,0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,
-3,3,1,1,1,1,2,3,0,0,2,1,1,1,1,1,0,2,1,1,0,0,0,2,1,0,1,2,1,1,0,1,
-2,1,0,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,3,1,0,0,0,0,0,0,0,3,0,0,0,3,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,
-0,0,0,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,3,2,0,0,0,0,0,0,1,2,1,0,1,1,0,2,0,0,1,0,0,2,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,2,0,0,0,1,3,0,1,0,0,0,2,0,0,0,0,0,0,0,1,2,0,0,0,0,0,
-3,3,0,0,1,1,2,0,0,1,2,1,0,1,1,1,0,1,1,0,0,2,1,1,0,1,0,0,1,1,1,0,
-0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,2,2,1,0,0,0,0,1,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,
-2,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,3,0,0,1,1,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-1,1,0,1,2,0,1,2,0,0,1,1,0,2,0,1,0,0,1,0,0,0,0,1,0,0,0,2,0,0,0,0,
-1,0,0,1,0,1,1,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,1,0,0,0,0,0,0,0,1,1,0,1,1,0,2,1,3,0,0,0,0,1,1,0,0,0,0,0,0,0,3,
-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,0,1,0,1,0,0,2,0,0,2,0,0,1,1,2,0,0,1,1,0,0,0,1,0,0,0,1,1,0,0,0,
-1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,
-1,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,1,0,0,0,
-2,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,0,0,0,0,2,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,3,0,0,0,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,1,0,0,0,0,
-1,0,0,0,0,0,0,0,0,1,0,0,0,0,2,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,1,1,0,0,2,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
-)
-
-TIS620ThaiModel = {
- 'charToOrderMap': TIS620CharToOrderMap,
- 'precedenceMatrix': ThaiLangModel,
- 'mTypicalPositiveRatio': 0.926386,
- 'keepEnglishLetter': False,
- 'charsetName': "TIS-620"
-}
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcharsetprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcharsetprober.py
deleted file mode 100644
index bb42f2f..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcharsetprober.py
+++ /dev/null
@@ -1,86 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Universal charset detector code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-# Shy Shalom - original C code
-# Proofpoint, Inc.
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-import sys
-from . import constants
-from .charsetprober import CharSetProber
-
-
-class MultiByteCharSetProber(CharSetProber):
- def __init__(self):
- CharSetProber.__init__(self)
- self._mDistributionAnalyzer = None
- self._mCodingSM = None
- self._mLastChar = [0, 0]
-
- def reset(self):
- CharSetProber.reset(self)
- if self._mCodingSM:
- self._mCodingSM.reset()
- if self._mDistributionAnalyzer:
- self._mDistributionAnalyzer.reset()
- self._mLastChar = [0, 0]
-
- def get_charset_name(self):
- pass
-
- def feed(self, aBuf):
- aLen = len(aBuf)
- for i in range(0, aLen):
- codingState = self._mCodingSM.next_state(aBuf[i])
- if codingState == constants.eError:
- if constants._debug:
- sys.stderr.write(self.get_charset_name()
- + ' prober hit error at byte ' + str(i)
- + '\n')
- self._mState = constants.eNotMe
- break
- elif codingState == constants.eItsMe:
- self._mState = constants.eFoundIt
- break
- elif codingState == constants.eStart:
- charLen = self._mCodingSM.get_current_charlen()
- if i == 0:
- self._mLastChar[1] = aBuf[0]
- self._mDistributionAnalyzer.feed(self._mLastChar, charLen)
- else:
- self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1],
- charLen)
-
- self._mLastChar[0] = aBuf[aLen - 1]
-
- if self.get_state() == constants.eDetecting:
- if (self._mDistributionAnalyzer.got_enough_data() and
- (self.get_confidence() > constants.SHORTCUT_THRESHOLD)):
- self._mState = constants.eFoundIt
-
- return self.get_state()
-
- def get_confidence(self):
- return self._mDistributionAnalyzer.get_confidence()
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcsgroupprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcsgroupprober.py
deleted file mode 100644
index 03c9dcf..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcsgroupprober.py
+++ /dev/null
@@ -1,54 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Universal charset detector code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-# Shy Shalom - original C code
-# Proofpoint, Inc.
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .charsetgroupprober import CharSetGroupProber
-from .utf8prober import UTF8Prober
-from .sjisprober import SJISProber
-from .eucjpprober import EUCJPProber
-from .gb2312prober import GB2312Prober
-from .euckrprober import EUCKRProber
-from .cp949prober import CP949Prober
-from .big5prober import Big5Prober
-from .euctwprober import EUCTWProber
-
-
-class MBCSGroupProber(CharSetGroupProber):
- def __init__(self):
- CharSetGroupProber.__init__(self)
- self._mProbers = [
- UTF8Prober(),
- SJISProber(),
- EUCJPProber(),
- GB2312Prober(),
- EUCKRProber(),
- CP949Prober(),
- Big5Prober(),
- EUCTWProber()
- ]
- self.reset()
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcssm.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcssm.py
deleted file mode 100644
index 3f93cfb..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcssm.py
+++ /dev/null
@@ -1,575 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .constants import eStart, eError, eItsMe
-
-# BIG5
-
-BIG5_cls = (
- 1,1,1,1,1,1,1,1, # 00 - 07 #allow 0x00 as legal value
- 1,1,1,1,1,1,0,0, # 08 - 0f
- 1,1,1,1,1,1,1,1, # 10 - 17
- 1,1,1,0,1,1,1,1, # 18 - 1f
- 1,1,1,1,1,1,1,1, # 20 - 27
- 1,1,1,1,1,1,1,1, # 28 - 2f
- 1,1,1,1,1,1,1,1, # 30 - 37
- 1,1,1,1,1,1,1,1, # 38 - 3f
- 2,2,2,2,2,2,2,2, # 40 - 47
- 2,2,2,2,2,2,2,2, # 48 - 4f
- 2,2,2,2,2,2,2,2, # 50 - 57
- 2,2,2,2,2,2,2,2, # 58 - 5f
- 2,2,2,2,2,2,2,2, # 60 - 67
- 2,2,2,2,2,2,2,2, # 68 - 6f
- 2,2,2,2,2,2,2,2, # 70 - 77
- 2,2,2,2,2,2,2,1, # 78 - 7f
- 4,4,4,4,4,4,4,4, # 80 - 87
- 4,4,4,4,4,4,4,4, # 88 - 8f
- 4,4,4,4,4,4,4,4, # 90 - 97
- 4,4,4,4,4,4,4,4, # 98 - 9f
- 4,3,3,3,3,3,3,3, # a0 - a7
- 3,3,3,3,3,3,3,3, # a8 - af
- 3,3,3,3,3,3,3,3, # b0 - b7
- 3,3,3,3,3,3,3,3, # b8 - bf
- 3,3,3,3,3,3,3,3, # c0 - c7
- 3,3,3,3,3,3,3,3, # c8 - cf
- 3,3,3,3,3,3,3,3, # d0 - d7
- 3,3,3,3,3,3,3,3, # d8 - df
- 3,3,3,3,3,3,3,3, # e0 - e7
- 3,3,3,3,3,3,3,3, # e8 - ef
- 3,3,3,3,3,3,3,3, # f0 - f7
- 3,3,3,3,3,3,3,0 # f8 - ff
-)
-
-BIG5_st = (
- eError,eStart,eStart, 3,eError,eError,eError,eError,#00-07
- eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eError,#08-0f
- eError,eStart,eStart,eStart,eStart,eStart,eStart,eStart#10-17
-)
-
-Big5CharLenTable = (0, 1, 1, 2, 0)
-
-Big5SMModel = {'classTable': BIG5_cls,
- 'classFactor': 5,
- 'stateTable': BIG5_st,
- 'charLenTable': Big5CharLenTable,
- 'name': 'Big5'}
-
-# CP949
-
-CP949_cls = (
- 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,0,0, # 00 - 0f
- 1,1,1,1,1,1,1,1, 1,1,1,0,1,1,1,1, # 10 - 1f
- 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, # 20 - 2f
- 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, # 30 - 3f
- 1,4,4,4,4,4,4,4, 4,4,4,4,4,4,4,4, # 40 - 4f
- 4,4,5,5,5,5,5,5, 5,5,5,1,1,1,1,1, # 50 - 5f
- 1,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5, # 60 - 6f
- 5,5,5,5,5,5,5,5, 5,5,5,1,1,1,1,1, # 70 - 7f
- 0,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6, # 80 - 8f
- 6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6, # 90 - 9f
- 6,7,7,7,7,7,7,7, 7,7,7,7,7,8,8,8, # a0 - af
- 7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7, # b0 - bf
- 7,7,7,7,7,7,9,2, 2,3,2,2,2,2,2,2, # c0 - cf
- 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, # d0 - df
- 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, # e0 - ef
- 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,0, # f0 - ff
-)
-
-CP949_st = (
-#cls= 0 1 2 3 4 5 6 7 8 9 # previous state =
- eError,eStart, 3,eError,eStart,eStart, 4, 5,eError, 6, # eStart
- eError,eError,eError,eError,eError,eError,eError,eError,eError,eError, # eError
- eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe, # eItsMe
- eError,eError,eStart,eStart,eError,eError,eError,eStart,eStart,eStart, # 3
- eError,eError,eStart,eStart,eStart,eStart,eStart,eStart,eStart,eStart, # 4
- eError,eStart,eStart,eStart,eStart,eStart,eStart,eStart,eStart,eStart, # 5
- eError,eStart,eStart,eStart,eStart,eError,eError,eStart,eStart,eStart, # 6
-)
-
-CP949CharLenTable = (0, 1, 2, 0, 1, 1, 2, 2, 0, 2)
-
-CP949SMModel = {'classTable': CP949_cls,
- 'classFactor': 10,
- 'stateTable': CP949_st,
- 'charLenTable': CP949CharLenTable,
- 'name': 'CP949'}
-
-# EUC-JP
-
-EUCJP_cls = (
- 4,4,4,4,4,4,4,4, # 00 - 07
- 4,4,4,4,4,4,5,5, # 08 - 0f
- 4,4,4,4,4,4,4,4, # 10 - 17
- 4,4,4,5,4,4,4,4, # 18 - 1f
- 4,4,4,4,4,4,4,4, # 20 - 27
- 4,4,4,4,4,4,4,4, # 28 - 2f
- 4,4,4,4,4,4,4,4, # 30 - 37
- 4,4,4,4,4,4,4,4, # 38 - 3f
- 4,4,4,4,4,4,4,4, # 40 - 47
- 4,4,4,4,4,4,4,4, # 48 - 4f
- 4,4,4,4,4,4,4,4, # 50 - 57
- 4,4,4,4,4,4,4,4, # 58 - 5f
- 4,4,4,4,4,4,4,4, # 60 - 67
- 4,4,4,4,4,4,4,4, # 68 - 6f
- 4,4,4,4,4,4,4,4, # 70 - 77
- 4,4,4,4,4,4,4,4, # 78 - 7f
- 5,5,5,5,5,5,5,5, # 80 - 87
- 5,5,5,5,5,5,1,3, # 88 - 8f
- 5,5,5,5,5,5,5,5, # 90 - 97
- 5,5,5,5,5,5,5,5, # 98 - 9f
- 5,2,2,2,2,2,2,2, # a0 - a7
- 2,2,2,2,2,2,2,2, # a8 - af
- 2,2,2,2,2,2,2,2, # b0 - b7
- 2,2,2,2,2,2,2,2, # b8 - bf
- 2,2,2,2,2,2,2,2, # c0 - c7
- 2,2,2,2,2,2,2,2, # c8 - cf
- 2,2,2,2,2,2,2,2, # d0 - d7
- 2,2,2,2,2,2,2,2, # d8 - df
- 0,0,0,0,0,0,0,0, # e0 - e7
- 0,0,0,0,0,0,0,0, # e8 - ef
- 0,0,0,0,0,0,0,0, # f0 - f7
- 0,0,0,0,0,0,0,5 # f8 - ff
-)
-
-EUCJP_st = (
- 3, 4, 3, 5,eStart,eError,eError,eError,#00-07
- eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,#08-0f
- eItsMe,eItsMe,eStart,eError,eStart,eError,eError,eError,#10-17
- eError,eError,eStart,eError,eError,eError, 3,eError,#18-1f
- 3,eError,eError,eError,eStart,eStart,eStart,eStart#20-27
-)
-
-EUCJPCharLenTable = (2, 2, 2, 3, 1, 0)
-
-EUCJPSMModel = {'classTable': EUCJP_cls,
- 'classFactor': 6,
- 'stateTable': EUCJP_st,
- 'charLenTable': EUCJPCharLenTable,
- 'name': 'EUC-JP'}
-
-# EUC-KR
-
-EUCKR_cls = (
- 1,1,1,1,1,1,1,1, # 00 - 07
- 1,1,1,1,1,1,0,0, # 08 - 0f
- 1,1,1,1,1,1,1,1, # 10 - 17
- 1,1,1,0,1,1,1,1, # 18 - 1f
- 1,1,1,1,1,1,1,1, # 20 - 27
- 1,1,1,1,1,1,1,1, # 28 - 2f
- 1,1,1,1,1,1,1,1, # 30 - 37
- 1,1,1,1,1,1,1,1, # 38 - 3f
- 1,1,1,1,1,1,1,1, # 40 - 47
- 1,1,1,1,1,1,1,1, # 48 - 4f
- 1,1,1,1,1,1,1,1, # 50 - 57
- 1,1,1,1,1,1,1,1, # 58 - 5f
- 1,1,1,1,1,1,1,1, # 60 - 67
- 1,1,1,1,1,1,1,1, # 68 - 6f
- 1,1,1,1,1,1,1,1, # 70 - 77
- 1,1,1,1,1,1,1,1, # 78 - 7f
- 0,0,0,0,0,0,0,0, # 80 - 87
- 0,0,0,0,0,0,0,0, # 88 - 8f
- 0,0,0,0,0,0,0,0, # 90 - 97
- 0,0,0,0,0,0,0,0, # 98 - 9f
- 0,2,2,2,2,2,2,2, # a0 - a7
- 2,2,2,2,2,3,3,3, # a8 - af
- 2,2,2,2,2,2,2,2, # b0 - b7
- 2,2,2,2,2,2,2,2, # b8 - bf
- 2,2,2,2,2,2,2,2, # c0 - c7
- 2,3,2,2,2,2,2,2, # c8 - cf
- 2,2,2,2,2,2,2,2, # d0 - d7
- 2,2,2,2,2,2,2,2, # d8 - df
- 2,2,2,2,2,2,2,2, # e0 - e7
- 2,2,2,2,2,2,2,2, # e8 - ef
- 2,2,2,2,2,2,2,2, # f0 - f7
- 2,2,2,2,2,2,2,0 # f8 - ff
-)
-
-EUCKR_st = (
- eError,eStart, 3,eError,eError,eError,eError,eError,#00-07
- eItsMe,eItsMe,eItsMe,eItsMe,eError,eError,eStart,eStart #08-0f
-)
-
-EUCKRCharLenTable = (0, 1, 2, 0)
-
-EUCKRSMModel = {'classTable': EUCKR_cls,
- 'classFactor': 4,
- 'stateTable': EUCKR_st,
- 'charLenTable': EUCKRCharLenTable,
- 'name': 'EUC-KR'}
-
-# EUC-TW
-
-EUCTW_cls = (
- 2,2,2,2,2,2,2,2, # 00 - 07
- 2,2,2,2,2,2,0,0, # 08 - 0f
- 2,2,2,2,2,2,2,2, # 10 - 17
- 2,2,2,0,2,2,2,2, # 18 - 1f
- 2,2,2,2,2,2,2,2, # 20 - 27
- 2,2,2,2,2,2,2,2, # 28 - 2f
- 2,2,2,2,2,2,2,2, # 30 - 37
- 2,2,2,2,2,2,2,2, # 38 - 3f
- 2,2,2,2,2,2,2,2, # 40 - 47
- 2,2,2,2,2,2,2,2, # 48 - 4f
- 2,2,2,2,2,2,2,2, # 50 - 57
- 2,2,2,2,2,2,2,2, # 58 - 5f
- 2,2,2,2,2,2,2,2, # 60 - 67
- 2,2,2,2,2,2,2,2, # 68 - 6f
- 2,2,2,2,2,2,2,2, # 70 - 77
- 2,2,2,2,2,2,2,2, # 78 - 7f
- 0,0,0,0,0,0,0,0, # 80 - 87
- 0,0,0,0,0,0,6,0, # 88 - 8f
- 0,0,0,0,0,0,0,0, # 90 - 97
- 0,0,0,0,0,0,0,0, # 98 - 9f
- 0,3,4,4,4,4,4,4, # a0 - a7
- 5,5,1,1,1,1,1,1, # a8 - af
- 1,1,1,1,1,1,1,1, # b0 - b7
- 1,1,1,1,1,1,1,1, # b8 - bf
- 1,1,3,1,3,3,3,3, # c0 - c7
- 3,3,3,3,3,3,3,3, # c8 - cf
- 3,3,3,3,3,3,3,3, # d0 - d7
- 3,3,3,3,3,3,3,3, # d8 - df
- 3,3,3,3,3,3,3,3, # e0 - e7
- 3,3,3,3,3,3,3,3, # e8 - ef
- 3,3,3,3,3,3,3,3, # f0 - f7
- 3,3,3,3,3,3,3,0 # f8 - ff
-)
-
-EUCTW_st = (
- eError,eError,eStart, 3, 3, 3, 4,eError,#00-07
- eError,eError,eError,eError,eError,eError,eItsMe,eItsMe,#08-0f
- eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eError,eStart,eError,#10-17
- eStart,eStart,eStart,eError,eError,eError,eError,eError,#18-1f
- 5,eError,eError,eError,eStart,eError,eStart,eStart,#20-27
- eStart,eError,eStart,eStart,eStart,eStart,eStart,eStart #28-2f
-)
-
-EUCTWCharLenTable = (0, 0, 1, 2, 2, 2, 3)
-
-EUCTWSMModel = {'classTable': EUCTW_cls,
- 'classFactor': 7,
- 'stateTable': EUCTW_st,
- 'charLenTable': EUCTWCharLenTable,
- 'name': 'x-euc-tw'}
-
-# GB2312
-
-GB2312_cls = (
- 1,1,1,1,1,1,1,1, # 00 - 07
- 1,1,1,1,1,1,0,0, # 08 - 0f
- 1,1,1,1,1,1,1,1, # 10 - 17
- 1,1,1,0,1,1,1,1, # 18 - 1f
- 1,1,1,1,1,1,1,1, # 20 - 27
- 1,1,1,1,1,1,1,1, # 28 - 2f
- 3,3,3,3,3,3,3,3, # 30 - 37
- 3,3,1,1,1,1,1,1, # 38 - 3f
- 2,2,2,2,2,2,2,2, # 40 - 47
- 2,2,2,2,2,2,2,2, # 48 - 4f
- 2,2,2,2,2,2,2,2, # 50 - 57
- 2,2,2,2,2,2,2,2, # 58 - 5f
- 2,2,2,2,2,2,2,2, # 60 - 67
- 2,2,2,2,2,2,2,2, # 68 - 6f
- 2,2,2,2,2,2,2,2, # 70 - 77
- 2,2,2,2,2,2,2,4, # 78 - 7f
- 5,6,6,6,6,6,6,6, # 80 - 87
- 6,6,6,6,6,6,6,6, # 88 - 8f
- 6,6,6,6,6,6,6,6, # 90 - 97
- 6,6,6,6,6,6,6,6, # 98 - 9f
- 6,6,6,6,6,6,6,6, # a0 - a7
- 6,6,6,6,6,6,6,6, # a8 - af
- 6,6,6,6,6,6,6,6, # b0 - b7
- 6,6,6,6,6,6,6,6, # b8 - bf
- 6,6,6,6,6,6,6,6, # c0 - c7
- 6,6,6,6,6,6,6,6, # c8 - cf
- 6,6,6,6,6,6,6,6, # d0 - d7
- 6,6,6,6,6,6,6,6, # d8 - df
- 6,6,6,6,6,6,6,6, # e0 - e7
- 6,6,6,6,6,6,6,6, # e8 - ef
- 6,6,6,6,6,6,6,6, # f0 - f7
- 6,6,6,6,6,6,6,0 # f8 - ff
-)
-
-GB2312_st = (
- eError,eStart,eStart,eStart,eStart,eStart, 3,eError,#00-07
- eError,eError,eError,eError,eError,eError,eItsMe,eItsMe,#08-0f
- eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eError,eError,eStart,#10-17
- 4,eError,eStart,eStart,eError,eError,eError,eError,#18-1f
- eError,eError, 5,eError,eError,eError,eItsMe,eError,#20-27
- eError,eError,eStart,eStart,eStart,eStart,eStart,eStart #28-2f
-)
-
-# To be accurate, the length of class 6 can be either 2 or 4.
-# But it is not necessary to discriminate between the two since
-# it is used for frequency analysis only, and we are validing
-# each code range there as well. So it is safe to set it to be
-# 2 here.
-GB2312CharLenTable = (0, 1, 1, 1, 1, 1, 2)
-
-GB2312SMModel = {'classTable': GB2312_cls,
- 'classFactor': 7,
- 'stateTable': GB2312_st,
- 'charLenTable': GB2312CharLenTable,
- 'name': 'GB2312'}
-
-# Shift_JIS
-
-SJIS_cls = (
- 1,1,1,1,1,1,1,1, # 00 - 07
- 1,1,1,1,1,1,0,0, # 08 - 0f
- 1,1,1,1,1,1,1,1, # 10 - 17
- 1,1,1,0,1,1,1,1, # 18 - 1f
- 1,1,1,1,1,1,1,1, # 20 - 27
- 1,1,1,1,1,1,1,1, # 28 - 2f
- 1,1,1,1,1,1,1,1, # 30 - 37
- 1,1,1,1,1,1,1,1, # 38 - 3f
- 2,2,2,2,2,2,2,2, # 40 - 47
- 2,2,2,2,2,2,2,2, # 48 - 4f
- 2,2,2,2,2,2,2,2, # 50 - 57
- 2,2,2,2,2,2,2,2, # 58 - 5f
- 2,2,2,2,2,2,2,2, # 60 - 67
- 2,2,2,2,2,2,2,2, # 68 - 6f
- 2,2,2,2,2,2,2,2, # 70 - 77
- 2,2,2,2,2,2,2,1, # 78 - 7f
- 3,3,3,3,3,3,3,3, # 80 - 87
- 3,3,3,3,3,3,3,3, # 88 - 8f
- 3,3,3,3,3,3,3,3, # 90 - 97
- 3,3,3,3,3,3,3,3, # 98 - 9f
- #0xa0 is illegal in sjis encoding, but some pages does
- #contain such byte. We need to be more error forgiven.
- 2,2,2,2,2,2,2,2, # a0 - a7
- 2,2,2,2,2,2,2,2, # a8 - af
- 2,2,2,2,2,2,2,2, # b0 - b7
- 2,2,2,2,2,2,2,2, # b8 - bf
- 2,2,2,2,2,2,2,2, # c0 - c7
- 2,2,2,2,2,2,2,2, # c8 - cf
- 2,2,2,2,2,2,2,2, # d0 - d7
- 2,2,2,2,2,2,2,2, # d8 - df
- 3,3,3,3,3,3,3,3, # e0 - e7
- 3,3,3,3,3,4,4,4, # e8 - ef
- 4,4,4,4,4,4,4,4, # f0 - f7
- 4,4,4,4,4,0,0,0 # f8 - ff
-)
-
-
-SJIS_st = (
- eError,eStart,eStart, 3,eError,eError,eError,eError,#00-07
- eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,#08-0f
- eItsMe,eItsMe,eError,eError,eStart,eStart,eStart,eStart #10-17
-)
-
-SJISCharLenTable = (0, 1, 1, 2, 0, 0)
-
-SJISSMModel = {'classTable': SJIS_cls,
- 'classFactor': 6,
- 'stateTable': SJIS_st,
- 'charLenTable': SJISCharLenTable,
- 'name': 'Shift_JIS'}
-
-# UCS2-BE
-
-UCS2BE_cls = (
- 0,0,0,0,0,0,0,0, # 00 - 07
- 0,0,1,0,0,2,0,0, # 08 - 0f
- 0,0,0,0,0,0,0,0, # 10 - 17
- 0,0,0,3,0,0,0,0, # 18 - 1f
- 0,0,0,0,0,0,0,0, # 20 - 27
- 0,3,3,3,3,3,0,0, # 28 - 2f
- 0,0,0,0,0,0,0,0, # 30 - 37
- 0,0,0,0,0,0,0,0, # 38 - 3f
- 0,0,0,0,0,0,0,0, # 40 - 47
- 0,0,0,0,0,0,0,0, # 48 - 4f
- 0,0,0,0,0,0,0,0, # 50 - 57
- 0,0,0,0,0,0,0,0, # 58 - 5f
- 0,0,0,0,0,0,0,0, # 60 - 67
- 0,0,0,0,0,0,0,0, # 68 - 6f
- 0,0,0,0,0,0,0,0, # 70 - 77
- 0,0,0,0,0,0,0,0, # 78 - 7f
- 0,0,0,0,0,0,0,0, # 80 - 87
- 0,0,0,0,0,0,0,0, # 88 - 8f
- 0,0,0,0,0,0,0,0, # 90 - 97
- 0,0,0,0,0,0,0,0, # 98 - 9f
- 0,0,0,0,0,0,0,0, # a0 - a7
- 0,0,0,0,0,0,0,0, # a8 - af
- 0,0,0,0,0,0,0,0, # b0 - b7
- 0,0,0,0,0,0,0,0, # b8 - bf
- 0,0,0,0,0,0,0,0, # c0 - c7
- 0,0,0,0,0,0,0,0, # c8 - cf
- 0,0,0,0,0,0,0,0, # d0 - d7
- 0,0,0,0,0,0,0,0, # d8 - df
- 0,0,0,0,0,0,0,0, # e0 - e7
- 0,0,0,0,0,0,0,0, # e8 - ef
- 0,0,0,0,0,0,0,0, # f0 - f7
- 0,0,0,0,0,0,4,5 # f8 - ff
-)
-
-UCS2BE_st = (
- 5, 7, 7,eError, 4, 3,eError,eError,#00-07
- eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,#08-0f
- eItsMe,eItsMe, 6, 6, 6, 6,eError,eError,#10-17
- 6, 6, 6, 6, 6,eItsMe, 6, 6,#18-1f
- 6, 6, 6, 6, 5, 7, 7,eError,#20-27
- 5, 8, 6, 6,eError, 6, 6, 6,#28-2f
- 6, 6, 6, 6,eError,eError,eStart,eStart #30-37
-)
-
-UCS2BECharLenTable = (2, 2, 2, 0, 2, 2)
-
-UCS2BESMModel = {'classTable': UCS2BE_cls,
- 'classFactor': 6,
- 'stateTable': UCS2BE_st,
- 'charLenTable': UCS2BECharLenTable,
- 'name': 'UTF-16BE'}
-
-# UCS2-LE
-
-UCS2LE_cls = (
- 0,0,0,0,0,0,0,0, # 00 - 07
- 0,0,1,0,0,2,0,0, # 08 - 0f
- 0,0,0,0,0,0,0,0, # 10 - 17
- 0,0,0,3,0,0,0,0, # 18 - 1f
- 0,0,0,0,0,0,0,0, # 20 - 27
- 0,3,3,3,3,3,0,0, # 28 - 2f
- 0,0,0,0,0,0,0,0, # 30 - 37
- 0,0,0,0,0,0,0,0, # 38 - 3f
- 0,0,0,0,0,0,0,0, # 40 - 47
- 0,0,0,0,0,0,0,0, # 48 - 4f
- 0,0,0,0,0,0,0,0, # 50 - 57
- 0,0,0,0,0,0,0,0, # 58 - 5f
- 0,0,0,0,0,0,0,0, # 60 - 67
- 0,0,0,0,0,0,0,0, # 68 - 6f
- 0,0,0,0,0,0,0,0, # 70 - 77
- 0,0,0,0,0,0,0,0, # 78 - 7f
- 0,0,0,0,0,0,0,0, # 80 - 87
- 0,0,0,0,0,0,0,0, # 88 - 8f
- 0,0,0,0,0,0,0,0, # 90 - 97
- 0,0,0,0,0,0,0,0, # 98 - 9f
- 0,0,0,0,0,0,0,0, # a0 - a7
- 0,0,0,0,0,0,0,0, # a8 - af
- 0,0,0,0,0,0,0,0, # b0 - b7
- 0,0,0,0,0,0,0,0, # b8 - bf
- 0,0,0,0,0,0,0,0, # c0 - c7
- 0,0,0,0,0,0,0,0, # c8 - cf
- 0,0,0,0,0,0,0,0, # d0 - d7
- 0,0,0,0,0,0,0,0, # d8 - df
- 0,0,0,0,0,0,0,0, # e0 - e7
- 0,0,0,0,0,0,0,0, # e8 - ef
- 0,0,0,0,0,0,0,0, # f0 - f7
- 0,0,0,0,0,0,4,5 # f8 - ff
-)
-
-UCS2LE_st = (
- 6, 6, 7, 6, 4, 3,eError,eError,#00-07
- eError,eError,eError,eError,eItsMe,eItsMe,eItsMe,eItsMe,#08-0f
- eItsMe,eItsMe, 5, 5, 5,eError,eItsMe,eError,#10-17
- 5, 5, 5,eError, 5,eError, 6, 6,#18-1f
- 7, 6, 8, 8, 5, 5, 5,eError,#20-27
- 5, 5, 5,eError,eError,eError, 5, 5,#28-2f
- 5, 5, 5,eError, 5,eError,eStart,eStart #30-37
-)
-
-UCS2LECharLenTable = (2, 2, 2, 2, 2, 2)
-
-UCS2LESMModel = {'classTable': UCS2LE_cls,
- 'classFactor': 6,
- 'stateTable': UCS2LE_st,
- 'charLenTable': UCS2LECharLenTable,
- 'name': 'UTF-16LE'}
-
-# UTF-8
-
-UTF8_cls = (
- 1,1,1,1,1,1,1,1, # 00 - 07 #allow 0x00 as a legal value
- 1,1,1,1,1,1,0,0, # 08 - 0f
- 1,1,1,1,1,1,1,1, # 10 - 17
- 1,1,1,0,1,1,1,1, # 18 - 1f
- 1,1,1,1,1,1,1,1, # 20 - 27
- 1,1,1,1,1,1,1,1, # 28 - 2f
- 1,1,1,1,1,1,1,1, # 30 - 37
- 1,1,1,1,1,1,1,1, # 38 - 3f
- 1,1,1,1,1,1,1,1, # 40 - 47
- 1,1,1,1,1,1,1,1, # 48 - 4f
- 1,1,1,1,1,1,1,1, # 50 - 57
- 1,1,1,1,1,1,1,1, # 58 - 5f
- 1,1,1,1,1,1,1,1, # 60 - 67
- 1,1,1,1,1,1,1,1, # 68 - 6f
- 1,1,1,1,1,1,1,1, # 70 - 77
- 1,1,1,1,1,1,1,1, # 78 - 7f
- 2,2,2,2,3,3,3,3, # 80 - 87
- 4,4,4,4,4,4,4,4, # 88 - 8f
- 4,4,4,4,4,4,4,4, # 90 - 97
- 4,4,4,4,4,4,4,4, # 98 - 9f
- 5,5,5,5,5,5,5,5, # a0 - a7
- 5,5,5,5,5,5,5,5, # a8 - af
- 5,5,5,5,5,5,5,5, # b0 - b7
- 5,5,5,5,5,5,5,5, # b8 - bf
- 0,0,6,6,6,6,6,6, # c0 - c7
- 6,6,6,6,6,6,6,6, # c8 - cf
- 6,6,6,6,6,6,6,6, # d0 - d7
- 6,6,6,6,6,6,6,6, # d8 - df
- 7,8,8,8,8,8,8,8, # e0 - e7
- 8,8,8,8,8,9,8,8, # e8 - ef
- 10,11,11,11,11,11,11,11, # f0 - f7
- 12,13,13,13,14,15,0,0 # f8 - ff
-)
-
-UTF8_st = (
- eError,eStart,eError,eError,eError,eError, 12, 10,#00-07
- 9, 11, 8, 7, 6, 5, 4, 3,#08-0f
- eError,eError,eError,eError,eError,eError,eError,eError,#10-17
- eError,eError,eError,eError,eError,eError,eError,eError,#18-1f
- eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,#20-27
- eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,eItsMe,#28-2f
- eError,eError, 5, 5, 5, 5,eError,eError,#30-37
- eError,eError,eError,eError,eError,eError,eError,eError,#38-3f
- eError,eError,eError, 5, 5, 5,eError,eError,#40-47
- eError,eError,eError,eError,eError,eError,eError,eError,#48-4f
- eError,eError, 7, 7, 7, 7,eError,eError,#50-57
- eError,eError,eError,eError,eError,eError,eError,eError,#58-5f
- eError,eError,eError,eError, 7, 7,eError,eError,#60-67
- eError,eError,eError,eError,eError,eError,eError,eError,#68-6f
- eError,eError, 9, 9, 9, 9,eError,eError,#70-77
- eError,eError,eError,eError,eError,eError,eError,eError,#78-7f
- eError,eError,eError,eError,eError, 9,eError,eError,#80-87
- eError,eError,eError,eError,eError,eError,eError,eError,#88-8f
- eError,eError, 12, 12, 12, 12,eError,eError,#90-97
- eError,eError,eError,eError,eError,eError,eError,eError,#98-9f
- eError,eError,eError,eError,eError, 12,eError,eError,#a0-a7
- eError,eError,eError,eError,eError,eError,eError,eError,#a8-af
- eError,eError, 12, 12, 12,eError,eError,eError,#b0-b7
- eError,eError,eError,eError,eError,eError,eError,eError,#b8-bf
- eError,eError,eStart,eStart,eStart,eStart,eError,eError,#c0-c7
- eError,eError,eError,eError,eError,eError,eError,eError #c8-cf
-)
-
-UTF8CharLenTable = (0, 1, 0, 0, 0, 0, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6)
-
-UTF8SMModel = {'classTable': UTF8_cls,
- 'classFactor': 16,
- 'stateTable': UTF8_st,
- 'charLenTable': UTF8CharLenTable,
- 'name': 'UTF-8'}
-
-# flake8: noqa
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/sbcharsetprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/sbcharsetprober.py
deleted file mode 100644
index 37291bd..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/sbcharsetprober.py
+++ /dev/null
@@ -1,120 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Universal charset detector code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-# Shy Shalom - original C code
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-import sys
-from . import constants
-from .charsetprober import CharSetProber
-from .compat import wrap_ord
-
-SAMPLE_SIZE = 64
-SB_ENOUGH_REL_THRESHOLD = 1024
-POSITIVE_SHORTCUT_THRESHOLD = 0.95
-NEGATIVE_SHORTCUT_THRESHOLD = 0.05
-SYMBOL_CAT_ORDER = 250
-NUMBER_OF_SEQ_CAT = 4
-POSITIVE_CAT = NUMBER_OF_SEQ_CAT - 1
-#NEGATIVE_CAT = 0
-
-
-class SingleByteCharSetProber(CharSetProber):
- def __init__(self, model, reversed=False, nameProber=None):
- CharSetProber.__init__(self)
- self._mModel = model
- # TRUE if we need to reverse every pair in the model lookup
- self._mReversed = reversed
- # Optional auxiliary prober for name decision
- self._mNameProber = nameProber
- self.reset()
-
- def reset(self):
- CharSetProber.reset(self)
- # char order of last character
- self._mLastOrder = 255
- self._mSeqCounters = [0] * NUMBER_OF_SEQ_CAT
- self._mTotalSeqs = 0
- self._mTotalChar = 0
- # characters that fall in our sampling range
- self._mFreqChar = 0
-
- def get_charset_name(self):
- if self._mNameProber:
- return self._mNameProber.get_charset_name()
- else:
- return self._mModel['charsetName']
-
- def feed(self, aBuf):
- if not self._mModel['keepEnglishLetter']:
- aBuf = self.filter_without_english_letters(aBuf)
- aLen = len(aBuf)
- if not aLen:
- return self.get_state()
- for c in aBuf:
- order = self._mModel['charToOrderMap'][wrap_ord(c)]
- if order < SYMBOL_CAT_ORDER:
- self._mTotalChar += 1
- if order < SAMPLE_SIZE:
- self._mFreqChar += 1
- if self._mLastOrder < SAMPLE_SIZE:
- self._mTotalSeqs += 1
- if not self._mReversed:
- i = (self._mLastOrder * SAMPLE_SIZE) + order
- model = self._mModel['precedenceMatrix'][i]
- else: # reverse the order of the letters in the lookup
- i = (order * SAMPLE_SIZE) + self._mLastOrder
- model = self._mModel['precedenceMatrix'][i]
- self._mSeqCounters[model] += 1
- self._mLastOrder = order
-
- if self.get_state() == constants.eDetecting:
- if self._mTotalSeqs > SB_ENOUGH_REL_THRESHOLD:
- cf = self.get_confidence()
- if cf > POSITIVE_SHORTCUT_THRESHOLD:
- if constants._debug:
- sys.stderr.write('%s confidence = %s, we have a'
- 'winner\n' %
- (self._mModel['charsetName'], cf))
- self._mState = constants.eFoundIt
- elif cf < NEGATIVE_SHORTCUT_THRESHOLD:
- if constants._debug:
- sys.stderr.write('%s confidence = %s, below negative'
- 'shortcut threshhold %s\n' %
- (self._mModel['charsetName'], cf,
- NEGATIVE_SHORTCUT_THRESHOLD))
- self._mState = constants.eNotMe
-
- return self.get_state()
-
- def get_confidence(self):
- r = 0.01
- if self._mTotalSeqs > 0:
- r = ((1.0 * self._mSeqCounters[POSITIVE_CAT]) / self._mTotalSeqs
- / self._mModel['mTypicalPositiveRatio'])
- r = r * self._mFreqChar / self._mTotalChar
- if r >= 1.0:
- r = 0.99
- return r
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/sbcsgroupprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/sbcsgroupprober.py
deleted file mode 100644
index 1b6196c..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/sbcsgroupprober.py
+++ /dev/null
@@ -1,69 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is Mozilla Universal charset detector code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 2001
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-# Shy Shalom - original C code
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from .charsetgroupprober import CharSetGroupProber
-from .sbcharsetprober import SingleByteCharSetProber
-from .langcyrillicmodel import (Win1251CyrillicModel, Koi8rModel,
- Latin5CyrillicModel, MacCyrillicModel,
- Ibm866Model, Ibm855Model)
-from .langgreekmodel import Latin7GreekModel, Win1253GreekModel
-from .langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel
-from .langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel
-from .langthaimodel import TIS620ThaiModel
-from .langhebrewmodel import Win1255HebrewModel
-from .hebrewprober import HebrewProber
-
-
-class SBCSGroupProber(CharSetGroupProber):
- def __init__(self):
- CharSetGroupProber.__init__(self)
- self._mProbers = [
- SingleByteCharSetProber(Win1251CyrillicModel),
- SingleByteCharSetProber(Koi8rModel),
- SingleByteCharSetProber(Latin5CyrillicModel),
- SingleByteCharSetProber(MacCyrillicModel),
- SingleByteCharSetProber(Ibm866Model),
- SingleByteCharSetProber(Ibm855Model),
- SingleByteCharSetProber(Latin7GreekModel),
- SingleByteCharSetProber(Win1253GreekModel),
- SingleByteCharSetProber(Latin5BulgarianModel),
- SingleByteCharSetProber(Win1251BulgarianModel),
- SingleByteCharSetProber(Latin2HungarianModel),
- SingleByteCharSetProber(Win1250HungarianModel),
- SingleByteCharSetProber(TIS620ThaiModel),
- ]
- hebrewProber = HebrewProber()
- logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel,
- False, hebrewProber)
- visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, True,
- hebrewProber)
- hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber)
- self._mProbers.extend([hebrewProber, logicalHebrewProber,
- visualHebrewProber])
-
- self.reset()
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/sjisprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/sjisprober.py
deleted file mode 100644
index b173614..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/sjisprober.py
+++ /dev/null
@@ -1,91 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-import sys
-from .mbcharsetprober import MultiByteCharSetProber
-from .codingstatemachine import CodingStateMachine
-from .chardistribution import SJISDistributionAnalysis
-from .jpcntx import SJISContextAnalysis
-from .mbcssm import SJISSMModel
-from . import constants
-
-
-class SJISProber(MultiByteCharSetProber):
- def __init__(self):
- MultiByteCharSetProber.__init__(self)
- self._mCodingSM = CodingStateMachine(SJISSMModel)
- self._mDistributionAnalyzer = SJISDistributionAnalysis()
- self._mContextAnalyzer = SJISContextAnalysis()
- self.reset()
-
- def reset(self):
- MultiByteCharSetProber.reset(self)
- self._mContextAnalyzer.reset()
-
- def get_charset_name(self):
- return "SHIFT_JIS"
-
- def feed(self, aBuf):
- aLen = len(aBuf)
- for i in range(0, aLen):
- codingState = self._mCodingSM.next_state(aBuf[i])
- if codingState == constants.eError:
- if constants._debug:
- sys.stderr.write(self.get_charset_name()
- + ' prober hit error at byte ' + str(i)
- + '\n')
- self._mState = constants.eNotMe
- break
- elif codingState == constants.eItsMe:
- self._mState = constants.eFoundIt
- break
- elif codingState == constants.eStart:
- charLen = self._mCodingSM.get_current_charlen()
- if i == 0:
- self._mLastChar[1] = aBuf[0]
- self._mContextAnalyzer.feed(self._mLastChar[2 - charLen:],
- charLen)
- self._mDistributionAnalyzer.feed(self._mLastChar, charLen)
- else:
- self._mContextAnalyzer.feed(aBuf[i + 1 - charLen:i + 3
- - charLen], charLen)
- self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1],
- charLen)
-
- self._mLastChar[0] = aBuf[aLen - 1]
-
- if self.get_state() == constants.eDetecting:
- if (self._mContextAnalyzer.got_enough_data() and
- (self.get_confidence() > constants.SHORTCUT_THRESHOLD)):
- self._mState = constants.eFoundIt
-
- return self.get_state()
-
- def get_confidence(self):
- contxtCf = self._mContextAnalyzer.get_confidence()
- distribCf = self._mDistributionAnalyzer.get_confidence()
- return max(contxtCf, distribCf)
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/utf8prober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/utf8prober.py
deleted file mode 100644
index 1c0bb5d..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/utf8prober.py
+++ /dev/null
@@ -1,76 +0,0 @@
-######################## BEGIN LICENSE BLOCK ########################
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is
-# Netscape Communications Corporation.
-# Portions created by the Initial Developer are Copyright (C) 1998
-# the Initial Developer. All Rights Reserved.
-#
-# Contributor(s):
-# Mark Pilgrim - port to Python
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
-# 02110-1301 USA
-######################### END LICENSE BLOCK #########################
-
-from . import constants
-from .charsetprober import CharSetProber
-from .codingstatemachine import CodingStateMachine
-from .mbcssm import UTF8SMModel
-
-ONE_CHAR_PROB = 0.5
-
-
-class UTF8Prober(CharSetProber):
- def __init__(self):
- CharSetProber.__init__(self)
- self._mCodingSM = CodingStateMachine(UTF8SMModel)
- self.reset()
-
- def reset(self):
- CharSetProber.reset(self)
- self._mCodingSM.reset()
- self._mNumOfMBChar = 0
-
- def get_charset_name(self):
- return "utf-8"
-
- def feed(self, aBuf):
- for c in aBuf:
- codingState = self._mCodingSM.next_state(c)
- if codingState == constants.eError:
- self._mState = constants.eNotMe
- break
- elif codingState == constants.eItsMe:
- self._mState = constants.eFoundIt
- break
- elif codingState == constants.eStart:
- if self._mCodingSM.get_current_charlen() >= 2:
- self._mNumOfMBChar += 1
-
- if self.get_state() == constants.eDetecting:
- if self.get_confidence() > constants.SHORTCUT_THRESHOLD:
- self._mState = constants.eFoundIt
-
- return self.get_state()
-
- def get_confidence(self):
- unlike = 0.99
- if self._mNumOfMBChar < 6:
- for i in range(0, self._mNumOfMBChar):
- unlike = unlike * ONE_CHAR_PROB
- return 1.0 - unlike
- else:
- return unlike
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/_collections.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/_collections.py
deleted file mode 100644
index 5907b0d..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/_collections.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# urllib3/_collections.py
-# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
-#
-# This module is part of urllib3 and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-from collections import MutableMapping
-try:
- from threading import RLock
-except ImportError: # Platform-specific: No threads available
- class RLock:
- def __enter__(self):
- pass
-
- def __exit__(self, exc_type, exc_value, traceback):
- pass
-
-
-try: # Python 2.7+
- from collections import OrderedDict
-except ImportError:
- from .packages.ordered_dict import OrderedDict
-
-
-__all__ = ['RecentlyUsedContainer']
-
-
-_Null = object()
-
-
-class RecentlyUsedContainer(MutableMapping):
- """
- Provides a thread-safe dict-like container which maintains up to
- ``maxsize`` keys while throwing away the least-recently-used keys beyond
- ``maxsize``.
-
- :param maxsize:
- Maximum number of recent elements to retain.
-
- :param dispose_func:
- Every time an item is evicted from the container,
- ``dispose_func(value)`` is called. Callback which will get called
- """
-
- ContainerCls = OrderedDict
-
- def __init__(self, maxsize=10, dispose_func=None):
- self._maxsize = maxsize
- self.dispose_func = dispose_func
-
- self._container = self.ContainerCls()
- self.lock = RLock()
-
- def __getitem__(self, key):
- # Re-insert the item, moving it to the end of the eviction line.
- with self.lock:
- item = self._container.pop(key)
- self._container[key] = item
- return item
-
- def __setitem__(self, key, value):
- evicted_value = _Null
- with self.lock:
- # Possibly evict the existing value of 'key'
- evicted_value = self._container.get(key, _Null)
- self._container[key] = value
-
- # If we didn't evict an existing value, we might have to evict the
- # least recently used item from the beginning of the container.
- if len(self._container) > self._maxsize:
- _key, evicted_value = self._container.popitem(last=False)
-
- if self.dispose_func and evicted_value is not _Null:
- self.dispose_func(evicted_value)
-
- def __delitem__(self, key):
- with self.lock:
- value = self._container.pop(key)
-
- if self.dispose_func:
- self.dispose_func(value)
-
- def __len__(self):
- with self.lock:
- return len(self._container)
-
- def __iter__(self):
- raise NotImplementedError('Iteration over this class is unlikely to be threadsafe.')
-
- def clear(self):
- with self.lock:
- # Copy pointers to all values, then wipe the mapping
- # under Python 2, this copies the list of values twice :-|
- values = list(self._container.values())
- self._container.clear()
-
- if self.dispose_func:
- for value in values:
- self.dispose_func(value)
-
- def keys(self):
- with self.lock:
- return self._container.keys()
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/__init__.py
deleted file mode 100644
index e69de29..0000000
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/util.py b/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/util.py
deleted file mode 100644
index bd26631..0000000
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/util.py
+++ /dev/null
@@ -1,648 +0,0 @@
-# urllib3/util.py
-# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
-#
-# This module is part of urllib3 and is released under
-# the MIT License: http://www.opensource.org/licenses/mit-license.php
-
-
-from base64 import b64encode
-from binascii import hexlify, unhexlify
-from collections import namedtuple
-from hashlib import md5, sha1
-from socket import error as SocketError, _GLOBAL_DEFAULT_TIMEOUT
-import time
-
-try:
- from select import poll, POLLIN
-except ImportError: # `poll` doesn't exist on OSX and other platforms
- poll = False
- try:
- from select import select
- except ImportError: # `select` doesn't exist on AppEngine.
- select = False
-
-try: # Test for SSL features
- SSLContext = None
- HAS_SNI = False
-
- import ssl
- from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
- from ssl import SSLContext # Modern SSL?
- from ssl import HAS_SNI # Has SNI?
-except ImportError:
- pass
-
-from .packages import six
-from .exceptions import LocationParseError, SSLError, TimeoutStateError
-
-
-_Default = object()
-# The default timeout to use for socket connections. This is the attribute used
-# by httplib to define the default timeout
-
-
-def current_time():
- """
- Retrieve the current time, this function is mocked out in unit testing.
- """
- return time.time()
-
-
-class Timeout(object):
- """
- Utility object for storing timeout values.
-
- Example usage:
-
- .. code-block:: python
-
- timeout = urllib3.util.Timeout(connect=2.0, read=7.0)
- pool = HTTPConnectionPool('www.google.com', 80, timeout=timeout)
- pool.request(...) # Etc, etc
-
- :param connect:
- The maximum amount of time to wait for a connection attempt to a server
- to succeed. Omitting the parameter will default the connect timeout to
- the system default, probably `the global default timeout in socket.py
- `_.
- None will set an infinite timeout for connection attempts.
-
- :type connect: integer, float, or None
-
- :param read:
- The maximum amount of time to wait between consecutive
- read operations for a response from the server. Omitting
- the parameter will default the read timeout to the system
- default, probably `the global default timeout in socket.py
- `_.
- None will set an infinite timeout.
-
- :type read: integer, float, or None
-
- :param total:
- This combines the connect and read timeouts into one; the read timeout
- will be set to the time leftover from the connect attempt. In the
- event that both a connect timeout and a total are specified, or a read
- timeout and a total are specified, the shorter timeout will be applied.
-
- Defaults to None.
-
- :type total: integer, float, or None
-
- .. note::
-
- Many factors can affect the total amount of time for urllib3 to return
- an HTTP response. Specifically, Python's DNS resolver does not obey the
- timeout specified on the socket. Other factors that can affect total
- request time include high CPU load, high swap, the program running at a
- low priority level, or other behaviors. The observed running time for
- urllib3 to return a response may be greater than the value passed to
- `total`.
-
- In addition, the read and total timeouts only measure the time between
- read operations on the socket connecting the client and the server,
- not the total amount of time for the request to return a complete
- response. For most requests, the timeout is raised because the server
- has not sent the first byte in the specified time. This is not always
- the case; if a server streams one byte every fifteen seconds, a timeout
- of 20 seconds will not ever trigger, even though the request will
- take several minutes to complete.
-
- If your goal is to cut off any request after a set amount of wall clock
- time, consider having a second "watcher" thread to cut off a slow
- request.
- """
-
- #: A sentinel object representing the default timeout value
- DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT
-
- def __init__(self, total=None, connect=_Default, read=_Default):
- self._connect = self._validate_timeout(connect, 'connect')
- self._read = self._validate_timeout(read, 'read')
- self.total = self._validate_timeout(total, 'total')
- self._start_connect = None
-
- def __str__(self):
- return '%s(connect=%r, read=%r, total=%r)' % (
- type(self).__name__, self._connect, self._read, self.total)
-
-
- @classmethod
- def _validate_timeout(cls, value, name):
- """ Check that a timeout attribute is valid
-
- :param value: The timeout value to validate
- :param name: The name of the timeout attribute to validate. This is used
- for clear error messages
- :return: the value
- :raises ValueError: if the type is not an integer or a float, or if it
- is a numeric value less than zero
- """
- if value is _Default:
- return cls.DEFAULT_TIMEOUT
-
- if value is None or value is cls.DEFAULT_TIMEOUT:
- return value
-
- try:
- float(value)
- except (TypeError, ValueError):
- raise ValueError("Timeout value %s was %s, but it must be an "
- "int or float." % (name, value))
-
- try:
- if value < 0:
- raise ValueError("Attempted to set %s timeout to %s, but the "
- "timeout cannot be set to a value less "
- "than 0." % (name, value))
- except TypeError: # Python 3
- raise ValueError("Timeout value %s was %s, but it must be an "
- "int or float." % (name, value))
-
- return value
-
- @classmethod
- def from_float(cls, timeout):
- """ Create a new Timeout from a legacy timeout value.
-
- The timeout value used by httplib.py sets the same timeout on the
- connect(), and recv() socket requests. This creates a :class:`Timeout`
- object that sets the individual timeouts to the ``timeout`` value passed
- to this function.
-
- :param timeout: The legacy timeout value
- :type timeout: integer, float, sentinel default object, or None
- :return: a Timeout object
- :rtype: :class:`Timeout`
- """
- return Timeout(read=timeout, connect=timeout)
-
- def clone(self):
- """ Create a copy of the timeout object
-
- Timeout properties are stored per-pool but each request needs a fresh
- Timeout object to ensure each one has its own start/stop configured.
-
- :return: a copy of the timeout object
- :rtype: :class:`Timeout`
- """
- # We can't use copy.deepcopy because that will also create a new object
- # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to
- # detect the user default.
- return Timeout(connect=self._connect, read=self._read,
- total=self.total)
-
- def start_connect(self):
- """ Start the timeout clock, used during a connect() attempt
-
- :raises urllib3.exceptions.TimeoutStateError: if you attempt
- to start a timer that has been started already.
- """
- if self._start_connect is not None:
- raise TimeoutStateError("Timeout timer has already been started.")
- self._start_connect = current_time()
- return self._start_connect
-
- def get_connect_duration(self):
- """ Gets the time elapsed since the call to :meth:`start_connect`.
-
- :return: the elapsed time
- :rtype: float
- :raises urllib3.exceptions.TimeoutStateError: if you attempt
- to get duration for a timer that hasn't been started.
- """
- if self._start_connect is None:
- raise TimeoutStateError("Can't get connect duration for timer "
- "that has not started.")
- return current_time() - self._start_connect
-
- @property
- def connect_timeout(self):
- """ Get the value to use when setting a connection timeout.
-
- This will be a positive float or integer, the value None
- (never timeout), or the default system timeout.
-
- :return: the connect timeout
- :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
- """
- if self.total is None:
- return self._connect
-
- if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
- return self.total
-
- return min(self._connect, self.total)
-
- @property
- def read_timeout(self):
- """ Get the value for the read timeout.
-
- This assumes some time has elapsed in the connection timeout and
- computes the read timeout appropriately.
-
- If self.total is set, the read timeout is dependent on the amount of
- time taken by the connect timeout. If the connection time has not been
- established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
- raised.
-
- :return: the value to use for the read timeout
- :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
- :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
- has not yet been called on this object.
- """
- if (self.total is not None and
- self.total is not self.DEFAULT_TIMEOUT and
- self._read is not None and
- self._read is not self.DEFAULT_TIMEOUT):
- # in case the connect timeout has not yet been established.
- if self._start_connect is None:
- return self._read
- return max(0, min(self.total - self.get_connect_duration(),
- self._read))
- elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:
- return max(0, self.total - self.get_connect_duration())
- else:
- return self._read
-
-
-class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):
- """
- Datastructure for representing an HTTP URL. Used as a return value for
- :func:`parse_url`.
- """
- slots = ()
-
- def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None):
- return super(Url, cls).__new__(cls, scheme, auth, host, port, path, query, fragment)
-
- @property
- def hostname(self):
- """For backwards-compatibility with urlparse. We're nice like that."""
- return self.host
-
- @property
- def request_uri(self):
- """Absolute path including the query string."""
- uri = self.path or '/'
-
- if self.query is not None:
- uri += '?' + self.query
-
- return uri
-
- @property
- def netloc(self):
- """Network location including host and port"""
- if self.port:
- return '%s:%d' % (self.host, self.port)
- return self.host
-
-
-def split_first(s, delims):
- """
- Given a string and an iterable of delimiters, split on the first found
- delimiter. Return two split parts and the matched delimiter.
-
- If not found, then the first part is the full input string.
-
- Example: ::
-
- >>> split_first('foo/bar?baz', '?/=')
- ('foo', 'bar?baz', '/')
- >>> split_first('foo/bar?baz', '123')
- ('foo/bar?baz', '', None)
-
- Scales linearly with number of delims. Not ideal for large number of delims.
- """
- min_idx = None
- min_delim = None
- for d in delims:
- idx = s.find(d)
- if idx < 0:
- continue
-
- if min_idx is None or idx < min_idx:
- min_idx = idx
- min_delim = d
-
- if min_idx is None or min_idx < 0:
- return s, '', None
-
- return s[:min_idx], s[min_idx+1:], min_delim
-
-
-def parse_url(url):
- """
- Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
- performed to parse incomplete urls. Fields not provided will be None.
-
- Partly backwards-compatible with :mod:`urlparse`.
-
- Example: ::
-
- >>> parse_url('http://google.com/mail/')
- Url(scheme='http', host='google.com', port=None, path='/', ...)
- >>> parse_url('google.com:80')
- Url(scheme=None, host='google.com', port=80, path=None, ...)
- >>> parse_url('/foo?bar')
- Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
- """
-
- # While this code has overlap with stdlib's urlparse, it is much
- # simplified for our needs and less annoying.
- # Additionally, this implementations does silly things to be optimal
- # on CPython.
-
- scheme = None
- auth = None
- host = None
- port = None
- path = None
- fragment = None
- query = None
-
- # Scheme
- if '://' in url:
- scheme, url = url.split('://', 1)
-
- # Find the earliest Authority Terminator
- # (http://tools.ietf.org/html/rfc3986#section-3.2)
- url, path_, delim = split_first(url, ['/', '?', '#'])
-
- if delim:
- # Reassemble the path
- path = delim + path_
-
- # Auth
- if '@' in url:
- # Last '@' denotes end of auth part
- auth, url = url.rsplit('@', 1)
-
- # IPv6
- if url and url[0] == '[':
- host, url = url.split(']', 1)
- host += ']'
-
- # Port
- if ':' in url:
- _host, port = url.split(':', 1)
-
- if not host:
- host = _host
-
- if port:
- # If given, ports must be integers.
- if not port.isdigit():
- raise LocationParseError("Failed to parse: %s" % url)
- port = int(port)
- else:
- # Blank ports are cool, too. (rfc3986#section-3.2.3)
- port = None
-
- elif not host and url:
- host = url
-
- if not path:
- return Url(scheme, auth, host, port, path, query, fragment)
-
- # Fragment
- if '#' in path:
- path, fragment = path.split('#', 1)
-
- # Query
- if '?' in path:
- path, query = path.split('?', 1)
-
- return Url(scheme, auth, host, port, path, query, fragment)
-
-
-def get_host(url):
- """
- Deprecated. Use :func:`.parse_url` instead.
- """
- p = parse_url(url)
- return p.scheme or 'http', p.hostname, p.port
-
-
-def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
- basic_auth=None, proxy_basic_auth=None):
- """
- Shortcuts for generating request headers.
-
- :param keep_alive:
- If ``True``, adds 'connection: keep-alive' header.
-
- :param accept_encoding:
- Can be a boolean, list, or string.
- ``True`` translates to 'gzip,deflate'.
- List will get joined by comma.
- String will be used as provided.
-
- :param user_agent:
- String representing the user-agent you want, such as
- "python-urllib3/0.6"
-
- :param basic_auth:
- Colon-separated username:password string for 'authorization: basic ...'
- auth header.
-
- :param proxy_basic_auth:
- Colon-separated username:password string for 'proxy-authorization: basic ...'
- auth header.
-
- Example: ::
-
- >>> make_headers(keep_alive=True, user_agent="Batman/1.0")
- {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
- >>> make_headers(accept_encoding=True)
- {'accept-encoding': 'gzip,deflate'}
- """
- headers = {}
- if accept_encoding:
- if isinstance(accept_encoding, str):
- pass
- elif isinstance(accept_encoding, list):
- accept_encoding = ','.join(accept_encoding)
- else:
- accept_encoding = 'gzip,deflate'
- headers['accept-encoding'] = accept_encoding
-
- if user_agent:
- headers['user-agent'] = user_agent
-
- if keep_alive:
- headers['connection'] = 'keep-alive'
-
- if basic_auth:
- headers['authorization'] = 'Basic ' + \
- b64encode(six.b(basic_auth)).decode('utf-8')
-
- if proxy_basic_auth:
- headers['proxy-authorization'] = 'Basic ' + \
- b64encode(six.b(proxy_basic_auth)).decode('utf-8')
-
- return headers
-
-
-def is_connection_dropped(conn): # Platform-specific
- """
- Returns True if the connection is dropped and should be closed.
-
- :param conn:
- :class:`httplib.HTTPConnection` object.
-
- Note: For platforms like AppEngine, this will always return ``False`` to
- let the platform handle connection recycling transparently for us.
- """
- sock = getattr(conn, 'sock', False)
- if not sock: # Platform-specific: AppEngine
- return False
-
- if not poll:
- if not select: # Platform-specific: AppEngine
- return False
-
- try:
- return select([sock], [], [], 0.0)[0]
- except SocketError:
- return True
-
- # This version is better on platforms that support it.
- p = poll()
- p.register(sock, POLLIN)
- for (fno, ev) in p.poll(0.0):
- if fno == sock.fileno():
- # Either data is buffered (bad), or the connection is dropped.
- return True
-
-
-def resolve_cert_reqs(candidate):
- """
- Resolves the argument to a numeric constant, which can be passed to
- the wrap_socket function/method from the ssl module.
- Defaults to :data:`ssl.CERT_NONE`.
- If given a string it is assumed to be the name of the constant in the
- :mod:`ssl` module or its abbrevation.
- (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
- If it's neither `None` nor a string we assume it is already the numeric
- constant which can directly be passed to wrap_socket.
- """
- if candidate is None:
- return CERT_NONE
-
- if isinstance(candidate, str):
- res = getattr(ssl, candidate, None)
- if res is None:
- res = getattr(ssl, 'CERT_' + candidate)
- return res
-
- return candidate
-
-
-def resolve_ssl_version(candidate):
- """
- like resolve_cert_reqs
- """
- if candidate is None:
- return PROTOCOL_SSLv23
-
- if isinstance(candidate, str):
- res = getattr(ssl, candidate, None)
- if res is None:
- res = getattr(ssl, 'PROTOCOL_' + candidate)
- return res
-
- return candidate
-
-
-def assert_fingerprint(cert, fingerprint):
- """
- Checks if given fingerprint matches the supplied certificate.
-
- :param cert:
- Certificate as bytes object.
- :param fingerprint:
- Fingerprint as string of hexdigits, can be interspersed by colons.
- """
-
- # Maps the length of a digest to a possible hash function producing
- # this digest.
- hashfunc_map = {
- 16: md5,
- 20: sha1
- }
-
- fingerprint = fingerprint.replace(':', '').lower()
-
- digest_length, rest = divmod(len(fingerprint), 2)
-
- if rest or digest_length not in hashfunc_map:
- raise SSLError('Fingerprint is of invalid length.')
-
- # We need encode() here for py32; works on py2 and p33.
- fingerprint_bytes = unhexlify(fingerprint.encode())
-
- hashfunc = hashfunc_map[digest_length]
-
- cert_digest = hashfunc(cert).digest()
-
- if not cert_digest == fingerprint_bytes:
- raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
- .format(hexlify(fingerprint_bytes),
- hexlify(cert_digest)))
-
-def is_fp_closed(obj):
- """
- Checks whether a given file-like object is closed.
-
- :param obj:
- The file-like object to check.
- """
- if hasattr(obj, 'fp'):
- # Object is a container for another file-like object that gets released
- # on exhaustion (e.g. HTTPResponse)
- return obj.fp is None
-
- return obj.closed
-
-
-if SSLContext is not None: # Python 3.2+
- def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
- ca_certs=None, server_hostname=None,
- ssl_version=None):
- """
- All arguments except `server_hostname` have the same meaning as for
- :func:`ssl.wrap_socket`
-
- :param server_hostname:
- Hostname of the expected certificate
- """
- context = SSLContext(ssl_version)
- context.verify_mode = cert_reqs
-
- # Disable TLS compression to migitate CRIME attack (issue #309)
- OP_NO_COMPRESSION = 0x20000
- context.options |= OP_NO_COMPRESSION
-
- if ca_certs:
- try:
- context.load_verify_locations(ca_certs)
- # Py32 raises IOError
- # Py33 raises FileNotFoundError
- except Exception as e: # Reraise as SSLError
- raise SSLError(e)
- if certfile:
- # FIXME: This block needs a test.
- context.load_cert_chain(certfile, keyfile)
- if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
- return context.wrap_socket(sock, server_hostname=server_hostname)
- return context.wrap_socket(sock)
-
-else: # Python 3.1 and earlier
- def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
- ca_certs=None, server_hostname=None,
- ssl_version=None):
- return wrap_socket(sock, keyfile=keyfile, certfile=certfile,
- ca_certs=ca_certs, cert_reqs=cert_reqs,
- ssl_version=ssl_version)
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/PKG-INFO b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/PKG-INFO
similarity index 99%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/PKG-INFO
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/PKG-INFO
index 367827a..c08706c 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/PKG-INFO
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 1.1
Name: pip
-Version: 1.5.5
+Version: 1.5.6
Summary: A tool for installing and managing Python packages.
Home-page: https://pip.pypa.io/
Author: The pip developers
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/SOURCES.txt b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/SOURCES.txt
similarity index 78%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/SOURCES.txt
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/SOURCES.txt
index 4674a0d..ef3a2ba 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/SOURCES.txt
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/SOURCES.txt
@@ -136,44 +136,6 @@ pip/_vendor/requests/status_codes.py
pip/_vendor/requests/structures.py
pip/_vendor/requests/utils.py
pip/_vendor/requests/packages/__init__.py
-pip/_vendor/requests/packages/charade/__init__.py
-pip/_vendor/requests/packages/charade/__main__.py
-pip/_vendor/requests/packages/charade/big5freq.py
-pip/_vendor/requests/packages/charade/big5prober.py
-pip/_vendor/requests/packages/charade/chardistribution.py
-pip/_vendor/requests/packages/charade/charsetgroupprober.py
-pip/_vendor/requests/packages/charade/charsetprober.py
-pip/_vendor/requests/packages/charade/codingstatemachine.py
-pip/_vendor/requests/packages/charade/compat.py
-pip/_vendor/requests/packages/charade/constants.py
-pip/_vendor/requests/packages/charade/cp949prober.py
-pip/_vendor/requests/packages/charade/escprober.py
-pip/_vendor/requests/packages/charade/escsm.py
-pip/_vendor/requests/packages/charade/eucjpprober.py
-pip/_vendor/requests/packages/charade/euckrfreq.py
-pip/_vendor/requests/packages/charade/euckrprober.py
-pip/_vendor/requests/packages/charade/euctwfreq.py
-pip/_vendor/requests/packages/charade/euctwprober.py
-pip/_vendor/requests/packages/charade/gb2312freq.py
-pip/_vendor/requests/packages/charade/gb2312prober.py
-pip/_vendor/requests/packages/charade/hebrewprober.py
-pip/_vendor/requests/packages/charade/jisfreq.py
-pip/_vendor/requests/packages/charade/jpcntx.py
-pip/_vendor/requests/packages/charade/langbulgarianmodel.py
-pip/_vendor/requests/packages/charade/langcyrillicmodel.py
-pip/_vendor/requests/packages/charade/langgreekmodel.py
-pip/_vendor/requests/packages/charade/langhebrewmodel.py
-pip/_vendor/requests/packages/charade/langhungarianmodel.py
-pip/_vendor/requests/packages/charade/langthaimodel.py
-pip/_vendor/requests/packages/charade/latin1prober.py
-pip/_vendor/requests/packages/charade/mbcharsetprober.py
-pip/_vendor/requests/packages/charade/mbcsgroupprober.py
-pip/_vendor/requests/packages/charade/mbcssm.py
-pip/_vendor/requests/packages/charade/sbcharsetprober.py
-pip/_vendor/requests/packages/charade/sbcsgroupprober.py
-pip/_vendor/requests/packages/charade/sjisprober.py
-pip/_vendor/requests/packages/charade/universaldetector.py
-pip/_vendor/requests/packages/charade/utf8prober.py
pip/_vendor/requests/packages/chardet/__init__.py
pip/_vendor/requests/packages/chardet/big5freq.py
pip/_vendor/requests/packages/chardet/big5prober.py
@@ -222,7 +184,6 @@ pip/_vendor/requests/packages/urllib3/filepost.py
pip/_vendor/requests/packages/urllib3/poolmanager.py
pip/_vendor/requests/packages/urllib3/request.py
pip/_vendor/requests/packages/urllib3/response.py
-pip/_vendor/requests/packages/urllib3/util.py
pip/_vendor/requests/packages/urllib3/contrib/__init__.py
pip/_vendor/requests/packages/urllib3/contrib/ntlmpool.py
pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py
@@ -231,6 +192,13 @@ pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py
pip/_vendor/requests/packages/urllib3/packages/six.py
pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py
pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py
+pip/_vendor/requests/packages/urllib3/util/__init__.py
+pip/_vendor/requests/packages/urllib3/util/connection.py
+pip/_vendor/requests/packages/urllib3/util/request.py
+pip/_vendor/requests/packages/urllib3/util/response.py
+pip/_vendor/requests/packages/urllib3/util/ssl_.py
+pip/_vendor/requests/packages/urllib3/util/timeout.py
+pip/_vendor/requests/packages/urllib3/util/url.py
pip/backwardcompat/__init__.py
pip/commands/__init__.py
pip/commands/bundle.py
diff --git a/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/dependency_links.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/dependency_links.txt
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/dependency_links.txt
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/entry_points.txt b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/entry_points.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/entry_points.txt
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/entry_points.txt
diff --git a/Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/not-zip-safe b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/not-zip-safe
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/Flask_Script-2.0.3-py2.7.egg-info/not-zip-safe
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/not-zip-safe
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/requires.txt b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/requires.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/requires.txt
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/requires.txt
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/top_level.txt b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/top_level.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/EGG-INFO/top_level.txt
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/EGG-INFO/top_level.txt
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/__init__.py
similarity index 99%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/__init__.py
index 7a8d694..bb4a588 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/__init__.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/__init__.py
@@ -19,7 +19,7 @@ import pip.cmdoptions
cmdoptions = pip.cmdoptions
# The version as used in the setup.py and the docs conf.py
-__version__ = "1.5.5"
+__version__ = "1.5.6"
def autocomplete():
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/__main__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/__main__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/__main__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/__main__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/_markerlib/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/_markerlib/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/_markerlib/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/_markerlib/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/_markerlib/markers.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/_markerlib/markers.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/_markerlib/markers.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/_markerlib/markers.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/ansi.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/ansi.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/ansi.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/ansi.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/ansitowin32.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/ansitowin32.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/ansitowin32.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/ansitowin32.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/initialise.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/initialise.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/initialise.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/initialise.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/win32.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/win32.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/win32.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/win32.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/winterm.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/winterm.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/colorama/winterm.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/colorama/winterm.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/misc.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/misc.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/misc.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/misc.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/shutil.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/shutil.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/shutil.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/shutil.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/sysconfig.cfg b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/sysconfig.cfg
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/sysconfig.cfg
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/sysconfig.cfg
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/sysconfig.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/sysconfig.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/sysconfig.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/sysconfig.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/tarfile.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/tarfile.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/_backport/tarfile.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/_backport/tarfile.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/compat.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/compat.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/compat.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/compat.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/database.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/database.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/database.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/database.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/index.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/index.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/index.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/index.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/locators.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/locators.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/locators.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/locators.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/manifest.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/manifest.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/manifest.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/manifest.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/markers.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/markers.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/markers.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/markers.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/metadata.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/metadata.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/metadata.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/metadata.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/resources.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/resources.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/resources.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/resources.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/scripts.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/scripts.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/scripts.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/scripts.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/t32.exe b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/t32.exe
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/t32.exe
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/t32.exe
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/t64.exe b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/t64.exe
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/t64.exe
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/t64.exe
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/util.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/util.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/util.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/util.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/version.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/version.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/version.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/version.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/w32.exe b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/w32.exe
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/w32.exe
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/w32.exe
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/w64.exe b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/w64.exe
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/w64.exe
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/w64.exe
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/wheel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/wheel.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/distlib/wheel.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/distlib/wheel.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/constants.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/constants.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/constants.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/constants.py
diff --git a/Darwin/lib/python2.7/site-packages/flask/testsuite/test_apps/blueprintapp/apps/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/flask/testsuite/test_apps/blueprintapp/apps/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/_base.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/_base.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/_base.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/_base.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/alphabeticalattributes.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/alphabeticalattributes.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/alphabeticalattributes.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/alphabeticalattributes.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/inject_meta_charset.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/inject_meta_charset.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/inject_meta_charset.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/inject_meta_charset.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/lint.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/lint.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/lint.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/lint.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/optionaltags.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/optionaltags.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/optionaltags.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/optionaltags.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/sanitizer.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/sanitizer.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/sanitizer.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/sanitizer.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/whitespace.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/whitespace.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/filters/whitespace.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/filters/whitespace.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/html5parser.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/html5parser.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/html5parser.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/html5parser.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/ihatexml.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/ihatexml.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/ihatexml.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/ihatexml.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/inputstream.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/inputstream.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/inputstream.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/inputstream.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/sanitizer.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/sanitizer.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/sanitizer.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/sanitizer.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/serializer/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/serializer/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/serializer/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/serializer/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/serializer/htmlserializer.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/serializer/htmlserializer.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/serializer/htmlserializer.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/serializer/htmlserializer.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/tokenizer.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/tokenizer.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/tokenizer.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/tokenizer.py
diff --git a/Darwin/lib/python2.7/site-packages/flask/testsuite/test_apps/flaskext/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treeadapters/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/flask/testsuite/test_apps/flaskext/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treeadapters/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treeadapters/sax.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treeadapters/sax.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treeadapters/sax.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treeadapters/sax.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treebuilders/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treebuilders/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treebuilders/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treebuilders/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treebuilders/_base.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treebuilders/_base.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treebuilders/_base.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treebuilders/_base.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treebuilders/dom.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treebuilders/dom.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treebuilders/dom.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treebuilders/dom.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treebuilders/etree.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treebuilders/etree.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treebuilders/etree.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treebuilders/etree.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treebuilders/etree_lxml.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treebuilders/etree_lxml.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treebuilders/etree_lxml.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treebuilders/etree_lxml.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/_base.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/_base.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/_base.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/_base.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/dom.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/dom.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/dom.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/dom.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/etree.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/etree.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/etree.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/etree.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/genshistream.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/genshistream.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/genshistream.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/genshistream.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/lxmletree.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/lxmletree.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/lxmletree.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/lxmletree.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/pulldom.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/pulldom.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/treewalkers/pulldom.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/treewalkers/pulldom.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/trie/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/trie/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/trie/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/trie/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/trie/_base.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/trie/_base.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/trie/_base.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/trie/_base.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/trie/datrie.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/trie/datrie.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/trie/datrie.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/trie/datrie.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/trie/py.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/trie/py.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/trie/py.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/trie/py.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/utils.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/utils.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/html5lib/utils.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/html5lib/utils.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/pkg_resources.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/pkg_resources.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/pkg_resources.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/pkg_resources.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/re-vendor.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/re-vendor.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/re-vendor.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/re-vendor.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/__init__.py
similarity index 97%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/__init__.py
index 2e9f3a0..bba1900 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/__init__.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/__init__.py
@@ -42,8 +42,8 @@ is at .
"""
__title__ = 'requests'
-__version__ = '2.2.1'
-__build__ = 0x020201
+__version__ = '2.3.0'
+__build__ = 0x020300
__author__ = 'Kenneth Reitz'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2014 Kenneth Reitz'
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/adapters.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/adapters.py
similarity index 96%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/adapters.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/adapters.py
index dd10e95..eb7a2d2 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/adapters.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/adapters.py
@@ -16,7 +16,7 @@ from .packages.urllib3.response import HTTPResponse
from .packages.urllib3.util import Timeout as TimeoutSauce
from .compat import urlparse, basestring, urldefrag, unquote
from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,
- except_on_missing_scheme, get_auth_from_url)
+ prepend_scheme_if_needed, get_auth_from_url)
from .structures import CaseInsensitiveDict
from .packages.urllib3.exceptions import MaxRetryError
from .packages.urllib3.exceptions import TimeoutError
@@ -203,7 +203,7 @@ class HTTPAdapter(BaseAdapter):
proxy = proxies.get(urlparse(url.lower()).scheme)
if proxy:
- except_on_missing_scheme(proxy)
+ proxy = prepend_scheme_if_needed(proxy, 'http')
proxy_headers = self.proxy_headers(proxy)
if not proxy in self.proxy_manager:
@@ -310,10 +310,7 @@ class HTTPAdapter(BaseAdapter):
chunked = not (request.body is None or 'Content-Length' in request.headers)
- if stream:
- timeout = TimeoutSauce(connect=timeout)
- else:
- timeout = TimeoutSauce(connect=timeout, read=timeout)
+ timeout = TimeoutSauce(connect=timeout, read=timeout)
try:
if not chunked:
@@ -372,25 +369,20 @@ class HTTPAdapter(BaseAdapter):
conn._put_conn(low_conn)
except socket.error as sockerr:
- raise ConnectionError(sockerr)
+ raise ConnectionError(sockerr, request=request)
except MaxRetryError as e:
- raise ConnectionError(e)
+ raise ConnectionError(e, request=request)
except _ProxyError as e:
raise ProxyError(e)
except (_SSLError, _HTTPError) as e:
if isinstance(e, _SSLError):
- raise SSLError(e)
+ raise SSLError(e, request=request)
elif isinstance(e, TimeoutError):
- raise Timeout(e)
+ raise Timeout(e, request=request)
else:
raise
- r = self.build_response(request, resp)
-
- if not stream:
- r.content
-
- return r
+ return self.build_response(request, resp)
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/api.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/api.py
similarity index 99%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/api.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/api.py
index baf43dd..01d853d 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/api.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/api.py
@@ -26,7 +26,7 @@ def request(method, url, **kwargs):
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of 'name': file-like-objects (or {'name': ('filename', fileobj)}) for multipart encoding upload.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
- :param timeout: (optional) Float describing the timeout of the request.
+ :param timeout: (optional) Float describing the timeout of the request in seconds.
:param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/auth.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/auth.py
similarity index 99%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/auth.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/auth.py
index 6664cd8..9f831b7 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/auth.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/auth.py
@@ -11,7 +11,6 @@ import os
import re
import time
import hashlib
-import logging
from base64 import b64encode
@@ -19,8 +18,6 @@ from .compat import urlparse, str
from .cookies import extract_cookies_to_jar
from .utils import parse_dict_header
-log = logging.getLogger(__name__)
-
CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/cacert.pem b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/cacert.pem
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/cacert.pem
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/cacert.pem
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/certs.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/certs.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/certs.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/certs.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/compat.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/compat.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/compat.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/compat.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/cookies.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/cookies.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/cookies.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/cookies.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/exceptions.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/exceptions.py
similarity index 76%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/exceptions.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/exceptions.py
index cd3c760..a4ee9d6 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/exceptions.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/exceptions.py
@@ -14,15 +14,22 @@ class RequestException(IOError):
"""There was an ambiguous exception that occurred while handling your
request."""
+ def __init__(self, *args, **kwargs):
+ """
+ Initialize RequestException with `request` and `response` objects.
+ """
+ response = kwargs.pop('response', None)
+ self.response = response
+ self.request = kwargs.pop('request', None)
+ if (response is not None and not self.request and
+ hasattr(response, 'request')):
+ self.request = self.response.request
+ super(RequestException, self).__init__(*args, **kwargs)
+
class HTTPError(RequestException):
"""An HTTP error occurred."""
- def __init__(self, *args, **kwargs):
- """ Initializes HTTPError with optional `response` object. """
- self.response = kwargs.pop('response', None)
- super(HTTPError, self).__init__(*args, **kwargs)
-
class ConnectionError(RequestException):
"""A Connection error occurred."""
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/hooks.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/hooks.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/hooks.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/hooks.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/models.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/models.py
similarity index 92%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/models.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/models.py
index ae46a83..120968f 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/models.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/models.py
@@ -8,7 +8,6 @@ This module contains the primary objects that power Requests.
"""
import collections
-import logging
import datetime
from io import BytesIO, UnsupportedOperation
@@ -31,12 +30,20 @@ from .utils import (
from .compat import (
cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,
is_py2, chardet, json, builtin_str, basestring, IncompleteRead)
+from .status_codes import codes
+#: The set of HTTP status codes that indicate an automatically
+#: processable redirect.
+REDIRECT_STATI = (
+ codes.moved, # 301
+ codes.found, # 302
+ codes.other, # 303
+ codes.temporary_moved, # 307
+)
+DEFAULT_REDIRECT_LIMIT = 30
CONTENT_CHUNK_SIZE = 10 * 1024
ITER_CHUNK_SIZE = 512
-log = logging.getLogger(__name__)
-
class RequestEncodingMixin(object):
@property
@@ -401,9 +408,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
is_stream = all([
hasattr(data, '__iter__'),
- not isinstance(data, basestring),
- not isinstance(data, list),
- not isinstance(data, dict)
+ not isinstance(data, (basestring, list, tuple, dict))
])
try:
@@ -517,7 +522,7 @@ class Response(object):
self._content = False
self._content_consumed = False
- #: Integer Code of responded HTTP Status.
+ #: Integer Code of responded HTTP Status, e.g. 404 or 200.
self.status_code = None
#: Case-insensitive Dictionary of Response Headers.
@@ -541,6 +546,7 @@ class Response(object):
#: up here. The list is sorted from the oldest to the most recent request.
self.history = []
+ #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
self.reason = None
#: A CookieJar of Cookies the server sent back.
@@ -567,6 +573,7 @@ class Response(object):
# pickled objects do not have .raw
setattr(self, '_content_consumed', True)
+ setattr(self, 'raw', None)
def __repr__(self):
return '' % (self.status_code)
@@ -591,10 +598,16 @@ class Response(object):
return False
return True
+ @property
+ def is_redirect(self):
+ """True if this Response is a well-formed HTTP redirect that could have
+ been processed automatically (by :meth:`Session.resolve_redirects`).
+ """
+ return ('location' in self.headers and self.status_code in REDIRECT_STATI)
+
@property
def apparent_encoding(self):
- """The apparent encoding, provided by the lovely Charade library
- (Thanks, Ian!)."""
+ """The apparent encoding, provided by the chardet library"""
return chardet.detect(self.content)['encoding']
def iter_content(self, chunk_size=1, decode_unicode=False):
@@ -603,17 +616,15 @@ class Response(object):
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
- """
- if self._content_consumed:
- # simulate reading small chunks of the content
- return iter_slices(self._content, chunk_size)
+ If decode_unicode is True, content will be decoded using the best
+ available encoding based on the response.
+ """
def generate():
try:
# Special case for urllib3.
try:
- for chunk in self.raw.stream(chunk_size,
- decode_content=True):
+ for chunk in self.raw.stream(chunk_size, decode_content=True):
yield chunk
except IncompleteRead as e:
raise ChunkedEncodingError(e)
@@ -629,12 +640,17 @@ class Response(object):
self._content_consumed = True
- gen = generate()
+ # simulate reading small chunks of the content
+ reused_chunks = iter_slices(self._content, chunk_size)
+
+ stream_chunks = generate()
+
+ chunks = reused_chunks if self._content_consumed else stream_chunks
if decode_unicode:
- gen = stream_decode_response_unicode(gen, self)
+ chunks = stream_decode_response_unicode(chunks, self)
- return gen
+ return chunks
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None):
"""Iterates over the response data, one line at a time. When
@@ -644,8 +660,7 @@ class Response(object):
pending = None
- for chunk in self.iter_content(chunk_size=chunk_size,
- decode_unicode=decode_unicode):
+ for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
if pending is not None:
chunk = pending + chunk
@@ -693,7 +708,7 @@ class Response(object):
If Response.encoding is None, encoding will be guessed using
``chardet``.
- The encoding of the response content is determined based soley on HTTP
+ The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
@@ -737,7 +752,14 @@ class Response(object):
# a best guess).
encoding = guess_json_utf(self.content)
if encoding is not None:
- return json.loads(self.content.decode(encoding), **kwargs)
+ try:
+ return json.loads(self.content.decode(encoding), **kwargs)
+ except UnicodeDecodeError:
+ # Wrong UTF codec detected; usually because it's not UTF-8
+ # but some other 8-bit codec. This is an RFC violation,
+ # and the server didn't bother to tell us what codec *was*
+ # used.
+ pass
return json.loads(self.text, **kwargs)
@property
@@ -773,8 +795,8 @@ class Response(object):
raise HTTPError(http_error_msg, response=self)
def close(self):
- """Closes the underlying file descriptor and releases the connection
- back to the pool.
+ """Releases the connection back to the pool. Once this method has been
+ called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.*
"""
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/big5freq.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/big5freq.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/big5freq.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/big5freq.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/big5prober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/big5prober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/big5prober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/big5prober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/chardetect.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/chardetect.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/chardetect.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/chardetect.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/chardistribution.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/chardistribution.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/chardistribution.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/chardistribution.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/charsetgroupprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/charsetgroupprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/charsetgroupprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/charsetgroupprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/charsetprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/charsetprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/charsetprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/charsetprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/codingstatemachine.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/codingstatemachine.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/codingstatemachine.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/codingstatemachine.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/compat.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/compat.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/compat.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/compat.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/constants.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/constants.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/constants.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/constants.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/cp949prober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/cp949prober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/cp949prober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/cp949prober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/escprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/escprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/escprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/escprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/escsm.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/escsm.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/escsm.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/escsm.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/eucjpprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/eucjpprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/eucjpprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/eucjpprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/euckrfreq.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/euckrfreq.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/euckrfreq.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/euckrfreq.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/euckrprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/euckrprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/euckrprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/euckrprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/euctwfreq.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/euctwfreq.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/euctwfreq.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/euctwfreq.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/euctwprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/euctwprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/euctwprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/euctwprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/gb2312freq.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/gb2312freq.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/gb2312freq.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/gb2312freq.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/gb2312prober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/gb2312prober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/gb2312prober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/gb2312prober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/hebrewprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/hebrewprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/hebrewprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/hebrewprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/jisfreq.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/jisfreq.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/jisfreq.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/jisfreq.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/jpcntx.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/jpcntx.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/jpcntx.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/jpcntx.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langbulgarianmodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langbulgarianmodel.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langbulgarianmodel.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langbulgarianmodel.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langcyrillicmodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langcyrillicmodel.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langcyrillicmodel.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langcyrillicmodel.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langgreekmodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langgreekmodel.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langgreekmodel.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langgreekmodel.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langhebrewmodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langhebrewmodel.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langhebrewmodel.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langhebrewmodel.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langhungarianmodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langhungarianmodel.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langhungarianmodel.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langhungarianmodel.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langthaimodel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langthaimodel.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/langthaimodel.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/langthaimodel.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/latin1prober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/latin1prober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/latin1prober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/latin1prober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/mbcharsetprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcharsetprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/mbcharsetprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcharsetprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/mbcsgroupprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcsgroupprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/mbcsgroupprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcsgroupprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/mbcssm.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcssm.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/mbcssm.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/mbcssm.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/sbcharsetprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/sbcharsetprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/sbcharsetprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/sbcharsetprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/sbcsgroupprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/sbcsgroupprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/sbcsgroupprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/sbcsgroupprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/sjisprober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/sjisprober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/sjisprober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/sjisprober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/universaldetector.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/universaldetector.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/chardet/universaldetector.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/universaldetector.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/utf8prober.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/utf8prober.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/charade/utf8prober.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/chardet/utf8prober.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/_collections.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/_collections.py
new file mode 100644
index 0000000..9cea3a4
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/_collections.py
@@ -0,0 +1,205 @@
+# urllib3/_collections.py
+# Copyright 2008-2013 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
+#
+# This module is part of urllib3 and is released under
+# the MIT License: http://www.opensource.org/licenses/mit-license.php
+
+from collections import Mapping, MutableMapping
+try:
+ from threading import RLock
+except ImportError: # Platform-specific: No threads available
+ class RLock:
+ def __enter__(self):
+ pass
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ pass
+
+
+try: # Python 2.7+
+ from collections import OrderedDict
+except ImportError:
+ from .packages.ordered_dict import OrderedDict
+from .packages.six import itervalues
+
+
+__all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict']
+
+
+_Null = object()
+
+
+class RecentlyUsedContainer(MutableMapping):
+ """
+ Provides a thread-safe dict-like container which maintains up to
+ ``maxsize`` keys while throwing away the least-recently-used keys beyond
+ ``maxsize``.
+
+ :param maxsize:
+ Maximum number of recent elements to retain.
+
+ :param dispose_func:
+ Every time an item is evicted from the container,
+ ``dispose_func(value)`` is called. Callback which will get called
+ """
+
+ ContainerCls = OrderedDict
+
+ def __init__(self, maxsize=10, dispose_func=None):
+ self._maxsize = maxsize
+ self.dispose_func = dispose_func
+
+ self._container = self.ContainerCls()
+ self.lock = RLock()
+
+ def __getitem__(self, key):
+ # Re-insert the item, moving it to the end of the eviction line.
+ with self.lock:
+ item = self._container.pop(key)
+ self._container[key] = item
+ return item
+
+ def __setitem__(self, key, value):
+ evicted_value = _Null
+ with self.lock:
+ # Possibly evict the existing value of 'key'
+ evicted_value = self._container.get(key, _Null)
+ self._container[key] = value
+
+ # If we didn't evict an existing value, we might have to evict the
+ # least recently used item from the beginning of the container.
+ if len(self._container) > self._maxsize:
+ _key, evicted_value = self._container.popitem(last=False)
+
+ if self.dispose_func and evicted_value is not _Null:
+ self.dispose_func(evicted_value)
+
+ def __delitem__(self, key):
+ with self.lock:
+ value = self._container.pop(key)
+
+ if self.dispose_func:
+ self.dispose_func(value)
+
+ def __len__(self):
+ with self.lock:
+ return len(self._container)
+
+ def __iter__(self):
+ raise NotImplementedError('Iteration over this class is unlikely to be threadsafe.')
+
+ def clear(self):
+ with self.lock:
+ # Copy pointers to all values, then wipe the mapping
+ # under Python 2, this copies the list of values twice :-|
+ values = list(self._container.values())
+ self._container.clear()
+
+ if self.dispose_func:
+ for value in values:
+ self.dispose_func(value)
+
+ def keys(self):
+ with self.lock:
+ return self._container.keys()
+
+
+class HTTPHeaderDict(MutableMapping):
+ """
+ :param headers:
+ An iterable of field-value pairs. Must not contain multiple field names
+ when compared case-insensitively.
+
+ :param kwargs:
+ Additional field-value pairs to pass in to ``dict.update``.
+
+ A ``dict`` like container for storing HTTP Headers.
+
+ Field names are stored and compared case-insensitively in compliance with
+ RFC 2616. Iteration provides the first case-sensitive key seen for each
+ case-insensitive pair.
+
+ Using ``__setitem__`` syntax overwrites fields that compare equal
+ case-insensitively in order to maintain ``dict``'s api. For fields that
+ compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``
+ in a loop.
+
+ If multiple fields that are equal case-insensitively are passed to the
+ constructor or ``.update``, the behavior is undefined and some will be
+ lost.
+
+ >>> headers = HTTPHeaderDict()
+ >>> headers.add('Set-Cookie', 'foo=bar')
+ >>> headers.add('set-cookie', 'baz=quxx')
+ >>> headers['content-length'] = '7'
+ >>> headers['SET-cookie']
+ 'foo=bar, baz=quxx'
+ >>> headers['Content-Length']
+ '7'
+
+ If you want to access the raw headers with their original casing
+ for debugging purposes you can access the private ``._data`` attribute
+ which is a normal python ``dict`` that maps the case-insensitive key to a
+ list of tuples stored as (case-sensitive-original-name, value). Using the
+ structure from above as our example:
+
+ >>> headers._data
+ {'set-cookie': [('Set-Cookie', 'foo=bar'), ('set-cookie', 'baz=quxx')],
+ 'content-length': [('content-length', '7')]}
+ """
+
+ def __init__(self, headers=None, **kwargs):
+ self._data = {}
+ if headers is None:
+ headers = {}
+ self.update(headers, **kwargs)
+
+ def add(self, key, value):
+ """Adds a (name, value) pair, doesn't overwrite the value if it already
+ exists.
+
+ >>> headers = HTTPHeaderDict(foo='bar')
+ >>> headers.add('Foo', 'baz')
+ >>> headers['foo']
+ 'bar, baz'
+ """
+ self._data.setdefault(key.lower(), []).append((key, value))
+
+ def getlist(self, key):
+ """Returns a list of all the values for the named field. Returns an
+ empty list if the key doesn't exist."""
+ return self[key].split(', ') if key in self else []
+
+ def copy(self):
+ h = HTTPHeaderDict()
+ for key in self._data:
+ for rawkey, value in self._data[key]:
+ h.add(rawkey, value)
+ return h
+
+ def __eq__(self, other):
+ if not isinstance(other, Mapping):
+ return False
+ other = HTTPHeaderDict(other)
+ return dict((k1, self[k1]) for k1 in self._data) == \
+ dict((k2, other[k2]) for k2 in other._data)
+
+ def __getitem__(self, key):
+ values = self._data[key.lower()]
+ return ', '.join(value[1] for value in values)
+
+ def __setitem__(self, key, value):
+ self._data[key.lower()] = [(key, value)]
+
+ def __delitem__(self, key):
+ del self._data[key.lower()]
+
+ def __len__(self):
+ return len(self._data)
+
+ def __iter__(self):
+ for headers in itervalues(self._data):
+ yield headers[0][0]
+
+ def __repr__(self):
+ return '%s(%r)' % (self.__class__.__name__, dict(self.items()))
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/connection.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/connection.py
similarity index 71%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/connection.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/connection.py
index 2124774..5feb332 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/connection.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/connection.py
@@ -4,6 +4,7 @@
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
+import sys
import socket
from socket import timeout as SocketTimeout
@@ -38,6 +39,7 @@ from .exceptions import (
ConnectTimeoutError,
)
from .packages.ssl_match_hostname import match_hostname
+from .packages import six
from .util import (
assert_fingerprint,
resolve_cert_reqs,
@@ -53,34 +55,50 @@ port_by_scheme = {
class HTTPConnection(_HTTPConnection, object):
+ """
+ Based on httplib.HTTPConnection but provides an extra constructor
+ backwards-compatibility layer between older and newer Pythons.
+ """
+
default_port = port_by_scheme['http']
# By default, disable Nagle's Algorithm.
tcp_nodelay = 1
+ def __init__(self, *args, **kw):
+ if six.PY3: # Python 3
+ kw.pop('strict', None)
+ if sys.version_info < (2, 7): # Python 2.6 and older
+ kw.pop('source_address', None)
+
+ # Pre-set source_address in case we have an older Python like 2.6.
+ self.source_address = kw.get('source_address')
+
+ # Superclass also sets self.source_address in Python 2.7+.
+ _HTTPConnection.__init__(self, *args, **kw)
+
def _new_conn(self):
- """ Establish a socket connection and set nodelay settings on it
+ """ Establish a socket connection and set nodelay settings on it.
:return: a new socket connection
"""
- try:
- conn = socket.create_connection(
- (self.host, self.port),
- self.timeout,
- self.source_address,
- )
- except AttributeError: # Python 2.6
- conn = socket.create_connection(
- (self.host, self.port),
- self.timeout,
- )
- conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY,
- self.tcp_nodelay)
+ extra_args = []
+ if self.source_address: # Python 2.7+
+ extra_args.append(self.source_address)
+
+ conn = socket.create_connection(
+ (self.host, self.port), self.timeout, *extra_args)
+ conn.setsockopt(
+ socket.IPPROTO_TCP, socket.TCP_NODELAY, self.tcp_nodelay)
+
return conn
def _prepare_conn(self, conn):
self.sock = conn
- if self._tunnel_host:
+ # the _tunnel_host attribute was added in python 2.6.3 (via
+ # http://hg.python.org/cpython/rev/0f57b30a152f) so pythons 2.6(0-2) do
+ # not have them.
+ if getattr(self, '_tunnel_host', None):
# TODO: Fix tunnel so it doesn't depend on self.sock state.
self._tunnel()
@@ -93,15 +111,18 @@ class HTTPSConnection(HTTPConnection):
default_port = port_by_scheme['https']
def __init__(self, host, port=None, key_file=None, cert_file=None,
- strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
- source_address=None):
- try:
- HTTPConnection.__init__(self, host, port, strict, timeout, source_address)
- except TypeError: # Python 2.6
- HTTPConnection.__init__(self, host, port, strict, timeout)
+ strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, **kw):
+
+ HTTPConnection.__init__(self, host, port, strict=strict,
+ timeout=timeout, **kw)
+
self.key_file = key_file
self.cert_file = cert_file
+ # Required property for Google AppEngine 1.9.0 which otherwise causes
+ # HTTPS requests to go out as HTTP. (See Issue #356)
+ self._protocol = 'https'
+
def connect(self):
conn = self._new_conn()
self._prepare_conn(conn)
@@ -116,6 +137,7 @@ class VerifiedHTTPSConnection(HTTPSConnection):
cert_reqs = None
ca_certs = None
ssl_version = None
+ conn_kw = {}
def set_cert(self, key_file=None, cert_file=None,
cert_reqs=None, ca_certs=None,
@@ -130,11 +152,11 @@ class VerifiedHTTPSConnection(HTTPSConnection):
def connect(self):
# Add certificate verification
+
try:
sock = socket.create_connection(
- address=(self.host, self.port),
- timeout=self.timeout,
- )
+ address=(self.host, self.port), timeout=self.timeout,
+ **self.conn_kw)
except SocketTimeout:
raise ConnectTimeoutError(
self, "Connection to %s timed out. (connect timeout=%s)" %
@@ -146,21 +168,25 @@ class VerifiedHTTPSConnection(HTTPSConnection):
resolved_cert_reqs = resolve_cert_reqs(self.cert_reqs)
resolved_ssl_version = resolve_ssl_version(self.ssl_version)
- # the _tunnel_host attribute was added in python 2.6.3 (via
- # http://hg.python.org/cpython/rev/0f57b30a152f) so pythons 2.6(0-2) do
- # not have them.
+ hostname = self.host
if getattr(self, '_tunnel_host', None):
+ # _tunnel_host was added in Python 2.6.3
+ # (See: http://hg.python.org/cpython/rev/0f57b30a152f)
+
self.sock = sock
# Calls self._set_hostport(), so self.host is
# self._tunnel_host below.
self._tunnel()
+ # Override the host with the one we're requesting data from.
+ hostname = self._tunnel_host
+
# Wrap socket using verification with the root certs in
# trusted_root_certs
self.sock = ssl_wrap_socket(sock, self.key_file, self.cert_file,
cert_reqs=resolved_cert_reqs,
ca_certs=self.ca_certs,
- server_hostname=self.host,
+ server_hostname=hostname,
ssl_version=resolved_ssl_version)
if resolved_cert_reqs != ssl.CERT_NONE:
@@ -169,7 +195,7 @@ class VerifiedHTTPSConnection(HTTPSConnection):
self.assert_fingerprint)
elif self.assert_hostname is not False:
match_hostname(self.sock.getpeercert(),
- self.assert_hostname or self.host)
+ self.assert_hostname or hostname)
if ssl:
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py
similarity index 89%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py
index 243d700..95a53a7 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/connectionpool.py
@@ -4,6 +4,7 @@
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
+import sys
import errno
import logging
@@ -19,9 +20,11 @@ except ImportError:
from .exceptions import (
ClosedPoolError,
+ ConnectionError,
ConnectTimeoutError,
EmptyPoolError,
HostChangedError,
+ LocationParseError,
MaxRetryError,
SSLError,
TimeoutError,
@@ -39,7 +42,6 @@ from .connection import (
from .request import RequestMethods
from .response import HTTPResponse
from .util import (
- assert_fingerprint,
get_host,
is_connection_dropped,
Timeout,
@@ -64,6 +66,9 @@ class ConnectionPool(object):
QueueCls = LifoQueue
def __init__(self, host, port=None):
+ if host is None:
+ raise LocationParseError(host)
+
# httplib doesn't like it when we include brackets in ipv6 addresses
host = host.strip('[]')
@@ -135,7 +140,7 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
def __init__(self, host, port=None, strict=False,
timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,
- headers=None, _proxy=None, _proxy_headers=None):
+ headers=None, _proxy=None, _proxy_headers=None, **conn_kw):
ConnectionPool.__init__(self, host, port)
RequestMethods.__init__(self, headers)
@@ -162,6 +167,10 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
self.num_connections = 0
self.num_requests = 0
+ if sys.version_info < (2, 7): # Python 2.6 and older
+ conn_kw.pop('source_address', None)
+ self.conn_kw = conn_kw
+
def _new_conn(self):
"""
Return a fresh :class:`HTTPConnection`.
@@ -170,13 +179,9 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
log.info("Starting new HTTP connection (%d): %s" %
(self.num_connections, self.host))
- extra_params = {}
- if not six.PY3: # Python 2
- extra_params['strict'] = self.strict
-
conn = self.ConnectionCls(host=self.host, port=self.port,
timeout=self.timeout.connect_timeout,
- **extra_params)
+ strict=self.strict, **self.conn_kw)
if self.proxy is not None:
# Enable Nagle's algorithm for proxies, to avoid packet
# fragmentation.
@@ -238,8 +243,9 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
pass
except Full:
# This should never happen if self.block == True
- log.warning("HttpConnectionPool is full, discarding connection: %s"
- % self.host)
+ log.warning(
+ "Connection pool is full, discarding connection: %s" %
+ self.host)
# Connection never got put back into the pool, close it.
if conn:
@@ -414,10 +420,13 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
:param retries:
Number of retries to allow before raising a MaxRetryError exception.
+ If `False`, then retries are disabled and any exception is raised
+ immediately.
:param redirect:
If True, automatically handle redirects (status codes 301, 302,
- 303, 307, 308). Each redirect counts as a retry.
+ 303, 307, 308). Each redirect counts as a retry. Disabling retries
+ will disable redirect, too.
:param assert_same_host:
If ``True``, will make sure that the host of the pool requests is
@@ -451,7 +460,7 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
if headers is None:
headers = self.headers
- if retries < 0:
+ if retries < 0 and retries is not False:
raise MaxRetryError(self, url)
if release_conn is None:
@@ -470,6 +479,10 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
headers = headers.copy()
headers.update(self.proxy_headers)
+ # Must keep the exception bound to a separate variable or else Python 3
+ # complains about UnboundLocalError.
+ err = None
+
try:
# Request a connection from the queue
conn = self._get_conn(timeout=pool_timeout)
@@ -497,38 +510,41 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
# ``response.read()``)
except Empty:
- # Timed out by queue
+ # Timed out by queue.
raise EmptyPoolError(self, "No pool connections are available.")
- except BaseSSLError as e:
+ except (BaseSSLError, CertificateError) as e:
+ # Release connection unconditionally because there is no way to
+ # close it externally in case of exception.
+ release_conn = True
raise SSLError(e)
- except CertificateError as e:
- # Name mismatch
- raise SSLError(e)
+ except (TimeoutError, HTTPException, SocketError) as e:
+ if conn:
+ # Discard the connection for these exceptions. It will be
+ # be replaced during the next _get_conn() call.
+ conn.close()
+ conn = None
- except TimeoutError as e:
- # Connection broken, discard.
- conn = None
- # Save the error off for retry logic.
+ if not retries:
+ if isinstance(e, TimeoutError):
+ # TimeoutError is exempt from MaxRetryError-wrapping.
+ # FIXME: ... Not sure why. Add a reason here.
+ raise
+
+ # Wrap unexpected exceptions with the most appropriate
+ # module-level exception and re-raise.
+ if isinstance(e, SocketError) and self.proxy:
+ raise ProxyError('Cannot connect to proxy.', e)
+
+ if retries is False:
+ raise ConnectionError('Connection failed.', e)
+
+ raise MaxRetryError(self, url, e)
+
+ # Keep track of the error for the retry warning.
err = e
- if retries == 0:
- raise
-
- except (HTTPException, SocketError) as e:
- # Connection broken, discard. It will be replaced next _get_conn().
- conn = None
- # This is necessary so we can access e below
- err = e
-
- if retries == 0:
- if isinstance(e, SocketError) and self.proxy is not None:
- raise ProxyError('Cannot connect to proxy. '
- 'Socket error: %s.' % e)
- else:
- raise MaxRetryError(self, url, e)
-
finally:
if release_conn:
# Put the connection back to be reused. If the connection is
@@ -538,8 +554,8 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
if not conn:
# Try again
- log.warn("Retrying (%d attempts remain) after connection "
- "broken by '%r': %s" % (retries, err, url))
+ log.warning("Retrying (%d attempts remain) after connection "
+ "broken by '%r': %s" % (retries, err, url))
return self.urlopen(method, url, body, headers, retries - 1,
redirect, assert_same_host,
timeout=timeout, pool_timeout=pool_timeout,
@@ -547,7 +563,7 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
# Handle redirect?
redirect_location = redirect and response.get_redirect_location()
- if redirect_location:
+ if redirect_location and retries is not False:
if response.status == 303:
method = 'GET'
log.info("Redirecting %s -> %s" % (url, redirect_location))
@@ -586,10 +602,14 @@ class HTTPSConnectionPool(HTTPConnectionPool):
_proxy=None, _proxy_headers=None,
key_file=None, cert_file=None, cert_reqs=None,
ca_certs=None, ssl_version=None,
- assert_hostname=None, assert_fingerprint=None):
+ assert_hostname=None, assert_fingerprint=None,
+ **conn_kw):
+
+ if sys.version_info < (2, 7): # Python 2.6 or older
+ conn_kw.pop('source_address', None)
HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,
- block, headers, _proxy, _proxy_headers)
+ block, headers, _proxy, _proxy_headers, **conn_kw)
self.key_file = key_file
self.cert_file = cert_file
self.cert_reqs = cert_reqs
@@ -597,6 +617,7 @@ class HTTPSConnectionPool(HTTPConnectionPool):
self.ssl_version = ssl_version
self.assert_hostname = assert_hostname
self.assert_fingerprint = assert_fingerprint
+ self.conn_kw = conn_kw
def _prepare_conn(self, conn):
"""
@@ -612,6 +633,7 @@ class HTTPSConnectionPool(HTTPConnectionPool):
assert_hostname=self.assert_hostname,
assert_fingerprint=self.assert_fingerprint)
conn.ssl_version = self.ssl_version
+ conn.conn_kw = self.conn_kw
if self.proxy is not None:
# Python 2.7+
@@ -648,6 +670,7 @@ class HTTPSConnectionPool(HTTPConnectionPool):
extra_params = {}
if not six.PY3: # Python 2
extra_params['strict'] = self.strict
+ extra_params.update(self.conn_kw)
conn = self.ConnectionCls(host=actual_host, port=actual_port,
timeout=self.timeout.connect_timeout,
diff --git a/Darwin/lib/python2.7/site-packages/flask/testsuite/test_apps/moduleapp/apps/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/flask/testsuite/test_apps/moduleapp/apps/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/ntlmpool.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/ntlmpool.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/ntlmpool.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/ntlmpool.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py
similarity index 86%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py
index d9bda15..21a12c6 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/contrib/pyopenssl.py
@@ -1,4 +1,7 @@
-'''SSL with SNI_-support for Python 2.
+'''SSL with SNI_-support for Python 2. Follow these instructions if you would
+like to verify SSL certificates in Python 2. Note, the default libraries do
+*not* do certificate checking; you need to do additional work to validate
+certificates yourself.
This needs the following packages installed:
@@ -6,9 +9,15 @@ This needs the following packages installed:
* ndg-httpsclient (tested with 0.3.2)
* pyasn1 (tested with 0.1.6)
-To activate it call :func:`~urllib3.contrib.pyopenssl.inject_into_urllib3`.
-This can be done in a ``sitecustomize`` module, or at any other time before
-your application begins using ``urllib3``, like this::
+You can install them with the following command:
+
+ pip install pyopenssl ndg-httpsclient pyasn1
+
+To activate certificate checking, call
+:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code
+before you begin making HTTP requests. This can be done in a ``sitecustomize``
+module, or at any other time before your application begins using ``urllib3``,
+like this::
try:
import urllib3.contrib.pyopenssl
@@ -29,9 +38,8 @@ Module Variables
----------------
:var DEFAULT_SSL_CIPHER_LIST: The list of supported SSL/TLS cipher suites.
- Default: ``EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA256
- EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EDH+aRSA EECDH RC4 !aNULL !eNULL !LOW !3DES
- !MD5 !EXP !PSK !SRP !DSS'``
+ Default: ``ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:
+ ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS``
.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication
.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)
@@ -43,7 +51,7 @@ from ndg.httpsclient.subj_alt_name import SubjectAltName as BaseSubjectAltName
import OpenSSL.SSL
from pyasn1.codec.der import decoder as der_decoder
from pyasn1.type import univ, constraint
-from socket import _fileobject
+from socket import _fileobject, timeout
import ssl
import select
from cStringIO import StringIO
@@ -69,12 +77,22 @@ _openssl_verify = {
+ OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
}
-# Default SSL/TLS cipher list.
-# Recommendation by https://community.qualys.com/blogs/securitylabs/2013/08/05/
-# configuring-apache-nginx-and-openssl-for-forward-secrecy
-DEFAULT_SSL_CIPHER_LIST = 'EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM ' + \
- 'EECDH+ECDSA+SHA256 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EDH+aRSA ' + \
- 'EECDH RC4 !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS'
+# A secure default.
+# Sources for more information on TLS ciphers:
+#
+# - https://wiki.mozilla.org/Security/Server_Side_TLS
+# - https://www.ssllabs.com/projects/best-practices/index.html
+# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
+#
+# The general intent is:
+# - Prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
+# - prefer ECDHE over DHE for better performance,
+# - prefer any AES-GCM over any AES-CBC for better performance and security,
+# - use 3DES as fallback which is secure but slow,
+# - disable NULL authentication, MD5 MACs and DSS for security reasons.
+DEFAULT_SSL_CIPHER_LIST = "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:" + \
+ "ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:" + \
+ "!aNULL:!MD5:!DSS"
orig_util_HAS_SNI = util.HAS_SNI
@@ -139,6 +157,13 @@ def get_subj_alt_name(peer_cert):
class fileobject(_fileobject):
+ def _wait_for_sock(self):
+ rd, wd, ed = select.select([self._sock], [], [],
+ self._sock.gettimeout())
+ if not rd:
+ raise timeout()
+
+
def read(self, size=-1):
# Use max, disallow tiny reads in a loop as they are very inefficient.
# We never leave read() with any leftover data from a new recv() call
@@ -156,6 +181,7 @@ class fileobject(_fileobject):
try:
data = self._sock.recv(rbufsize)
except OpenSSL.SSL.WantReadError:
+ self._wait_for_sock()
continue
if not data:
break
@@ -183,6 +209,7 @@ class fileobject(_fileobject):
try:
data = self._sock.recv(left)
except OpenSSL.SSL.WantReadError:
+ self._wait_for_sock()
continue
if not data:
break
@@ -234,6 +261,7 @@ class fileobject(_fileobject):
break
buffers.append(data)
except OpenSSL.SSL.WantReadError:
+ self._wait_for_sock()
continue
break
return "".join(buffers)
@@ -244,6 +272,7 @@ class fileobject(_fileobject):
try:
data = self._sock.recv(self._rbufsize)
except OpenSSL.SSL.WantReadError:
+ self._wait_for_sock()
continue
if not data:
break
@@ -271,7 +300,8 @@ class fileobject(_fileobject):
try:
data = self._sock.recv(self._rbufsize)
except OpenSSL.SSL.WantReadError:
- continue
+ self._wait_for_sock()
+ continue
if not data:
break
left = size - buf_len
@@ -366,6 +396,8 @@ def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ctx.load_verify_locations(ca_certs, None)
except OpenSSL.SSL.Error as e:
raise ssl.SSLError('bad ca_certs: %r' % ca_certs, e)
+ else:
+ ctx.set_default_verify_paths()
# Disable TLS compression to migitate CRIME attack (issue #309)
OP_NO_COMPRESSION = 0x20000
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/exceptions.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/exceptions.py
similarity index 97%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/exceptions.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/exceptions.py
index 98ef9ab..b4df831 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/exceptions.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/exceptions.py
@@ -44,6 +44,11 @@ class ProxyError(HTTPError):
pass
+class ConnectionError(HTTPError):
+ "Raised when a normal connection fails."
+ pass
+
+
class DecodeError(HTTPError):
"Raised when automatic decoding based on Content-Type fails."
pass
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/fields.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/fields.py
similarity index 99%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/fields.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/fields.py
index ed01765..da79e92 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/fields.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/fields.py
@@ -15,7 +15,7 @@ def guess_content_type(filename, default='application/octet-stream'):
Guess the "Content-Type" of a file.
:param filename:
- The filename to guess the "Content-Type" of using :mod:`mimetimes`.
+ The filename to guess the "Content-Type" of using :mod:`mimetypes`.
:param default:
If no "Content-Type" can be guessed, default to `default`.
"""
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/filepost.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/filepost.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/filepost.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/filepost.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/six.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/six.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/six.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/six.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py
similarity index 84%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py
index 3aa5b2e..dd59a75 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py
@@ -7,7 +7,7 @@ except ImportError:
from backports.ssl_match_hostname import CertificateError, match_hostname
except ImportError:
# Our vendored copy
- from _implementation import CertificateError, match_hostname
+ from ._implementation import CertificateError, match_hostname
# Not needed, but documenting what we provide.
__all__ = ('CertificateError', 'match_hostname')
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/poolmanager.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/poolmanager.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/poolmanager.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/poolmanager.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/request.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/request.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/request.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/request.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/response.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/response.py
similarity index 96%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/response.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/response.py
index 6a1fe1a..db44182 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/packages/urllib3/response.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/response.py
@@ -9,6 +9,7 @@ import logging
import zlib
import io
+from ._collections import HTTPHeaderDict
from .exceptions import DecodeError
from .packages.six import string_types as basestring, binary_type
from .util import is_fp_closed
@@ -79,7 +80,10 @@ class HTTPResponse(io.IOBase):
def __init__(self, body='', headers=None, status=0, version=0, reason=None,
strict=0, preload_content=True, decode_content=True,
original_response=None, pool=None, connection=None):
- self.headers = headers or {}
+
+ self.headers = HTTPHeaderDict()
+ if headers:
+ self.headers.update(headers)
self.status = status
self.version = version
self.reason = reason
@@ -249,17 +253,9 @@ class HTTPResponse(io.IOBase):
with ``original_response=r``.
"""
- # Normalize headers between different versions of Python
- headers = {}
+ headers = HTTPHeaderDict()
for k, v in r.getheaders():
- # Python 3: Header keys are returned capitalised
- k = k.lower()
-
- has_value = headers.get(k)
- if has_value: # Python 3: Repeating header keys are unmerged.
- v = ', '.join([has_value, v])
-
- headers[k] = v
+ headers.add(k, v)
# HTTPResponse objects in Python 3 don't have a .strict attribute
strict = getattr(r, 'strict', 0)
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/__init__.py
new file mode 100644
index 0000000..a40185e
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/__init__.py
@@ -0,0 +1,27 @@
+# urllib3/util/__init__.py
+# Copyright 2008-2014 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
+#
+# This module is part of urllib3 and is released under
+# the MIT License: http://www.opensource.org/licenses/mit-license.php
+
+from .connection import is_connection_dropped
+from .request import make_headers
+from .response import is_fp_closed
+from .ssl_ import (
+ SSLContext,
+ HAS_SNI,
+ assert_fingerprint,
+ resolve_cert_reqs,
+ resolve_ssl_version,
+ ssl_wrap_socket,
+)
+from .timeout import (
+ current_time,
+ Timeout,
+)
+from .url import (
+ get_host,
+ parse_url,
+ split_first,
+ Url,
+)
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/connection.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/connection.py
new file mode 100644
index 0000000..8deeab5
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/connection.py
@@ -0,0 +1,45 @@
+from socket import error as SocketError
+try:
+ from select import poll, POLLIN
+except ImportError: # `poll` doesn't exist on OSX and other platforms
+ poll = False
+ try:
+ from select import select
+ except ImportError: # `select` doesn't exist on AppEngine.
+ select = False
+
+def is_connection_dropped(conn): # Platform-specific
+ """
+ Returns True if the connection is dropped and should be closed.
+
+ :param conn:
+ :class:`httplib.HTTPConnection` object.
+
+ Note: For platforms like AppEngine, this will always return ``False`` to
+ let the platform handle connection recycling transparently for us.
+ """
+ sock = getattr(conn, 'sock', False)
+ if sock is False: # Platform-specific: AppEngine
+ return False
+ if sock is None: # Connection already closed (such as by httplib).
+ return False
+
+ if not poll:
+ if not select: # Platform-specific: AppEngine
+ return False
+
+ try:
+ return select([sock], [], [], 0.0)[0]
+ except SocketError:
+ return True
+
+ # This version is better on platforms that support it.
+ p = poll()
+ p.register(sock, POLLIN)
+ for (fno, ev) in p.poll(0.0):
+ if fno == sock.fileno():
+ # Either data is buffered (bad), or the connection is dropped.
+ return True
+
+
+
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/request.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/request.py
new file mode 100644
index 0000000..d48d651
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/request.py
@@ -0,0 +1,68 @@
+from base64 import b64encode
+
+from ..packages import six
+
+
+ACCEPT_ENCODING = 'gzip,deflate'
+
+
+def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
+ basic_auth=None, proxy_basic_auth=None):
+ """
+ Shortcuts for generating request headers.
+
+ :param keep_alive:
+ If ``True``, adds 'connection: keep-alive' header.
+
+ :param accept_encoding:
+ Can be a boolean, list, or string.
+ ``True`` translates to 'gzip,deflate'.
+ List will get joined by comma.
+ String will be used as provided.
+
+ :param user_agent:
+ String representing the user-agent you want, such as
+ "python-urllib3/0.6"
+
+ :param basic_auth:
+ Colon-separated username:password string for 'authorization: basic ...'
+ auth header.
+
+ :param proxy_basic_auth:
+ Colon-separated username:password string for 'proxy-authorization: basic ...'
+ auth header.
+
+ Example: ::
+
+ >>> make_headers(keep_alive=True, user_agent="Batman/1.0")
+ {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
+ >>> make_headers(accept_encoding=True)
+ {'accept-encoding': 'gzip,deflate'}
+ """
+ headers = {}
+ if accept_encoding:
+ if isinstance(accept_encoding, str):
+ pass
+ elif isinstance(accept_encoding, list):
+ accept_encoding = ','.join(accept_encoding)
+ else:
+ accept_encoding = ACCEPT_ENCODING
+ headers['accept-encoding'] = accept_encoding
+
+ if user_agent:
+ headers['user-agent'] = user_agent
+
+ if keep_alive:
+ headers['connection'] = 'keep-alive'
+
+ if basic_auth:
+ headers['authorization'] = 'Basic ' + \
+ b64encode(six.b(basic_auth)).decode('utf-8')
+
+ if proxy_basic_auth:
+ headers['proxy-authorization'] = 'Basic ' + \
+ b64encode(six.b(proxy_basic_auth)).decode('utf-8')
+
+ return headers
+
+
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/response.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/response.py
new file mode 100644
index 0000000..d0325bc
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/response.py
@@ -0,0 +1,13 @@
+def is_fp_closed(obj):
+ """
+ Checks whether a given file-like object is closed.
+
+ :param obj:
+ The file-like object to check.
+ """
+ if hasattr(obj, 'fp'):
+ # Object is a container for another file-like object that gets released
+ # on exhaustion (e.g. HTTPResponse)
+ return obj.fp is None
+
+ return obj.closed
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py
new file mode 100644
index 0000000..dee4b87
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/ssl_.py
@@ -0,0 +1,133 @@
+from binascii import hexlify, unhexlify
+from hashlib import md5, sha1
+
+from ..exceptions import SSLError
+
+
+try: # Test for SSL features
+ SSLContext = None
+ HAS_SNI = False
+
+ import ssl
+ from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
+ from ssl import SSLContext # Modern SSL?
+ from ssl import HAS_SNI # Has SNI?
+except ImportError:
+ pass
+
+
+def assert_fingerprint(cert, fingerprint):
+ """
+ Checks if given fingerprint matches the supplied certificate.
+
+ :param cert:
+ Certificate as bytes object.
+ :param fingerprint:
+ Fingerprint as string of hexdigits, can be interspersed by colons.
+ """
+
+ # Maps the length of a digest to a possible hash function producing
+ # this digest.
+ hashfunc_map = {
+ 16: md5,
+ 20: sha1
+ }
+
+ fingerprint = fingerprint.replace(':', '').lower()
+
+ digest_length, rest = divmod(len(fingerprint), 2)
+
+ if rest or digest_length not in hashfunc_map:
+ raise SSLError('Fingerprint is of invalid length.')
+
+ # We need encode() here for py32; works on py2 and p33.
+ fingerprint_bytes = unhexlify(fingerprint.encode())
+
+ hashfunc = hashfunc_map[digest_length]
+
+ cert_digest = hashfunc(cert).digest()
+
+ if not cert_digest == fingerprint_bytes:
+ raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
+ .format(hexlify(fingerprint_bytes),
+ hexlify(cert_digest)))
+
+
+def resolve_cert_reqs(candidate):
+ """
+ Resolves the argument to a numeric constant, which can be passed to
+ the wrap_socket function/method from the ssl module.
+ Defaults to :data:`ssl.CERT_NONE`.
+ If given a string it is assumed to be the name of the constant in the
+ :mod:`ssl` module or its abbrevation.
+ (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
+ If it's neither `None` nor a string we assume it is already the numeric
+ constant which can directly be passed to wrap_socket.
+ """
+ if candidate is None:
+ return CERT_NONE
+
+ if isinstance(candidate, str):
+ res = getattr(ssl, candidate, None)
+ if res is None:
+ res = getattr(ssl, 'CERT_' + candidate)
+ return res
+
+ return candidate
+
+
+def resolve_ssl_version(candidate):
+ """
+ like resolve_cert_reqs
+ """
+ if candidate is None:
+ return PROTOCOL_SSLv23
+
+ if isinstance(candidate, str):
+ res = getattr(ssl, candidate, None)
+ if res is None:
+ res = getattr(ssl, 'PROTOCOL_' + candidate)
+ return res
+
+ return candidate
+
+
+if SSLContext is not None: # Python 3.2+
+ def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
+ ca_certs=None, server_hostname=None,
+ ssl_version=None):
+ """
+ All arguments except `server_hostname` have the same meaning as for
+ :func:`ssl.wrap_socket`
+
+ :param server_hostname:
+ Hostname of the expected certificate
+ """
+ context = SSLContext(ssl_version)
+ context.verify_mode = cert_reqs
+
+ # Disable TLS compression to migitate CRIME attack (issue #309)
+ OP_NO_COMPRESSION = 0x20000
+ context.options |= OP_NO_COMPRESSION
+
+ if ca_certs:
+ try:
+ context.load_verify_locations(ca_certs)
+ # Py32 raises IOError
+ # Py33 raises FileNotFoundError
+ except Exception as e: # Reraise as SSLError
+ raise SSLError(e)
+ if certfile:
+ # FIXME: This block needs a test.
+ context.load_cert_chain(certfile, keyfile)
+ if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
+ return context.wrap_socket(sock, server_hostname=server_hostname)
+ return context.wrap_socket(sock)
+
+else: # Python 3.1 and earlier
+ def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
+ ca_certs=None, server_hostname=None,
+ ssl_version=None):
+ return wrap_socket(sock, keyfile=keyfile, certfile=certfile,
+ ca_certs=ca_certs, cert_reqs=cert_reqs,
+ ssl_version=ssl_version)
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/timeout.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/timeout.py
new file mode 100644
index 0000000..4f947cb
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/timeout.py
@@ -0,0 +1,234 @@
+from socket import _GLOBAL_DEFAULT_TIMEOUT
+import time
+
+from ..exceptions import TimeoutStateError
+
+
+def current_time():
+ """
+ Retrieve the current time, this function is mocked out in unit testing.
+ """
+ return time.time()
+
+
+_Default = object()
+# The default timeout to use for socket connections. This is the attribute used
+# by httplib to define the default timeout
+
+
+class Timeout(object):
+ """
+ Utility object for storing timeout values.
+
+ Example usage:
+
+ .. code-block:: python
+
+ timeout = urllib3.util.Timeout(connect=2.0, read=7.0)
+ pool = HTTPConnectionPool('www.google.com', 80, timeout=timeout)
+ pool.request(...) # Etc, etc
+
+ :param connect:
+ The maximum amount of time to wait for a connection attempt to a server
+ to succeed. Omitting the parameter will default the connect timeout to
+ the system default, probably `the global default timeout in socket.py
+ `_.
+ None will set an infinite timeout for connection attempts.
+
+ :type connect: integer, float, or None
+
+ :param read:
+ The maximum amount of time to wait between consecutive
+ read operations for a response from the server. Omitting
+ the parameter will default the read timeout to the system
+ default, probably `the global default timeout in socket.py
+ `_.
+ None will set an infinite timeout.
+
+ :type read: integer, float, or None
+
+ :param total:
+ This combines the connect and read timeouts into one; the read timeout
+ will be set to the time leftover from the connect attempt. In the
+ event that both a connect timeout and a total are specified, or a read
+ timeout and a total are specified, the shorter timeout will be applied.
+
+ Defaults to None.
+
+ :type total: integer, float, or None
+
+ .. note::
+
+ Many factors can affect the total amount of time for urllib3 to return
+ an HTTP response. Specifically, Python's DNS resolver does not obey the
+ timeout specified on the socket. Other factors that can affect total
+ request time include high CPU load, high swap, the program running at a
+ low priority level, or other behaviors. The observed running time for
+ urllib3 to return a response may be greater than the value passed to
+ `total`.
+
+ In addition, the read and total timeouts only measure the time between
+ read operations on the socket connecting the client and the server,
+ not the total amount of time for the request to return a complete
+ response. For most requests, the timeout is raised because the server
+ has not sent the first byte in the specified time. This is not always
+ the case; if a server streams one byte every fifteen seconds, a timeout
+ of 20 seconds will not ever trigger, even though the request will
+ take several minutes to complete.
+
+ If your goal is to cut off any request after a set amount of wall clock
+ time, consider having a second "watcher" thread to cut off a slow
+ request.
+ """
+
+ #: A sentinel object representing the default timeout value
+ DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT
+
+ def __init__(self, total=None, connect=_Default, read=_Default):
+ self._connect = self._validate_timeout(connect, 'connect')
+ self._read = self._validate_timeout(read, 'read')
+ self.total = self._validate_timeout(total, 'total')
+ self._start_connect = None
+
+ def __str__(self):
+ return '%s(connect=%r, read=%r, total=%r)' % (
+ type(self).__name__, self._connect, self._read, self.total)
+
+
+ @classmethod
+ def _validate_timeout(cls, value, name):
+ """ Check that a timeout attribute is valid
+
+ :param value: The timeout value to validate
+ :param name: The name of the timeout attribute to validate. This is used
+ for clear error messages
+ :return: the value
+ :raises ValueError: if the type is not an integer or a float, or if it
+ is a numeric value less than zero
+ """
+ if value is _Default:
+ return cls.DEFAULT_TIMEOUT
+
+ if value is None or value is cls.DEFAULT_TIMEOUT:
+ return value
+
+ try:
+ float(value)
+ except (TypeError, ValueError):
+ raise ValueError("Timeout value %s was %s, but it must be an "
+ "int or float." % (name, value))
+
+ try:
+ if value < 0:
+ raise ValueError("Attempted to set %s timeout to %s, but the "
+ "timeout cannot be set to a value less "
+ "than 0." % (name, value))
+ except TypeError: # Python 3
+ raise ValueError("Timeout value %s was %s, but it must be an "
+ "int or float." % (name, value))
+
+ return value
+
+ @classmethod
+ def from_float(cls, timeout):
+ """ Create a new Timeout from a legacy timeout value.
+
+ The timeout value used by httplib.py sets the same timeout on the
+ connect(), and recv() socket requests. This creates a :class:`Timeout`
+ object that sets the individual timeouts to the ``timeout`` value passed
+ to this function.
+
+ :param timeout: The legacy timeout value
+ :type timeout: integer, float, sentinel default object, or None
+ :return: a Timeout object
+ :rtype: :class:`Timeout`
+ """
+ return Timeout(read=timeout, connect=timeout)
+
+ def clone(self):
+ """ Create a copy of the timeout object
+
+ Timeout properties are stored per-pool but each request needs a fresh
+ Timeout object to ensure each one has its own start/stop configured.
+
+ :return: a copy of the timeout object
+ :rtype: :class:`Timeout`
+ """
+ # We can't use copy.deepcopy because that will also create a new object
+ # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to
+ # detect the user default.
+ return Timeout(connect=self._connect, read=self._read,
+ total=self.total)
+
+ def start_connect(self):
+ """ Start the timeout clock, used during a connect() attempt
+
+ :raises urllib3.exceptions.TimeoutStateError: if you attempt
+ to start a timer that has been started already.
+ """
+ if self._start_connect is not None:
+ raise TimeoutStateError("Timeout timer has already been started.")
+ self._start_connect = current_time()
+ return self._start_connect
+
+ def get_connect_duration(self):
+ """ Gets the time elapsed since the call to :meth:`start_connect`.
+
+ :return: the elapsed time
+ :rtype: float
+ :raises urllib3.exceptions.TimeoutStateError: if you attempt
+ to get duration for a timer that hasn't been started.
+ """
+ if self._start_connect is None:
+ raise TimeoutStateError("Can't get connect duration for timer "
+ "that has not started.")
+ return current_time() - self._start_connect
+
+ @property
+ def connect_timeout(self):
+ """ Get the value to use when setting a connection timeout.
+
+ This will be a positive float or integer, the value None
+ (never timeout), or the default system timeout.
+
+ :return: the connect timeout
+ :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
+ """
+ if self.total is None:
+ return self._connect
+
+ if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
+ return self.total
+
+ return min(self._connect, self.total)
+
+ @property
+ def read_timeout(self):
+ """ Get the value for the read timeout.
+
+ This assumes some time has elapsed in the connection timeout and
+ computes the read timeout appropriately.
+
+ If self.total is set, the read timeout is dependent on the amount of
+ time taken by the connect timeout. If the connection time has not been
+ established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
+ raised.
+
+ :return: the value to use for the read timeout
+ :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
+ :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
+ has not yet been called on this object.
+ """
+ if (self.total is not None and
+ self.total is not self.DEFAULT_TIMEOUT and
+ self._read is not None and
+ self._read is not self.DEFAULT_TIMEOUT):
+ # in case the connect timeout has not yet been established.
+ if self._start_connect is None:
+ return self._read
+ return max(0, min(self.total - self.get_connect_duration(),
+ self._read))
+ elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:
+ return max(0, self.total - self.get_connect_duration())
+ else:
+ return self._read
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/url.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/url.py
new file mode 100644
index 0000000..362d216
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/packages/urllib3/util/url.py
@@ -0,0 +1,162 @@
+from collections import namedtuple
+
+from ..exceptions import LocationParseError
+
+
+class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):
+ """
+ Datastructure for representing an HTTP URL. Used as a return value for
+ :func:`parse_url`.
+ """
+ slots = ()
+
+ def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None):
+ return super(Url, cls).__new__(cls, scheme, auth, host, port, path, query, fragment)
+
+ @property
+ def hostname(self):
+ """For backwards-compatibility with urlparse. We're nice like that."""
+ return self.host
+
+ @property
+ def request_uri(self):
+ """Absolute path including the query string."""
+ uri = self.path or '/'
+
+ if self.query is not None:
+ uri += '?' + self.query
+
+ return uri
+
+ @property
+ def netloc(self):
+ """Network location including host and port"""
+ if self.port:
+ return '%s:%d' % (self.host, self.port)
+ return self.host
+
+
+def split_first(s, delims):
+ """
+ Given a string and an iterable of delimiters, split on the first found
+ delimiter. Return two split parts and the matched delimiter.
+
+ If not found, then the first part is the full input string.
+
+ Example: ::
+
+ >>> split_first('foo/bar?baz', '?/=')
+ ('foo', 'bar?baz', '/')
+ >>> split_first('foo/bar?baz', '123')
+ ('foo/bar?baz', '', None)
+
+ Scales linearly with number of delims. Not ideal for large number of delims.
+ """
+ min_idx = None
+ min_delim = None
+ for d in delims:
+ idx = s.find(d)
+ if idx < 0:
+ continue
+
+ if min_idx is None or idx < min_idx:
+ min_idx = idx
+ min_delim = d
+
+ if min_idx is None or min_idx < 0:
+ return s, '', None
+
+ return s[:min_idx], s[min_idx+1:], min_delim
+
+
+def parse_url(url):
+ """
+ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
+ performed to parse incomplete urls. Fields not provided will be None.
+
+ Partly backwards-compatible with :mod:`urlparse`.
+
+ Example: ::
+
+ >>> parse_url('http://google.com/mail/')
+ Url(scheme='http', host='google.com', port=None, path='/', ...)
+ >>> parse_url('google.com:80')
+ Url(scheme=None, host='google.com', port=80, path=None, ...)
+ >>> parse_url('/foo?bar')
+ Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
+ """
+
+ # While this code has overlap with stdlib's urlparse, it is much
+ # simplified for our needs and less annoying.
+ # Additionally, this implementations does silly things to be optimal
+ # on CPython.
+
+ scheme = None
+ auth = None
+ host = None
+ port = None
+ path = None
+ fragment = None
+ query = None
+
+ # Scheme
+ if '://' in url:
+ scheme, url = url.split('://', 1)
+
+ # Find the earliest Authority Terminator
+ # (http://tools.ietf.org/html/rfc3986#section-3.2)
+ url, path_, delim = split_first(url, ['/', '?', '#'])
+
+ if delim:
+ # Reassemble the path
+ path = delim + path_
+
+ # Auth
+ if '@' in url:
+ # Last '@' denotes end of auth part
+ auth, url = url.rsplit('@', 1)
+
+ # IPv6
+ if url and url[0] == '[':
+ host, url = url.split(']', 1)
+ host += ']'
+
+ # Port
+ if ':' in url:
+ _host, port = url.split(':', 1)
+
+ if not host:
+ host = _host
+
+ if port:
+ # If given, ports must be integers.
+ if not port.isdigit():
+ raise LocationParseError(url)
+ port = int(port)
+ else:
+ # Blank ports are cool, too. (rfc3986#section-3.2.3)
+ port = None
+
+ elif not host and url:
+ host = url
+
+ if not path:
+ return Url(scheme, auth, host, port, path, query, fragment)
+
+ # Fragment
+ if '#' in path:
+ path, fragment = path.split('#', 1)
+
+ # Query
+ if '?' in path:
+ path, query = path.split('?', 1)
+
+ return Url(scheme, auth, host, port, path, query, fragment)
+
+
+def get_host(url):
+ """
+ Deprecated. Use :func:`.parse_url` instead.
+ """
+ p = parse_url(url)
+ return p.scheme or 'http', p.hostname, p.port
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/sessions.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/sessions.py
similarity index 82%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/sessions.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/sessions.py
index db227ca..df85a25 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/sessions.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/sessions.py
@@ -12,27 +12,28 @@ import os
from collections import Mapping
from datetime import datetime
+from .auth import _basic_auth_str
from .compat import cookielib, OrderedDict, urljoin, urlparse, builtin_str
from .cookies import (
cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)
-from .models import Request, PreparedRequest
+from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT
from .hooks import default_hooks, dispatch_hook
-from .utils import to_key_val_list, default_headers
-from .exceptions import TooManyRedirects, InvalidSchema
+from .utils import to_key_val_list, default_headers, to_native_string
+from .exceptions import (
+ TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError)
from .structures import CaseInsensitiveDict
from .adapters import HTTPAdapter
-from .utils import requote_uri, get_environ_proxies, get_netrc_auth
+from .utils import (
+ requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,
+ get_auth_from_url
+)
from .status_codes import codes
-REDIRECT_STATI = (
- codes.moved, # 301
- codes.found, # 302
- codes.other, # 303
- codes.temporary_moved, # 307
-)
-DEFAULT_REDIRECT_LIMIT = 30
+
+# formerly defined here, reexposed here for backward compatibility
+from .models import REDIRECT_STATI
def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
@@ -63,6 +64,8 @@ def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
if v is None:
del merged_setting[k]
+ merged_setting = dict((k, v) for (k, v) in merged_setting.items() if v is not None)
+
return merged_setting
@@ -89,11 +92,13 @@ class SessionRedirectMixin(object):
i = 0
- # ((resp.status_code is codes.see_other))
- while ('location' in resp.headers and resp.status_code in REDIRECT_STATI):
+ while resp.is_redirect:
prepared_request = req.copy()
- resp.content # Consume socket so it can be released
+ try:
+ resp.content # Consume socket so it can be released
+ except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
+ resp.raw.read(decode_content=False)
if i >= self.max_redirects:
raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects)
@@ -121,7 +126,7 @@ class SessionRedirectMixin(object):
else:
url = requote_uri(url)
- prepared_request.url = url
+ prepared_request.url = to_native_string(url)
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
if (resp.status_code == codes.see_other and
@@ -153,13 +158,19 @@ class SessionRedirectMixin(object):
except KeyError:
pass
- extract_cookies_to_jar(prepared_request._cookies,
- prepared_request, resp.raw)
+ extract_cookies_to_jar(prepared_request._cookies, prepared_request, resp.raw)
prepared_request._cookies.update(self.cookies)
prepared_request.prepare_cookies(prepared_request._cookies)
+ # Rebuild auth and proxy information.
+ proxies = self.rebuild_proxies(prepared_request, proxies)
+ self.rebuild_auth(prepared_request, resp)
+
+ # Override the original request.
+ req = prepared_request
+
resp = self.send(
- prepared_request,
+ req,
stream=stream,
timeout=timeout,
verify=verify,
@@ -173,6 +184,68 @@ class SessionRedirectMixin(object):
i += 1
yield resp
+ def rebuild_auth(self, prepared_request, response):
+ """
+ When being redirected we may want to strip authentication from the
+ request to avoid leaking credentials. This method intelligently removes
+ and reapplies authentication where possible to avoid credential loss.
+ """
+ headers = prepared_request.headers
+ url = prepared_request.url
+
+ if 'Authorization' in headers:
+ # If we get redirected to a new host, we should strip out any
+ #Â authentication headers.
+ original_parsed = urlparse(response.request.url)
+ redirect_parsed = urlparse(url)
+
+ if (original_parsed.hostname != redirect_parsed.hostname):
+ del headers['Authorization']
+
+ # .netrc might have more auth for us on our new host.
+ new_auth = get_netrc_auth(url) if self.trust_env else None
+ if new_auth is not None:
+ prepared_request.prepare_auth(new_auth)
+
+ return
+
+ def rebuild_proxies(self, prepared_request, proxies):
+ """
+ This method re-evaluates the proxy configuration by considering the
+ environment variables. If we are redirected to a URL covered by
+ NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
+ proxy keys for this URL (in case they were stripped by a previous
+ redirect).
+
+ This method also replaces the Proxy-Authorization header where
+ necessary.
+ """
+ headers = prepared_request.headers
+ url = prepared_request.url
+ scheme = urlparse(url).scheme
+ new_proxies = proxies.copy() if proxies is not None else {}
+
+ if self.trust_env and not should_bypass_proxies(url):
+ environ_proxies = get_environ_proxies(url)
+
+ proxy = environ_proxies.get(scheme)
+
+ if proxy:
+ new_proxies.setdefault(scheme, environ_proxies[scheme])
+
+ if 'Proxy-Authorization' in headers:
+ del headers['Proxy-Authorization']
+
+ try:
+ username, password = get_auth_from_url(new_proxies[scheme])
+ except KeyError:
+ username, password = None, None
+
+ if username and password:
+ headers['Proxy-Authorization'] = _basic_auth_str(username, password)
+
+ return new_proxies
+
class Session(SessionRedirectMixin):
"""A Requests session.
@@ -320,7 +393,7 @@ class Session(SessionRedirectMixin):
:param auth: (optional) Auth tuple or callable to enable
Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) Float describing the timeout of the
- request.
+ request in seconds.
:param allow_redirects: (optional) Boolean. Set to True by default.
:param proxies: (optional) Dictionary mapping protocol to the URL of
the proxy.
@@ -467,8 +540,7 @@ class Session(SessionRedirectMixin):
if not isinstance(request, PreparedRequest):
raise ValueError('You can only send PreparedRequests.')
- # Set up variables needed for resolve_redirects and dispatching of
- # hooks
+ # Set up variables needed for resolve_redirects and dispatching of hooks
allow_redirects = kwargs.pop('allow_redirects', True)
stream = kwargs.get('stream')
timeout = kwargs.get('timeout')
@@ -482,8 +554,10 @@ class Session(SessionRedirectMixin):
# Start time (approximately) of the request
start = datetime.utcnow()
+
# Send the request
r = adapter.send(request, **kwargs)
+
# Total elapsed time of the request (approximately)
r.elapsed = datetime.utcnow() - start
@@ -492,15 +566,20 @@ class Session(SessionRedirectMixin):
# Persist cookies
if r.history:
+
# If the hooks create history then we want those cookies too
for resp in r.history:
extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
+
extract_cookies_to_jar(self.cookies, request, r.raw)
# Redirect resolving generator.
- gen = self.resolve_redirects(r, request, stream=stream,
- timeout=timeout, verify=verify, cert=cert,
- proxies=proxies)
+ gen = self.resolve_redirects(r, request,
+ stream=stream,
+ timeout=timeout,
+ verify=verify,
+ cert=cert,
+ proxies=proxies)
# Resolve redirects if allowed.
history = [resp for resp in gen] if allow_redirects else []
@@ -511,7 +590,10 @@ class Session(SessionRedirectMixin):
history.insert(0, r)
# Get the last request made
r = history.pop()
- r.history = tuple(history)
+ r.history = history
+
+ if not stream:
+ r.content
return r
@@ -534,8 +616,10 @@ class Session(SessionRedirectMixin):
"""Registers a connection adapter to a prefix.
Adapters are sorted in descending order by key length."""
+
self.adapters[prefix] = adapter
keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
+
for key in keys_to_move:
self.adapters[key] = self.adapters.pop(key)
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/status_codes.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/status_codes.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/status_codes.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/status_codes.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/structures.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/structures.py
similarity index 97%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/structures.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/structures.py
index a175913..9fd7818 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/structures.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/structures.py
@@ -106,8 +106,7 @@ class CaseInsensitiveDict(collections.MutableMapping):
return CaseInsensitiveDict(self._store.values())
def __repr__(self):
- return '%s(%r)' % (self.__class__.__name__, dict(self.items()))
-
+ return str(dict(self.items()))
class LookupDict(dict):
"""Dictionary lookup object."""
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/utils.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/utils.py
similarity index 94%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/utils.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/utils.py
index 7b7ff0a..68e50cf 100644
--- a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/requests/utils.py
+++ b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/requests/utils.py
@@ -24,10 +24,10 @@ from . import __version__
from . import certs
from .compat import parse_http_list as _parse_list_header
from .compat import (quote, urlparse, bytes, str, OrderedDict, unquote, is_py2,
- builtin_str, getproxies, proxy_bypass)
+ builtin_str, getproxies, proxy_bypass, urlunparse)
from .cookies import RequestsCookieJar, cookiejar_from_dict
from .structures import CaseInsensitiveDict
-from .exceptions import MissingSchema, InvalidURL
+from .exceptions import InvalidURL
_hush_pyflakes = (RequestsCookieJar,)
@@ -61,7 +61,7 @@ def super_len(o):
return os.fstat(fileno).st_size
if hasattr(o, 'getvalue'):
- # e.g. BytesIO, cStringIO.StringI
+ # e.g. BytesIO, cStringIO.StringIO
return len(o.getvalue())
@@ -466,9 +466,10 @@ def is_valid_cidr(string_network):
return True
-def get_environ_proxies(url):
- """Return a dict of environment proxies."""
-
+def should_bypass_proxies(url):
+ """
+ Returns whether we should bypass proxies or not.
+ """
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
# First check whether no_proxy is defined. If it is, check that the URL
@@ -486,13 +487,13 @@ def get_environ_proxies(url):
for proxy_ip in no_proxy:
if is_valid_cidr(proxy_ip):
if address_in_network(ip, proxy_ip):
- return {}
+ return True
else:
for host in no_proxy:
if netloc.endswith(host) or netloc.split(':')[0].endswith(host):
# The URL does match something in no_proxy, so we don't want
# to apply the proxies on this URL.
- return {}
+ return True
# If the system proxy settings indicate that this URL should be bypassed,
# don't proxy.
@@ -506,12 +507,16 @@ def get_environ_proxies(url):
bypass = False
if bypass:
- return {}
+ return True
- # If we get here, we either didn't have no_proxy set or we're not going
- # anywhere that no_proxy applies to, and the system settings don't require
- # bypassing the proxy for the current URL.
- return getproxies()
+ return False
+
+def get_environ_proxies(url):
+ """Return a dict of environment proxies."""
+ if should_bypass_proxies(url):
+ return {}
+ else:
+ return getproxies()
def default_user_agent(name="python-requests"):
@@ -548,7 +553,7 @@ def default_user_agent(name="python-requests"):
def default_headers():
return CaseInsensitiveDict({
'User-Agent': default_user_agent(),
- 'Accept-Encoding': ', '.join(('gzip', 'deflate', 'compress')),
+ 'Accept-Encoding': ', '.join(('gzip', 'deflate')),
'Accept': '*/*'
})
@@ -622,13 +627,18 @@ def guess_json_utf(data):
return None
-def except_on_missing_scheme(url):
- """Given a URL, raise a MissingSchema exception if the scheme is missing.
- """
- scheme, netloc, path, params, query, fragment = urlparse(url)
+def prepend_scheme_if_needed(url, new_scheme):
+ '''Given a URL that may or may not have a scheme, prepend the given scheme.
+ Does not replace a present scheme with the one provided as an argument.'''
+ scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
- if not scheme:
- raise MissingSchema('Proxy URLs must have explicit schemes.')
+ # urlparse is a finicky beast, and sometimes decides that there isn't a
+ # netloc present. Assume that it's being over-cautious, and switch netloc
+ # and path if urlparse decided there was no netloc.
+ if not netloc:
+ netloc, path = path, netloc
+
+ return urlunparse((scheme, netloc, path, params, query, fragment))
def get_auth_from_url(url):
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/six.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/six.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/_vendor/six.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/_vendor/six.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/backwardcompat/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/backwardcompat/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/backwardcompat/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/backwardcompat/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/basecommand.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/basecommand.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/basecommand.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/basecommand.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/baseparser.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/baseparser.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/baseparser.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/baseparser.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/cmdoptions.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/cmdoptions.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/cmdoptions.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/cmdoptions.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/bundle.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/bundle.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/bundle.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/bundle.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/completion.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/completion.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/completion.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/completion.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/freeze.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/freeze.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/freeze.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/freeze.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/help.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/help.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/help.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/help.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/install.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/install.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/install.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/install.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/list.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/list.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/list.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/list.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/search.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/search.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/search.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/search.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/show.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/show.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/show.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/show.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/uninstall.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/uninstall.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/uninstall.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/uninstall.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/unzip.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/unzip.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/unzip.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/unzip.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/wheel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/wheel.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/wheel.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/wheel.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/zip.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/zip.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/commands/zip.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/commands/zip.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/download.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/download.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/download.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/download.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/exceptions.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/exceptions.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/exceptions.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/exceptions.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/index.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/index.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/index.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/index.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/locations.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/locations.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/locations.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/locations.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/log.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/log.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/log.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/log.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/pep425tags.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/pep425tags.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/pep425tags.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/pep425tags.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/req.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/req.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/req.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/req.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/runner.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/runner.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/runner.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/runner.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/status_codes.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/status_codes.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/status_codes.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/status_codes.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/util.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/util.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/util.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/util.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/vcs/__init__.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/vcs/__init__.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/vcs/__init__.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/vcs/__init__.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/vcs/bazaar.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/vcs/bazaar.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/vcs/bazaar.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/vcs/bazaar.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/vcs/git.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/vcs/git.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/vcs/git.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/vcs/git.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/vcs/mercurial.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/vcs/mercurial.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/vcs/mercurial.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/vcs/mercurial.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/vcs/subversion.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/vcs/subversion.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/vcs/subversion.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/vcs/subversion.py
diff --git a/Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/wheel.py b/Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/wheel.py
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/pip-1.5.5-py2.7.egg/pip/wheel.py
rename to Darwin/lib/python2.7/site-packages/pip-1.5.6-py2.7.egg/pip/wheel.py
diff --git a/Darwin/lib/python2.7/site-packages/setuptools-3.6-py2.7.egg b/Darwin/lib/python2.7/site-packages/setuptools-3.6-py2.7.egg
index e33a0b9..c49254f 100644
Binary files a/Darwin/lib/python2.7/site-packages/setuptools-3.6-py2.7.egg and b/Darwin/lib/python2.7/site-packages/setuptools-3.6-py2.7.egg differ
diff --git a/Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/dependency_links.txt
deleted file mode 100644
index 8b13789..0000000
--- a/Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/dependency_links.txt
+++ /dev/null
@@ -1 +0,0 @@
-
diff --git a/Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/PKG-INFO b/Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/PKG-INFO
similarity index 83%
rename from Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/PKG-INFO
rename to Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/PKG-INFO
index 26d7ce8..abae236 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/PKG-INFO
+++ b/Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 1.1
Name: simplejson
-Version: 3.4.1
+Version: 3.6.3
Summary: Simple, fast, extensible JSON encoder/decoder for Python
Home-page: http://github.com/simplejson/simplejson
Author: Bob Ippolito
@@ -29,6 +29,12 @@ Description: simplejson is a simple, fast, complete, correct and extensible
is particularly useful for implementing protocols such as JSON-RPC
that have a richer type system than JSON itself.
+ For those of you that have legacy systems to maintain, there is a
+ very old fork of simplejson in the `python2.2`_ branch that supports
+ Python 2.2. This is based off of a very old version of simplejson,
+ is not maintained, and should only be used as a last resort.
+
+ .. _python2.2: https://github.com/simplejson/simplejson/tree/python2.2
Platform: any
Classifier: Development Status :: 5 - Production/Stable
@@ -42,6 +48,7 @@ Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.3
+Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Topic :: Software Development :: Libraries :: Python Modules
diff --git a/Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/SOURCES.txt b/Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/SOURCES.txt
similarity index 94%
rename from Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/SOURCES.txt
rename to Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/SOURCES.txt
index 536f83a..76f095a 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/SOURCES.txt
+++ b/Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/SOURCES.txt
@@ -21,6 +21,7 @@ simplejson.egg-info/dependency_links.txt
simplejson.egg-info/top_level.txt
simplejson/tests/__init__.py
simplejson/tests/test_bigint_as_string.py
+simplejson/tests/test_bitsize_int_as_string.py
simplejson/tests/test_check_circular.py
simplejson/tests/test_decimal.py
simplejson/tests/test_decode.py
diff --git a/Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/dependency_links.txt b/Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/dependency_links.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/Jinja2-2.7.2-py2.7.egg-info/dependency_links.txt
rename to Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/dependency_links.txt
diff --git a/Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/installed-files.txt b/Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/installed-files.txt
similarity index 95%
rename from Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/installed-files.txt
rename to Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/installed-files.txt
index 75aeb4c..51f3d8e 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/installed-files.txt
+++ b/Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/installed-files.txt
@@ -7,6 +7,7 @@
../simplejson/tool.py
../simplejson/tests/__init__.py
../simplejson/tests/test_bigint_as_string.py
+../simplejson/tests/test_bitsize_int_as_string.py
../simplejson/tests/test_check_circular.py
../simplejson/tests/test_decimal.py
../simplejson/tests/test_decode.py
@@ -40,6 +41,7 @@
../simplejson/tool.pyc
../simplejson/tests/__init__.pyc
../simplejson/tests/test_bigint_as_string.pyc
+../simplejson/tests/test_bitsize_int_as_string.pyc
../simplejson/tests/test_check_circular.pyc
../simplejson/tests/test_decimal.pyc
../simplejson/tests/test_decode.pyc
diff --git a/Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/top_level.txt b/Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/top_level.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/simplejson-3.4.1-py2.7.egg-info/top_level.txt
rename to Darwin/lib/python2.7/site-packages/simplejson-3.6.3-py2.7.egg-info/top_level.txt
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/__init__.py b/Darwin/lib/python2.7/site-packages/simplejson/__init__.py
index ed9c9a8..a02c4de 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson/__init__.py
+++ b/Darwin/lib/python2.7/site-packages/simplejson/__init__.py
@@ -98,7 +98,7 @@ Using simplejson.tool from the shell to validate and pretty-print::
Expecting property name: line 1 column 3 (char 2)
"""
from __future__ import absolute_import
-__version__ = '3.4.1'
+__version__ = '3.6.3'
__all__ = [
'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONDecodeError', 'JSONEncoder',
@@ -144,14 +144,15 @@ _default_encoder = JSONEncoder(
item_sort_key=None,
for_json=False,
ignore_nan=False,
+ int_as_string_bitcount=None,
)
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
- allow_nan=True, cls=None, indent=None, separators=None,
- encoding='utf-8', default=None, use_decimal=True,
- namedtuple_as_object=True, tuple_as_array=True,
- bigint_as_string=False, sort_keys=False, item_sort_key=None,
- for_json=False, ignore_nan=False, **kw):
+ allow_nan=True, cls=None, indent=None, separators=None,
+ encoding='utf-8', default=None, use_decimal=True,
+ namedtuple_as_object=True, tuple_as_array=True,
+ bigint_as_string=False, sort_keys=False, item_sort_key=None,
+ for_json=False, ignore_nan=False, int_as_string_bitcount=None, **kw):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
@@ -209,6 +210,10 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
lossy operation that will not round-trip correctly and should be used
sparingly.
+ If *int_as_string_bitcount* is a positive number (n), then int of size
+ greater than or equal to 2**n or lower than or equal to -2**n will be
+ encoded as strings.
+
If specified, *item_sort_key* is a callable used to sort the items in
each dictionary. This is useful if you want to sort items other than
in alphabetical order by key. This option takes precedence over
@@ -238,8 +243,8 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and use_decimal
and namedtuple_as_object and tuple_as_array
- and not bigint_as_string and not item_sort_key
- and not for_json and not ignore_nan and not kw):
+ and not bigint_as_string and int_as_string_bitcount is None
+ and not item_sort_key and not for_json and not ignore_nan and not kw):
iterable = _default_encoder.iterencode(obj)
else:
if cls is None:
@@ -255,6 +260,7 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
item_sort_key=item_sort_key,
for_json=for_json,
ignore_nan=ignore_nan,
+ int_as_string_bitcount=int_as_string_bitcount,
**kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at
# a debuggability cost
@@ -263,11 +269,11 @@ def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
- allow_nan=True, cls=None, indent=None, separators=None,
- encoding='utf-8', default=None, use_decimal=True,
- namedtuple_as_object=True, tuple_as_array=True,
- bigint_as_string=False, sort_keys=False, item_sort_key=None,
- for_json=False, ignore_nan=False, **kw):
+ allow_nan=True, cls=None, indent=None, separators=None,
+ encoding='utf-8', default=None, use_decimal=True,
+ namedtuple_as_object=True, tuple_as_array=True,
+ bigint_as_string=False, sort_keys=False, item_sort_key=None,
+ for_json=False, ignore_nan=False, int_as_string_bitcount=None, **kw):
"""Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is false then ``dict`` keys that are not basic types
@@ -319,6 +325,10 @@ def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
or lower than -2**53 will be encoded as strings. This is to avoid the
rounding that happens in Javascript otherwise.
+ If *int_as_string_bitcount* is a positive number (n), then int of size
+ greater than or equal to 2**n or lower than or equal to -2**n will be
+ encoded as strings.
+
If specified, *item_sort_key* is a callable used to sort the items in
each dictionary. This is useful if you want to sort items other than
in alphabetical order by key. This option takes precendence over
@@ -343,14 +353,16 @@ def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
"""
# cached encoder
- if (not skipkeys and ensure_ascii and
+ if (
+ not skipkeys and ensure_ascii and
check_circular and allow_nan and
cls is None and indent is None and separators is None and
encoding == 'utf-8' and default is None and use_decimal
and namedtuple_as_object and tuple_as_array
- and not bigint_as_string and not sort_keys
- and not item_sort_key and not for_json
- and not ignore_nan and not kw):
+ and not bigint_as_string and int_as_string_bitcount is None
+ and not sort_keys and not item_sort_key and not for_json
+ and not ignore_nan and not kw
+ ):
return _default_encoder.encode(obj)
if cls is None:
cls = JSONEncoder
@@ -366,6 +378,7 @@ def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
item_sort_key=item_sort_key,
for_json=for_json,
ignore_nan=ignore_nan,
+ int_as_string_bitcount=int_as_string_bitcount,
**kw).encode(obj)
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/_speedups.so b/Darwin/lib/python2.7/site-packages/simplejson/_speedups.so
index edb0b52..9449edf 100755
Binary files a/Darwin/lib/python2.7/site-packages/simplejson/_speedups.so and b/Darwin/lib/python2.7/site-packages/simplejson/_speedups.so differ
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/decoder.py b/Darwin/lib/python2.7/site-packages/simplejson/decoder.py
index 38cb027..545e658 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson/decoder.py
+++ b/Darwin/lib/python2.7/site-packages/simplejson/decoder.py
@@ -384,6 +384,17 @@ class JSONDecoder(object):
have extraneous data at the end.
"""
+ if idx < 0:
+ # Ensure that raw_decode bails on negative indexes, the regex
+ # would otherwise mask this behavior. #98
+ raise JSONDecodeError('Expecting value', s, idx)
if _PY3 and not isinstance(s, text_type):
raise TypeError("Input string must be text, not bytes")
+ # strip UTF-8 bom
+ if len(s) > idx:
+ ord0 = ord(s[idx])
+ if ord0 == 0xfeff:
+ idx += 1
+ elif ord0 == 0xef and s[idx:idx + 3] == '\xef\xbb\xbf':
+ idx += 3
return self.scan_once(s, idx=_w(s, idx).end())
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/encoder.py b/Darwin/lib/python2.7/site-packages/simplejson/encoder.py
index 9815ee5..db18244 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson/encoder.py
+++ b/Darwin/lib/python2.7/site-packages/simplejson/encoder.py
@@ -116,12 +116,14 @@ class JSONEncoder(object):
"""
item_separator = ', '
key_separator = ': '
+
def __init__(self, skipkeys=False, ensure_ascii=True,
- check_circular=True, allow_nan=True, sort_keys=False,
- indent=None, separators=None, encoding='utf-8', default=None,
- use_decimal=True, namedtuple_as_object=True,
- tuple_as_array=True, bigint_as_string=False,
- item_sort_key=None, for_json=False, ignore_nan=False):
+ check_circular=True, allow_nan=True, sort_keys=False,
+ indent=None, separators=None, encoding='utf-8', default=None,
+ use_decimal=True, namedtuple_as_object=True,
+ tuple_as_array=True, bigint_as_string=False,
+ item_sort_key=None, for_json=False, ignore_nan=False,
+ int_as_string_bitcount=None):
"""Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
@@ -180,6 +182,10 @@ class JSONEncoder(object):
or lower than -2**53 will be encoded as strings. This is to avoid the
rounding that happens in Javascript otherwise.
+ If int_as_string_bitcount is a positive number (n), then int of size
+ greater than or equal to 2**n or lower than or equal to -2**n will be
+ encoded as strings.
+
If specified, item_sort_key is a callable used to sort the items in
each dictionary. This is useful if you want to sort items other than
in alphabetical order by key.
@@ -207,6 +213,7 @@ class JSONEncoder(object):
self.item_sort_key = item_sort_key
self.for_json = for_json
self.ignore_nan = ignore_nan
+ self.int_as_string_bitcount = int_as_string_bitcount
if indent is not None and not isinstance(indent, string_types):
indent = indent * ' '
self.indent = indent
@@ -315,8 +322,9 @@ class JSONEncoder(object):
return text
-
key_memo = {}
+ int_as_string_bitcount = (
+ 53 if self.bigint_as_string else self.int_as_string_bitcount)
if (_one_shot and c_make_encoder is not None
and self.indent is None):
_iterencode = c_make_encoder(
@@ -324,17 +332,17 @@ class JSONEncoder(object):
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, self.allow_nan, key_memo, self.use_decimal,
self.namedtuple_as_object, self.tuple_as_array,
- self.bigint_as_string, self.item_sort_key,
- self.encoding, self.for_json, self.ignore_nan,
- Decimal)
+ int_as_string_bitcount,
+ self.item_sort_key, self.encoding, self.for_json,
+ self.ignore_nan, Decimal)
else:
_iterencode = _make_iterencode(
markers, self.default, _encoder, self.indent, floatstr,
self.key_separator, self.item_separator, self.sort_keys,
self.skipkeys, _one_shot, self.use_decimal,
self.namedtuple_as_object, self.tuple_as_array,
- self.bigint_as_string, self.item_sort_key,
- self.encoding, self.for_json,
+ int_as_string_bitcount,
+ self.item_sort_key, self.encoding, self.for_json,
Decimal=Decimal)
try:
return _iterencode(o, 0)
@@ -372,7 +380,8 @@ class JSONEncoderForHTML(JSONEncoder):
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
_key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
_use_decimal, _namedtuple_as_object, _tuple_as_array,
- _bigint_as_string, _item_sort_key, _encoding, _for_json,
+ _int_as_string_bitcount, _item_sort_key,
+ _encoding,_for_json,
## HACK: hand-optimized bytecode; turn globals into locals
_PY3=PY3,
ValueError=ValueError,
@@ -392,6 +401,26 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
elif _sort_keys and not _item_sort_key:
_item_sort_key = itemgetter(0)
+ if (_int_as_string_bitcount is not None and
+ (_int_as_string_bitcount <= 0 or
+ not isinstance(_int_as_string_bitcount, integer_types))):
+ raise TypeError("int_as_string_bitcount must be a positive integer")
+
+ def _encode_int(value):
+ skip_quoting = (
+ _int_as_string_bitcount is None
+ or
+ _int_as_string_bitcount < 1
+ )
+ if (
+ skip_quoting or
+ (-1 << _int_as_string_bitcount)
+ < value <
+ (1 << _int_as_string_bitcount)
+ ):
+ return str(value)
+ return '"' + str(value) + '"'
+
def _iterencode_list(lst, _current_indent_level):
if not lst:
yield '[]'
@@ -426,10 +455,7 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
elif value is False:
yield buf + 'false'
elif isinstance(value, integer_types):
- yield ((buf + str(value))
- if (not _bigint_as_string or
- (-1 << 53) < value < (1 << 53))
- else (buf + '"' + str(value) + '"'))
+ yield buf + _encode_int(value)
elif isinstance(value, float):
yield buf + _floatstr(value)
elif _use_decimal and isinstance(value, Decimal):
@@ -540,10 +566,7 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
elif value is False:
yield 'false'
elif isinstance(value, integer_types):
- yield (str(value)
- if (not _bigint_as_string or
- (-1 << 53) < value < (1 << 53))
- else ('"' + str(value) + '"'))
+ yield _encode_int(value)
elif isinstance(value, float):
yield _floatstr(value)
elif _use_decimal and isinstance(value, Decimal):
@@ -585,10 +608,7 @@ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
elif o is False:
yield 'false'
elif isinstance(o, integer_types):
- yield (str(o)
- if (not _bigint_as_string or
- (-1 << 53) < o < (1 << 53))
- else ('"' + str(o) + '"'))
+ yield _encode_int(o)
elif isinstance(o, float):
yield _floatstr(o)
else:
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/scanner.py b/Darwin/lib/python2.7/site-packages/simplejson/scanner.py
index b7918b3..5abed35 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson/scanner.py
+++ b/Darwin/lib/python2.7/site-packages/simplejson/scanner.py
@@ -118,6 +118,11 @@ def py_make_scanner(context):
raise JSONDecodeError(errmsg, string, idx)
def scan_once(string, idx):
+ if idx < 0:
+ # Ensure the same behavior as the C speedup, otherwise
+ # this would work for *some* negative string indices due
+ # to the behavior of __getitem__ for strings. #98
+ raise JSONDecodeError('Expecting value', string, idx)
try:
return _scan_once(string, idx)
finally:
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/tests/__init__.py b/Darwin/lib/python2.7/site-packages/simplejson/tests/__init__.py
index 5490584..c7551e8 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson/tests/__init__.py
+++ b/Darwin/lib/python2.7/site-packages/simplejson/tests/__init__.py
@@ -37,6 +37,7 @@ def all_tests_suite():
def get_suite():
return additional_tests(
unittest.TestLoader().loadTestsFromNames([
+ 'simplejson.tests.test_bitsize_int_as_string',
'simplejson.tests.test_bigint_as_string',
'simplejson.tests.test_check_circular',
'simplejson.tests.test_decode',
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/tests/test_bigint_as_string.py b/Darwin/lib/python2.7/site-packages/simplejson/tests/test_bigint_as_string.py
index 20ea64c..2cf2cc2 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson/tests/test_bigint_as_string.py
+++ b/Darwin/lib/python2.7/site-packages/simplejson/tests/test_bigint_as_string.py
@@ -1,7 +1,7 @@
from unittest import TestCase
import simplejson as json
-from simplejson.compat import long_type
+
class TestBigintAsString(TestCase):
# Python 2.5, at least the one that ships on Mac OS X, calculates
@@ -15,44 +15,53 @@ class TestBigintAsString(TestCase):
((-1 << 53) - 1, '-9007199254740993'),
((-1 << 53) + 1, -9007199254740991)]
+ options = (
+ {"bigint_as_string": True},
+ {"int_as_string_bitcount": 53}
+ )
+
def test_ints(self):
- for val, expect in self.values:
- self.assertEqual(
- val,
- json.loads(json.dumps(val)))
- self.assertEqual(
- expect,
- json.loads(json.dumps(val, bigint_as_string=True)))
+ for opts in self.options:
+ for val, expect in self.values:
+ self.assertEqual(
+ val,
+ json.loads(json.dumps(val)))
+ self.assertEqual(
+ expect,
+ json.loads(json.dumps(val, **opts)))
def test_lists(self):
- for val, expect in self.values:
- val = [val, val]
- expect = [expect, expect]
- self.assertEqual(
- val,
- json.loads(json.dumps(val)))
- self.assertEqual(
- expect,
- json.loads(json.dumps(val, bigint_as_string=True)))
+ for opts in self.options:
+ for val, expect in self.values:
+ val = [val, val]
+ expect = [expect, expect]
+ self.assertEqual(
+ val,
+ json.loads(json.dumps(val)))
+ self.assertEqual(
+ expect,
+ json.loads(json.dumps(val, **opts)))
def test_dicts(self):
- for val, expect in self.values:
- val = {'k': val}
- expect = {'k': expect}
- self.assertEqual(
- val,
- json.loads(json.dumps(val)))
- self.assertEqual(
- expect,
- json.loads(json.dumps(val, bigint_as_string=True)))
+ for opts in self.options:
+ for val, expect in self.values:
+ val = {'k': val}
+ expect = {'k': expect}
+ self.assertEqual(
+ val,
+ json.loads(json.dumps(val)))
+ self.assertEqual(
+ expect,
+ json.loads(json.dumps(val, **opts)))
def test_dict_keys(self):
- for val, _ in self.values:
- expect = {str(val): 'value'}
- val = {val: 'value'}
- self.assertEqual(
- expect,
- json.loads(json.dumps(val)))
- self.assertEqual(
- expect,
- json.loads(json.dumps(val, bigint_as_string=True)))
+ for opts in self.options:
+ for val, _ in self.values:
+ expect = {str(val): 'value'}
+ val = {val: 'value'}
+ self.assertEqual(
+ expect,
+ json.loads(json.dumps(val)))
+ self.assertEqual(
+ expect,
+ json.loads(json.dumps(val, **opts)))
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/tests/test_bitsize_int_as_string.py b/Darwin/lib/python2.7/site-packages/simplejson/tests/test_bitsize_int_as_string.py
new file mode 100644
index 0000000..fd7d103
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/simplejson/tests/test_bitsize_int_as_string.py
@@ -0,0 +1,73 @@
+from unittest import TestCase
+
+import simplejson as json
+
+
+class TestBitSizeIntAsString(TestCase):
+ # Python 2.5, at least the one that ships on Mac OS X, calculates
+ # 2 ** 31 as 0! It manages to calculate 1 << 31 correctly.
+ values = [
+ (200, 200),
+ ((1 << 31) - 1, (1 << 31) - 1),
+ ((1 << 31), str(1 << 31)),
+ ((1 << 31) + 1, str((1 << 31) + 1)),
+ (-100, -100),
+ ((-1 << 31), str(-1 << 31)),
+ ((-1 << 31) - 1, str((-1 << 31) - 1)),
+ ((-1 << 31) + 1, (-1 << 31) + 1),
+ ]
+
+ def test_invalid_counts(self):
+ for n in ['foo', -1, 0, 1.0]:
+ self.assertRaises(
+ TypeError,
+ json.dumps, 0, int_as_string_bitcount=n)
+
+ def test_ints_outside_range_fails(self):
+ self.assertNotEqual(
+ str(1 << 15),
+ json.loads(json.dumps(1 << 15, int_as_string_bitcount=16)),
+ )
+
+ def test_ints(self):
+ for val, expect in self.values:
+ self.assertEqual(
+ val,
+ json.loads(json.dumps(val)))
+ self.assertEqual(
+ expect,
+ json.loads(json.dumps(val, int_as_string_bitcount=31)),
+ )
+
+ def test_lists(self):
+ for val, expect in self.values:
+ val = [val, val]
+ expect = [expect, expect]
+ self.assertEqual(
+ val,
+ json.loads(json.dumps(val)))
+ self.assertEqual(
+ expect,
+ json.loads(json.dumps(val, int_as_string_bitcount=31)))
+
+ def test_dicts(self):
+ for val, expect in self.values:
+ val = {'k': val}
+ expect = {'k': expect}
+ self.assertEqual(
+ val,
+ json.loads(json.dumps(val)))
+ self.assertEqual(
+ expect,
+ json.loads(json.dumps(val, int_as_string_bitcount=31)))
+
+ def test_dict_keys(self):
+ for val, _ in self.values:
+ expect = {str(val): 'value'}
+ val = {val: 'value'}
+ self.assertEqual(
+ expect,
+ json.loads(json.dumps(val)))
+ self.assertEqual(
+ expect,
+ json.loads(json.dumps(val, int_as_string_bitcount=31)))
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/tests/test_decode.py b/Darwin/lib/python2.7/site-packages/simplejson/tests/test_decode.py
index ea5c90a..30b692a 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson/tests/test_decode.py
+++ b/Darwin/lib/python2.7/site-packages/simplejson/tests/test_decode.py
@@ -86,3 +86,14 @@ class TestDecode(TestCase):
self.assertEqual(
({'a': {}}, 11),
cls().raw_decode(" \n{\"a\": {}}"))
+
+ def test_bounds_checking(self):
+ # https://github.com/simplejson/simplejson/issues/98
+ j = json.decoder.JSONDecoder()
+ for i in [4, 5, 6, -1, -2, -3, -4, -5, -6]:
+ self.assertRaises(ValueError, j.scan_once, '1234', i)
+ self.assertRaises(ValueError, j.raw_decode, '1234', i)
+ x, y = sorted(['128931233', '472389423'], key=id)
+ diff = id(x) - id(y)
+ self.assertRaises(ValueError, j.scan_once, y, diff)
+ self.assertRaises(ValueError, j.raw_decode, y, i)
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/tests/test_speedups.py b/Darwin/lib/python2.7/site-packages/simplejson/tests/test_speedups.py
index 825ecf2..0a2b63b 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson/tests/test_speedups.py
+++ b/Darwin/lib/python2.7/site-packages/simplejson/tests/test_speedups.py
@@ -1,20 +1,39 @@
+import sys
+import unittest
from unittest import TestCase
from simplejson import encoder, scanner
+
def has_speedups():
return encoder.c_make_encoder is not None
-class TestDecode(TestCase):
- def test_make_scanner(self):
+
+def skip_if_speedups_missing(func):
+ def wrapper(*args, **kwargs):
if not has_speedups():
- return
+ if hasattr(unittest, 'SkipTest'):
+ raise unittest.SkipTest("C Extension not available")
+ else:
+ sys.stdout.write("C Extension not available")
+ return
+ return func(*args, **kwargs)
+
+ return wrapper
+
+
+class TestDecode(TestCase):
+ @skip_if_speedups_missing
+ def test_make_scanner(self):
self.assertRaises(AttributeError, scanner.c_make_scanner, 1)
+ @skip_if_speedups_missing
def test_make_encoder(self):
- if not has_speedups():
- return
- self.assertRaises(TypeError, encoder.c_make_encoder,
+ self.assertRaises(
+ TypeError,
+ encoder.c_make_encoder,
None,
- "\xCD\x7D\x3D\x4E\x12\x4C\xF9\x79\xD7\x52\xBA\x82\xF2\x27\x4A\x7D\xA0\xCA\x75",
- None)
+ ("\xCD\x7D\x3D\x4E\x12\x4C\xF9\x79\xD7"
+ "\x52\xBA\x82\xF2\x27\x4A\x7D\xA0\xCA\x75"),
+ None
+ )
diff --git a/Darwin/lib/python2.7/site-packages/simplejson/tests/test_unicode.py b/Darwin/lib/python2.7/site-packages/simplejson/tests/test_unicode.py
index f04cc5c..3b37f65 100644
--- a/Darwin/lib/python2.7/site-packages/simplejson/tests/test_unicode.py
+++ b/Darwin/lib/python2.7/site-packages/simplejson/tests/test_unicode.py
@@ -1,8 +1,9 @@
import sys
+import codecs
from unittest import TestCase
import simplejson as json
-from simplejson.compat import unichr, text_type, b, u
+from simplejson.compat import unichr, text_type, b, u, BytesIO
class TestUnicode(TestCase):
def test_encoding1(self):
@@ -143,3 +144,10 @@ class TestUnicode(TestCase):
self.assertEqual(
json.dumps(c, ensure_ascii=False),
'"' + c + '"')
+
+ def test_strip_bom(self):
+ content = u"\u3053\u3093\u306b\u3061\u308f"
+ json_doc = codecs.BOM_UTF8 + b(json.dumps(content))
+ self.assertEqual(json.load(BytesIO(json_doc)), content)
+ for doc in json_doc, json_doc.decode('utf8'):
+ self.assertEqual(json.loads(doc), content)
diff --git a/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/RECORD b/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/RECORD
deleted file mode 100644
index 5292ea2..0000000
--- a/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/RECORD
+++ /dev/null
@@ -1,8 +0,0 @@
-six.py,sha256=whAS1kvmixxh-pKqb5qQ05-fHMnGjuKyU6m7_wa09O4,23462
-six-1.6.1.dist-info/METADATA,sha256=gJwO11jBmVqgPIovWODDi3q04AIG3IshXc3uvmvtOu4,1279
-six-1.6.1.dist-info/top_level.txt,sha256=_iVH_iYEtEXnD8nYGQYpYFUvkUW9sEO1GYbkeKSAais,4
-six-1.6.1.dist-info/pydist.json,sha256=mKxr_5dOwkrHUxMGy62vhBZaKnllO0YPuuEMElNgFBs,621
-six-1.6.1.dist-info/DESCRIPTION.rst,sha256=wDIPS0rnIMXICM3qxqUg2g5ozzQyOpCLh8oaca9UgFQ,771
-six-1.6.1.dist-info/RECORD,,
-six-1.6.1.dist-info/WHEEL,sha256=SXYYsi-y-rEGIva8sB8iKF6bAFD6YDhmqHX5hI3fc0o,110
-six.pyc,,
diff --git a/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/pydist.json b/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/pydist.json
deleted file mode 100644
index ba0c0b4..0000000
--- a/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/pydist.json
+++ /dev/null
@@ -1 +0,0 @@
-{"summary": "Python 2 and 3 compatibility utilities", "classifiers": ["Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Software Development :: Libraries", "Topic :: Utilities"], "license": "MIT", "metadata_version": "2.0", "project_urls": {"Home": "http://pypi.python.org/pypi/six/"}, "contacts": [{"email": "benjamin@python.org", "name": "Benjamin Peterson", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}, "version": "1.6.1", "name": "six", "generator": "bdist_wheel (0.22.0)"}
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/DESCRIPTION.rst b/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/DESCRIPTION.rst
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/DESCRIPTION.rst
rename to Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/DESCRIPTION.rst
diff --git a/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/METADATA b/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/METADATA
similarity index 98%
rename from Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/METADATA
rename to Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/METADATA
index dee873b..893c80d 100644
--- a/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/METADATA
+++ b/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/METADATA
@@ -1,6 +1,6 @@
Metadata-Version: 2.0
Name: six
-Version: 1.6.1
+Version: 1.7.3
Summary: Python 2 and 3 compatibility utilities
Home-page: http://pypi.python.org/pypi/six/
Author: Benjamin Peterson
diff --git a/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/RECORD b/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/RECORD
new file mode 100644
index 0000000..46f7a01
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/RECORD
@@ -0,0 +1,8 @@
+six.py,sha256=SHMbYUbZdimEb9Q7FBGMUtwaLCRC7qYQgXXSS_PHQss,26518
+six-1.7.3.dist-info/METADATA,sha256=J5bgiEeMfq7UWjeoY8UJSndsDcCGQlaAVNrEkDHgE0g,1279
+six-1.7.3.dist-info/top_level.txt,sha256=_iVH_iYEtEXnD8nYGQYpYFUvkUW9sEO1GYbkeKSAais,4
+six-1.7.3.dist-info/DESCRIPTION.rst,sha256=wDIPS0rnIMXICM3qxqUg2g5ozzQyOpCLh8oaca9UgFQ,771
+six-1.7.3.dist-info/metadata.json,sha256=BLxlZMZlGI6548ILR5YYtDZ_U35REqChoRN1SCjGy5M,621
+six-1.7.3.dist-info/RECORD,,
+six-1.7.3.dist-info/WHEEL,sha256=6lxp_S3wZGmTBtGMVmNNLyvKFcp7HqQw2Wn4YYk-Suo,110
+six.pyc,,
diff --git a/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/WHEEL b/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/WHEEL
similarity index 70%
rename from Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/WHEEL
rename to Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/WHEEL
index f2ddc35..f19235c 100644
--- a/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/WHEEL
+++ b/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/WHEEL
@@ -1,5 +1,5 @@
Wheel-Version: 1.0
-Generator: bdist_wheel (0.22.0)
+Generator: bdist_wheel (0.23.0)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any
diff --git a/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/metadata.json b/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/metadata.json
new file mode 100644
index 0000000..13595fb
--- /dev/null
+++ b/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/metadata.json
@@ -0,0 +1 @@
+{"version": "1.7.3", "license": "MIT", "metadata_version": "2.0", "project_urls": {"Home": "http://pypi.python.org/pypi/six/"}, "contacts": [{"email": "benjamin@python.org", "role": "author", "name": "Benjamin Peterson"}], "generator": "bdist_wheel (0.23.0)", "name": "six", "document_names": {"description": "DESCRIPTION.rst"}, "summary": "Python 2 and 3 compatibility utilities", "classifiers": ["Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Topic :: Software Development :: Libraries", "Topic :: Utilities"]}
\ No newline at end of file
diff --git a/Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/top_level.txt b/Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/top_level.txt
similarity index 100%
rename from Darwin/lib/python2.7/site-packages/six-1.6.1.dist-info/top_level.txt
rename to Darwin/lib/python2.7/site-packages/six-1.7.3.dist-info/top_level.txt
diff --git a/Darwin/lib/python2.7/site-packages/six.py b/Darwin/lib/python2.7/site-packages/six.py
index 019130f..f8f7d40 100644
--- a/Darwin/lib/python2.7/site-packages/six.py
+++ b/Darwin/lib/python2.7/site-packages/six.py
@@ -20,12 +20,13 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
+import functools
import operator
import sys
import types
__author__ = "Benjamin Peterson "
-__version__ = "1.6.1"
+__version__ = "1.7.3"
# Useful for very coarse version differentiation.
@@ -83,11 +84,7 @@ class _LazyDescr(object):
self.name = name
def __get__(self, obj, tp):
- try:
- result = self._resolve()
- except ImportError:
- # See the nice big comment in MovedModule.__getattr__.
- raise AttributeError("%s could not be imported " % self.name)
+ result = self._resolve()
setattr(obj, self.name, result) # Invokes __set__.
# This is a bit ugly, but it avoids running this again.
delattr(obj.__class__, self.name)
@@ -109,22 +106,7 @@ class MovedModule(_LazyDescr):
return _import_module(self.mod)
def __getattr__(self, attr):
- # It turns out many Python frameworks like to traverse sys.modules and
- # try to load various attributes. This causes problems if this is a
- # platform-specific module on the wrong platform, like _winreg on
- # Unixes. Therefore, we silently pretend unimportable modules do not
- # have any attributes. See issues #51, #53, #56, and #63 for the full
- # tales of woe.
- #
- # First, if possible, avoid loading the module just to look at __file__,
- # __name__, or __path__.
- if (attr in ("__file__", "__name__", "__path__") and
- self.mod not in sys.modules):
- raise AttributeError(attr)
- try:
- _module = self._resolve()
- except ImportError:
- raise AttributeError(attr)
+ _module = self._resolve()
value = getattr(_module, attr)
setattr(self, attr, value)
return value
@@ -170,9 +152,72 @@ class MovedAttribute(_LazyDescr):
return getattr(module, self.attr)
+class _SixMetaPathImporter(object):
+ """
+ A meta path importer to import six.moves and its submodules.
+
+ This class implements a PEP302 finder and loader. It should be compatible
+ with Python 2.5 and all existing versions of Python3
+ """
+ def __init__(self, six_module_name):
+ self.name = six_module_name
+ self.known_modules = {}
+
+ def _add_module(self, mod, *fullnames):
+ for fullname in fullnames:
+ self.known_modules[self.name + "." + fullname] = mod
+
+ def _get_module(self, fullname):
+ return self.known_modules[self.name + "." + fullname]
+
+ def find_module(self, fullname, path=None):
+ if fullname in self.known_modules:
+ return self
+ return None
+
+ def __get_module(self, fullname):
+ try:
+ return self.known_modules[fullname]
+ except KeyError:
+ raise ImportError("This loader does not know module " + fullname)
+
+ def load_module(self, fullname):
+ try:
+ # in case of a reload
+ return sys.modules[fullname]
+ except KeyError:
+ pass
+ mod = self.__get_module(fullname)
+ if isinstance(mod, MovedModule):
+ mod = mod._resolve()
+ else:
+ mod.__loader__ = self
+ sys.modules[fullname] = mod
+ return mod
+
+ def is_package(self, fullname):
+ """
+ Return true, if the named module is a package.
+
+ We need this method to get correct spec objects with
+ Python 3.4 (see PEP451)
+ """
+ return hasattr(self.__get_module(fullname), "__path__")
+
+ def get_code(self, fullname):
+ """Return None
+
+ Required, if is_package is implemented"""
+ self.__get_module(fullname) # eventually raises ImportError
+ return None
+ get_source = get_code # same as get_code
+
+_importer = _SixMetaPathImporter(__name__)
+
class _MovedItems(_LazyModule):
"""Lazy loading of moved objects"""
+ __path__ = [] # mark as package
_moved_attributes = [
@@ -185,6 +230,8 @@ _moved_attributes = [
MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
MovedAttribute("reduce", "__builtin__", "functools"),
MovedAttribute("StringIO", "StringIO", "io"),
+ MovedAttribute("UserDict", "UserDict", "collections"),
+ MovedAttribute("UserList", "UserList", "collections"),
MovedAttribute("UserString", "UserString", "collections"),
MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
@@ -194,6 +241,7 @@ _moved_attributes = [
MovedModule("configparser", "ConfigParser"),
MovedModule("copyreg", "copy_reg"),
MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
+ MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),
MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
MovedModule("http_cookies", "Cookie", "http.cookies"),
MovedModule("html_entities", "htmlentitydefs", "html.entities"),
@@ -233,18 +281,19 @@ _moved_attributes = [
MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
- MovedModule("xmlrpc_server", "xmlrpclib", "xmlrpc.server"),
+ MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
MovedModule("winreg", "_winreg"),
]
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
if isinstance(attr, MovedModule):
- sys.modules[__name__ + ".moves." + attr.name] = attr
+ _importer._add_module(attr, "moves." + attr.name)
del attr
_MovedItems._moved_attributes = _moved_attributes
-moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves")
+moves = _MovedItems(__name__ + ".moves")
+_importer._add_module(moves, "moves")
class Module_six_moves_urllib_parse(_LazyModule):
@@ -275,7 +324,8 @@ del attr
Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
-sys.modules[__name__ + ".moves.urllib_parse"] = sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse")
+_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
+ "moves.urllib_parse", "moves.urllib.parse")
class Module_six_moves_urllib_error(_LazyModule):
@@ -293,7 +343,8 @@ del attr
Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
-sys.modules[__name__ + ".moves.urllib_error"] = sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error")
+_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
+ "moves.urllib_error", "moves.urllib.error")
class Module_six_moves_urllib_request(_LazyModule):
@@ -341,7 +392,8 @@ del attr
Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
-sys.modules[__name__ + ".moves.urllib_request"] = sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request")
+_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
+ "moves.urllib_request", "moves.urllib.request")
class Module_six_moves_urllib_response(_LazyModule):
@@ -360,7 +412,8 @@ del attr
Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
-sys.modules[__name__ + ".moves.urllib_response"] = sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response")
+_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
+ "moves.urllib_response", "moves.urllib.response")
class Module_six_moves_urllib_robotparser(_LazyModule):
@@ -376,22 +429,24 @@ del attr
Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
-sys.modules[__name__ + ".moves.urllib_robotparser"] = sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser")
+_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
+ "moves.urllib_robotparser", "moves.urllib.robotparser")
class Module_six_moves_urllib(types.ModuleType):
"""Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
- parse = sys.modules[__name__ + ".moves.urllib_parse"]
- error = sys.modules[__name__ + ".moves.urllib_error"]
- request = sys.modules[__name__ + ".moves.urllib_request"]
- response = sys.modules[__name__ + ".moves.urllib_response"]
- robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"]
+ __path__ = [] # mark as package
+ parse = _importer._get_module("moves.urllib_parse")
+ error = _importer._get_module("moves.urllib_error")
+ request = _importer._get_module("moves.urllib_request")
+ response = _importer._get_module("moves.urllib_response")
+ robotparser = _importer._get_module("moves.urllib_robotparser")
def __dir__(self):
return ['parse', 'error', 'request', 'response', 'robotparser']
-
-sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib")
+_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
+ "moves.urllib")
def add_move(move):
@@ -418,11 +473,6 @@ if PY3:
_func_code = "__code__"
_func_defaults = "__defaults__"
_func_globals = "__globals__"
-
- _iterkeys = "keys"
- _itervalues = "values"
- _iteritems = "items"
- _iterlists = "lists"
else:
_meth_func = "im_func"
_meth_self = "im_self"
@@ -432,11 +482,6 @@ else:
_func_defaults = "func_defaults"
_func_globals = "func_globals"
- _iterkeys = "iterkeys"
- _itervalues = "itervalues"
- _iteritems = "iteritems"
- _iterlists = "iterlists"
-
try:
advance_iterator = next
@@ -485,21 +530,37 @@ get_function_defaults = operator.attrgetter(_func_defaults)
get_function_globals = operator.attrgetter(_func_globals)
-def iterkeys(d, **kw):
- """Return an iterator over the keys of a dictionary."""
- return iter(getattr(d, _iterkeys)(**kw))
+if PY3:
+ def iterkeys(d, **kw):
+ return iter(d.keys(**kw))
-def itervalues(d, **kw):
- """Return an iterator over the values of a dictionary."""
- return iter(getattr(d, _itervalues)(**kw))
+ def itervalues(d, **kw):
+ return iter(d.values(**kw))
-def iteritems(d, **kw):
- """Return an iterator over the (key, value) pairs of a dictionary."""
- return iter(getattr(d, _iteritems)(**kw))
+ def iteritems(d, **kw):
+ return iter(d.items(**kw))
-def iterlists(d, **kw):
- """Return an iterator over the (key, [values]) pairs of a dictionary."""
- return iter(getattr(d, _iterlists)(**kw))
+ def iterlists(d, **kw):
+ return iter(d.lists(**kw))
+else:
+ def iterkeys(d, **kw):
+ return iter(d.iterkeys(**kw))
+
+ def itervalues(d, **kw):
+ return iter(d.itervalues(**kw))
+
+ def iteritems(d, **kw):
+ return iter(d.iteritems(**kw))
+
+ def iterlists(d, **kw):
+ return iter(d.iterlists(**kw))
+
+_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
+_add_doc(itervalues, "Return an iterator over the values of a dictionary.")
+_add_doc(iteritems,
+ "Return an iterator over the (key, value) pairs of a dictionary.")
+_add_doc(iterlists,
+ "Return an iterator over the (key, [values]) pairs of a dictionary.")
if PY3:
@@ -625,10 +686,26 @@ if print_ is None:
_add_doc(reraise, """Reraise an exception.""")
+if sys.version_info[0:2] < (3, 4):
+ def wraps(wrapped):
+ def wrapper(f):
+ f = functools.wraps(wrapped)(f)
+ f.__wrapped__ = wrapped
+ return f
+ return wrapper
+else:
+ wraps = functools.wraps
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
- return meta("NewBase", bases, {})
+ # This requires a bit of explanation: the basic idea is to make a dummy
+ # metaclass for one level of class instantiation that replaces itself with
+ # the actual metaclass.
+ class metaclass(meta):
+ def __new__(cls, name, this_bases, d):
+ return meta(name, bases, d)
+ return type.__new__(metaclass, 'temporary_class', (), {})
+
def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
@@ -644,3 +721,27 @@ def add_metaclass(metaclass):
orig_vars.pop(slots_var)
return metaclass(cls.__name__, cls.__bases__, orig_vars)
return wrapper
+
+# Complete the moves implementation.
+# This code is at the end of this module to speed up module loading.
+# Turn this module into a package.
+__path__ = [] # required for PEP 302 and PEP 451
+__package__ = __name__ # see PEP 366 @ReservedAssignment
+if globals().get("__spec__") is not None:
+ __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
+# Remove other six meta path importers, since they cause problems. This can
+# happen if six is removed from sys.modules and then reloaded. (Setuptools does
+# this for some reason.)
+if sys.meta_path:
+ for i, importer in enumerate(sys.meta_path):
+ # Here's some real nastiness: Another "instance" of the six module might
+ # be floating around. Therefore, we can't use isinstance() to check for
+ # the six meta path importer, since the other six instance will have
+ # inserted an importer with different class.
+ if (type(importer).__name__ == "_SixMetaPathImporter" and
+ importer.name == __name__):
+ del sys.meta_path[i]
+ break
+ del i, importer
+# Finally, add the importer to the meta path import hook.
+sys.meta_path.append(_importer)
diff --git a/Darwin/lib/python2.7/site-packages/sqlalchemy/cprocessors.so b/Darwin/lib/python2.7/site-packages/sqlalchemy/cprocessors.so
index 96f2ea5..4d86431 100755
Binary files a/Darwin/lib/python2.7/site-packages/sqlalchemy/cprocessors.so and b/Darwin/lib/python2.7/site-packages/sqlalchemy/cprocessors.so differ
diff --git a/Darwin/lib/python2.7/site-packages/sqlalchemy/cresultproxy.so b/Darwin/lib/python2.7/site-packages/sqlalchemy/cresultproxy.so
index 9e3f799..5757c3e 100755
Binary files a/Darwin/lib/python2.7/site-packages/sqlalchemy/cresultproxy.so and b/Darwin/lib/python2.7/site-packages/sqlalchemy/cresultproxy.so differ
diff --git a/Darwin/lib/python2.7/site-packages/sqlalchemy/cutils.so b/Darwin/lib/python2.7/site-packages/sqlalchemy/cutils.so
index ac74820..cf5c0d6 100755
Binary files a/Darwin/lib/python2.7/site-packages/sqlalchemy/cutils.so and b/Darwin/lib/python2.7/site-packages/sqlalchemy/cutils.so differ
diff --git a/Darwin/lib/python2.7/site-packages/twisted/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/__init__.py
deleted file mode 100644
index 7a819d9..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/__init__.py
+++ /dev/null
@@ -1,71 +0,0 @@
-# -*- test-case-name: twisted -*-
-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Twisted: The Framework Of Your Internet.
-"""
-
-def _checkRequirements():
- # Don't allow the user to run a version of Python we don't support.
- import sys
-
- version = getattr(sys, "version_info", (0,))
- if version < (2, 6):
- raise ImportError("Twisted requires Python 2.6 or later.")
- if version < (3, 0):
- required = "3.6.0"
- else:
- required = "4.0.0"
-
- if ("setuptools" in sys.modules and
- getattr(sys.modules["setuptools"],
- "_TWISTED_NO_CHECK_REQUIREMENTS", None) is not None):
- # Skip requirement checks, setuptools ought to take care of installing
- # the dependencies.
- return
-
- # Don't allow the user to run with a version of zope.interface we don't
- # support.
- required = "Twisted requires zope.interface %s or later" % (required,)
- try:
- from zope import interface
- except ImportError:
- # It isn't installed.
- raise ImportError(required + ": no module named zope.interface.")
- except:
- # It is installed but not compatible with this version of Python.
- raise ImportError(required + ".")
- try:
- # Try using the API that we need, which only works right with
- # zope.interface 3.6 (or 4.0 on Python 3)
- class IDummy(interface.Interface):
- pass
- @interface.implementer(IDummy)
- class Dummy(object):
- pass
- except TypeError:
- # It is installed but not compatible with this version of Python.
- raise ImportError(required + ".")
-
-_checkRequirements()
-
-# Ensure compat gets imported
-from twisted.python import compat
-
-# setup version
-from twisted._version import version
-__version__ = version.short()
-
-del compat
-
-# Deprecating lore.
-from twisted.python.versions import Version
-from twisted.python.deprecate import deprecatedModuleAttribute
-
-deprecatedModuleAttribute(
- Version("Twisted", 14, 0, 0),
- "Use Sphinx instead.",
- "twisted", "lore")
diff --git a/Darwin/lib/python2.7/site-packages/twisted/_version.py b/Darwin/lib/python2.7/site-packages/twisted/_version.py
deleted file mode 100644
index 1e7fd81..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/_version.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-# This is an auto-generated file. Do not edit it.
-
-"""
-Provides Twisted version information.
-"""
-
-from twisted.python import versions
-version = versions.Version('twisted', 14, 0, 0)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/application/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/application/__init__.py
deleted file mode 100644
index c155ca4..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/application/__init__.py
+++ /dev/null
@@ -1,7 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-"""
-Configuration objects for Twisted Applications
-"""
diff --git a/Darwin/lib/python2.7/site-packages/twisted/application/app.py b/Darwin/lib/python2.7/site-packages/twisted/application/app.py
deleted file mode 100644
index f0545d0..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/application/app.py
+++ /dev/null
@@ -1,664 +0,0 @@
-# -*- test-case-name: twisted.test.test_application,twisted.test.test_twistd -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-import sys, os, pdb, getpass, traceback, signal
-from operator import attrgetter
-
-from twisted.python import runtime, log, usage, failure, util, logfile
-from twisted.python.versions import Version
-from twisted.python.reflect import qual, namedAny
-from twisted.python.deprecate import deprecated
-from twisted.python.log import ILogObserver
-from twisted.persisted import sob
-from twisted.application import service, reactors
-from twisted.internet import defer
-from twisted import copyright, plugin
-
-# Expose the new implementation of installReactor at the old location.
-from twisted.application.reactors import installReactor
-from twisted.application.reactors import NoSuchReactor
-
-
-
-class _BasicProfiler(object):
- """
- @ivar saveStats: if C{True}, save the stats information instead of the
- human readable format
- @type saveStats: C{bool}
-
- @ivar profileOutput: the name of the file use to print profile data.
- @type profileOutput: C{str}
- """
-
- def __init__(self, profileOutput, saveStats):
- self.profileOutput = profileOutput
- self.saveStats = saveStats
-
-
- def _reportImportError(self, module, e):
- """
- Helper method to report an import error with a profile module. This
- has to be explicit because some of these modules are removed by
- distributions due to them being non-free.
- """
- s = "Failed to import module %s: %s" % (module, e)
- s += """
-This is most likely caused by your operating system not including
-the module due to it being non-free. Either do not use the option
---profile, or install the module; your operating system vendor
-may provide it in a separate package.
-"""
- raise SystemExit(s)
-
-
-
-class ProfileRunner(_BasicProfiler):
- """
- Runner for the standard profile module.
- """
-
- def run(self, reactor):
- """
- Run reactor under the standard profiler.
- """
- try:
- import profile
- except ImportError, e:
- self._reportImportError("profile", e)
-
- p = profile.Profile()
- p.runcall(reactor.run)
- if self.saveStats:
- p.dump_stats(self.profileOutput)
- else:
- tmp, sys.stdout = sys.stdout, open(self.profileOutput, 'a')
- try:
- p.print_stats()
- finally:
- sys.stdout, tmp = tmp, sys.stdout
- tmp.close()
-
-
-
-class HotshotRunner(_BasicProfiler):
- """
- Runner for the hotshot profile module.
- """
-
- def run(self, reactor):
- """
- Run reactor under the hotshot profiler.
- """
- try:
- import hotshot.stats
- except (ImportError, SystemExit), e:
- # Certain versions of Debian (and Debian derivatives) raise
- # SystemExit when importing hotshot if the "non-free" profiler
- # module is not installed. Someone eventually recognized this
- # as a bug and changed the Debian packaged Python to raise
- # ImportError instead. Handle both exception types here in
- # order to support the versions of Debian which have this
- # behavior. The bug report which prompted the introduction of
- # this highly undesirable behavior should be available online at
- # .
- # There seems to be no corresponding bug report which resulted
- # in the behavior being removed. -exarkun
- self._reportImportError("hotshot", e)
-
- # this writes stats straight out
- p = hotshot.Profile(self.profileOutput)
- p.runcall(reactor.run)
- if self.saveStats:
- # stats are automatically written to file, nothing to do
- return
- else:
- s = hotshot.stats.load(self.profileOutput)
- s.strip_dirs()
- s.sort_stats(-1)
- s.stream = open(self.profileOutput, 'w')
- s.print_stats()
- s.stream.close()
-
-
-
-class CProfileRunner(_BasicProfiler):
- """
- Runner for the cProfile module.
- """
-
- def run(self, reactor):
- """
- Run reactor under the cProfile profiler.
- """
- try:
- import cProfile, pstats
- except ImportError, e:
- self._reportImportError("cProfile", e)
-
- p = cProfile.Profile()
- p.runcall(reactor.run)
- if self.saveStats:
- p.dump_stats(self.profileOutput)
- else:
- stream = open(self.profileOutput, 'w')
- s = pstats.Stats(p, stream=stream)
- s.strip_dirs()
- s.sort_stats(-1)
- s.print_stats()
- stream.close()
-
-
-
-class AppProfiler(object):
- """
- Class which selects a specific profile runner based on configuration
- options.
-
- @ivar profiler: the name of the selected profiler.
- @type profiler: C{str}
- """
- profilers = {"profile": ProfileRunner, "hotshot": HotshotRunner,
- "cprofile": CProfileRunner}
-
- def __init__(self, options):
- saveStats = options.get("savestats", False)
- profileOutput = options.get("profile", None)
- self.profiler = options.get("profiler", "hotshot").lower()
- if self.profiler in self.profilers:
- profiler = self.profilers[self.profiler](profileOutput, saveStats)
- self.run = profiler.run
- else:
- raise SystemExit("Unsupported profiler name: %s" % (self.profiler,))
-
-
-
-class AppLogger(object):
- """
- Class managing logging faciliy of the application.
-
- @ivar _logfilename: The name of the file to which to log, if other than the
- default.
- @type _logfilename: C{str}
-
- @ivar _observerFactory: Callable object that will create a log observer, or
- None.
-
- @ivar _observer: log observer added at C{start} and removed at C{stop}.
- @type _observer: C{callable}
- """
- _observer = None
-
- def __init__(self, options):
- self._logfilename = options.get("logfile", "")
- self._observerFactory = options.get("logger") or None
-
-
- def start(self, application):
- """
- Initialize the logging system.
-
- If a customer logger was specified on the command line it will be
- used. If not, and an L{ILogObserver} component has been set on
- C{application}, then it will be used as the log observer. Otherwise a
- log observer will be created based on the command-line options for
- built-in loggers (e.g. C{--logfile}).
-
- @param application: The application on which to check for an
- L{ILogObserver}.
- """
- if self._observerFactory is not None:
- observer = self._observerFactory()
- else:
- observer = application.getComponent(ILogObserver, None)
-
- if observer is None:
- observer = self._getLogObserver()
- self._observer = observer
- log.startLoggingWithObserver(self._observer)
- self._initialLog()
-
-
- def _initialLog(self):
- """
- Print twistd start log message.
- """
- from twisted.internet import reactor
- log.msg("twistd %s (%s %s) starting up." % (copyright.version,
- sys.executable,
- runtime.shortPythonVersion()))
- log.msg('reactor class: %s.' % (qual(reactor.__class__),))
-
-
- def _getLogObserver(self):
- """
- Create a log observer to be added to the logging system before running
- this application.
- """
- if self._logfilename == '-' or not self._logfilename:
- logFile = sys.stdout
- else:
- logFile = logfile.LogFile.fromFullPath(self._logfilename)
- return log.FileLogObserver(logFile).emit
-
-
- def stop(self):
- """
- Print twistd stop log message.
- """
- log.msg("Server Shut Down.")
- if self._observer is not None:
- log.removeObserver(self._observer)
- self._observer = None
-
-
-
-def fixPdb():
- def do_stop(self, arg):
- self.clear_all_breaks()
- self.set_continue()
- from twisted.internet import reactor
- reactor.callLater(0, reactor.stop)
- return 1
-
-
- def help_stop(self):
- print """stop - Continue execution, then cleanly shutdown the twisted reactor."""
-
-
- def set_quit(self):
- os._exit(0)
-
- pdb.Pdb.set_quit = set_quit
- pdb.Pdb.do_stop = do_stop
- pdb.Pdb.help_stop = help_stop
-
-
-
-def runReactorWithLogging(config, oldstdout, oldstderr, profiler=None, reactor=None):
- """
- Start the reactor, using profiling if specified by the configuration, and
- log any error happening in the process.
-
- @param config: configuration of the twistd application.
- @type config: L{ServerOptions}
-
- @param oldstdout: initial value of C{sys.stdout}.
- @type oldstdout: C{file}
-
- @param oldstderr: initial value of C{sys.stderr}.
- @type oldstderr: C{file}
-
- @param profiler: object used to run the reactor with profiling.
- @type profiler: L{AppProfiler}
-
- @param reactor: The reactor to use. If C{None}, the global reactor will
- be used.
- """
- if reactor is None:
- from twisted.internet import reactor
- try:
- if config['profile']:
- if profiler is not None:
- profiler.run(reactor)
- elif config['debug']:
- sys.stdout = oldstdout
- sys.stderr = oldstderr
- if runtime.platformType == 'posix':
- signal.signal(signal.SIGUSR2, lambda *args: pdb.set_trace())
- signal.signal(signal.SIGINT, lambda *args: pdb.set_trace())
- fixPdb()
- pdb.runcall(reactor.run)
- else:
- reactor.run()
- except:
- if config['nodaemon']:
- file = oldstdout
- else:
- file = open("TWISTD-CRASH.log",'a')
- traceback.print_exc(file=file)
- file.flush()
-
-
-
-def getPassphrase(needed):
- if needed:
- return getpass.getpass('Passphrase: ')
- else:
- return None
-
-
-
-def getSavePassphrase(needed):
- if needed:
- passphrase = util.getPassword("Encryption passphrase: ")
- else:
- return None
-
-
-
-class ApplicationRunner(object):
- """
- An object which helps running an application based on a config object.
-
- Subclass me and implement preApplication and postApplication
- methods. postApplication generally will want to run the reactor
- after starting the application.
-
- @ivar config: The config object, which provides a dict-like interface.
-
- @ivar application: Available in postApplication, but not
- preApplication. This is the application object.
-
- @ivar profilerFactory: Factory for creating a profiler object, able to
- profile the application if options are set accordingly.
-
- @ivar profiler: Instance provided by C{profilerFactory}.
-
- @ivar loggerFactory: Factory for creating object responsible for logging.
-
- @ivar logger: Instance provided by C{loggerFactory}.
- """
- profilerFactory = AppProfiler
- loggerFactory = AppLogger
-
- def __init__(self, config):
- self.config = config
- self.profiler = self.profilerFactory(config)
- self.logger = self.loggerFactory(config)
-
-
- def run(self):
- """
- Run the application.
- """
- self.preApplication()
- self.application = self.createOrGetApplication()
-
- self.logger.start(self.application)
-
- self.postApplication()
- self.logger.stop()
-
-
- def startReactor(self, reactor, oldstdout, oldstderr):
- """
- Run the reactor with the given configuration. Subclasses should
- probably call this from C{postApplication}.
-
- @see: L{runReactorWithLogging}
- """
- runReactorWithLogging(
- self.config, oldstdout, oldstderr, self.profiler, reactor)
-
-
- def preApplication(self):
- """
- Override in subclass.
-
- This should set up any state necessary before loading and
- running the Application.
- """
- raise NotImplementedError()
-
-
- def postApplication(self):
- """
- Override in subclass.
-
- This will be called after the application has been loaded (so
- the C{application} attribute will be set). Generally this
- should start the application and run the reactor.
- """
- raise NotImplementedError()
-
-
- def createOrGetApplication(self):
- """
- Create or load an Application based on the parameters found in the
- given L{ServerOptions} instance.
-
- If a subcommand was used, the L{service.IServiceMaker} that it
- represents will be used to construct a service to be added to
- a newly-created Application.
-
- Otherwise, an application will be loaded based on parameters in
- the config.
- """
- if self.config.subCommand:
- # If a subcommand was given, it's our responsibility to create
- # the application, instead of load it from a file.
-
- # loadedPlugins is set up by the ServerOptions.subCommands
- # property, which is iterated somewhere in the bowels of
- # usage.Options.
- plg = self.config.loadedPlugins[self.config.subCommand]
- ser = plg.makeService(self.config.subOptions)
- application = service.Application(plg.tapname)
- ser.setServiceParent(application)
- else:
- passphrase = getPassphrase(self.config['encrypted'])
- application = getApplication(self.config, passphrase)
- return application
-
-
-
-def getApplication(config, passphrase):
- s = [(config[t], t)
- for t in ['python', 'source', 'file'] if config[t]][0]
- filename, style = s[0], {'file':'pickle'}.get(s[1],s[1])
- try:
- log.msg("Loading %s..." % filename)
- application = service.loadApplication(filename, style, passphrase)
- log.msg("Loaded.")
- except Exception, e:
- s = "Failed to load application: %s" % e
- if isinstance(e, KeyError) and e.args[0] == "application":
- s += """
-Could not find 'application' in the file. To use 'twistd -y', your .tac
-file must create a suitable object (e.g., by calling service.Application())
-and store it in a variable named 'application'. twistd loads your .tac file
-and scans the global variables for one of this name.
-
-Please read the 'Using Application' HOWTO for details.
-"""
- traceback.print_exc(file=log.logfile)
- log.msg(s)
- log.deferr()
- sys.exit('\n' + s + '\n')
- return application
-
-
-
-def _reactorAction():
- return usage.CompleteList([r.shortName for r in reactors.getReactorTypes()])
-
-
-class ReactorSelectionMixin:
- """
- Provides options for selecting a reactor to install.
-
- If a reactor is installed, the short name which was used to locate it is
- saved as the value for the C{"reactor"} key.
- """
- compData = usage.Completions(
- optActions={"reactor": _reactorAction})
-
- messageOutput = sys.stdout
- _getReactorTypes = staticmethod(reactors.getReactorTypes)
-
-
- def opt_help_reactors(self):
- """
- Display a list of possibly available reactor names.
- """
- rcts = sorted(self._getReactorTypes(), key=attrgetter('shortName'))
- for r in rcts:
- self.messageOutput.write(' %-4s\t%s\n' %
- (r.shortName, r.description))
- raise SystemExit(0)
-
-
- def opt_reactor(self, shortName):
- """
- Which reactor to use (see --help-reactors for a list of possibilities)
- """
- # Actually actually actually install the reactor right at this very
- # moment, before any other code (for example, a sub-command plugin)
- # runs and accidentally imports and installs the default reactor.
- #
- # This could probably be improved somehow.
- try:
- installReactor(shortName)
- except NoSuchReactor:
- msg = ("The specified reactor does not exist: '%s'.\n"
- "See the list of available reactors with "
- "--help-reactors" % (shortName,))
- raise usage.UsageError(msg)
- except Exception, e:
- msg = ("The specified reactor cannot be used, failed with error: "
- "%s.\nSee the list of available reactors with "
- "--help-reactors" % (e,))
- raise usage.UsageError(msg)
- else:
- self["reactor"] = shortName
- opt_r = opt_reactor
-
-
-
-
-class ServerOptions(usage.Options, ReactorSelectionMixin):
-
- longdesc = ("twistd reads a twisted.application.service.Application out "
- "of a file and runs it.")
-
- optFlags = [['savestats', None,
- "save the Stats object rather than the text output of "
- "the profiler."],
- ['no_save','o', "do not save state on shutdown"],
- ['encrypted', 'e',
- "The specified tap/aos file is encrypted."]]
-
- optParameters = [['logfile','l', None,
- "log to a specified file, - for stdout"],
- ['logger', None, None,
- "A fully-qualified name to a log observer factory to use "
- "for the initial log observer. Takes precedence over "
- "--logfile and --syslog (when available)."],
- ['profile', 'p', None,
- "Run in profile mode, dumping results to specified file"],
- ['profiler', None, "hotshot",
- "Name of the profiler to use (%s)." %
- ", ".join(AppProfiler.profilers)],
- ['file','f','twistd.tap',
- "read the given .tap file"],
- ['python','y', None,
- "read an application from within a Python file "
- "(implies -o)"],
- ['source', 's', None,
- "Read an application from a .tas file (AOT format)."],
- ['rundir','d','.',
- 'Change to a supplied directory before running']]
-
- compData = usage.Completions(
- mutuallyExclusive=[("file", "python", "source")],
- optActions={"file": usage.CompleteFiles("*.tap"),
- "python": usage.CompleteFiles("*.(tac|py)"),
- "source": usage.CompleteFiles("*.tas"),
- "rundir": usage.CompleteDirs()}
- )
-
- _getPlugins = staticmethod(plugin.getPlugins)
-
- def __init__(self, *a, **kw):
- self['debug'] = False
- usage.Options.__init__(self, *a, **kw)
-
-
- def opt_debug(self):
- """
- Run the application in the Python Debugger (implies nodaemon),
- sending SIGUSR2 will drop into debugger
- """
- defer.setDebugging(True)
- failure.startDebugMode()
- self['debug'] = True
- opt_b = opt_debug
-
-
- def opt_spew(self):
- """
- Print an insanely verbose log of everything that happens.
- Useful when debugging freezes or locks in complex code."""
- sys.settrace(util.spewer)
- try:
- import threading
- except ImportError:
- return
- threading.settrace(util.spewer)
-
-
- def parseOptions(self, options=None):
- if options is None:
- options = sys.argv[1:] or ["--help"]
- usage.Options.parseOptions(self, options)
-
-
- def postOptions(self):
- if self.subCommand or self['python']:
- self['no_save'] = True
- if self['logger'] is not None:
- try:
- self['logger'] = namedAny(self['logger'])
- except Exception, e:
- raise usage.UsageError("Logger '%s' could not be imported: %s"
- % (self['logger'], e))
-
-
- def subCommands(self):
- plugins = self._getPlugins(service.IServiceMaker)
- self.loadedPlugins = {}
- for plug in sorted(plugins, key=attrgetter('tapname')):
- self.loadedPlugins[plug.tapname] = plug
- yield (plug.tapname,
- None,
- # Avoid resolving the options attribute right away, in case
- # it's a property with a non-trivial getter (eg, one which
- # imports modules).
- lambda plug=plug: plug.options(),
- plug.description)
- subCommands = property(subCommands)
-
-
-
-def run(runApp, ServerOptions):
- config = ServerOptions()
- try:
- config.parseOptions()
- except usage.error, ue:
- print config
- print "%s: %s" % (sys.argv[0], ue)
- else:
- runApp(config)
-
-
-
-def convertStyle(filein, typein, passphrase, fileout, typeout, encrypt):
- application = service.loadApplication(filein, typein, passphrase)
- sob.IPersistable(application).setStyle(typeout)
- passphrase = getSavePassphrase(encrypt)
- if passphrase:
- fileout = None
- sob.IPersistable(application).save(filename=fileout, passphrase=passphrase)
-
-
-
-def startApplication(application, save):
- from twisted.internet import reactor
- service.IService(application).startService()
- if save:
- p = sob.IPersistable(application)
- reactor.addSystemEventTrigger('after', 'shutdown', p.save, 'shutdown')
- reactor.addSystemEventTrigger('before', 'shutdown',
- service.IService(application).stopService)
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/application/internet.py b/Darwin/lib/python2.7/site-packages/twisted/application/internet.py
deleted file mode 100644
index b5d913d..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/application/internet.py
+++ /dev/null
@@ -1,405 +0,0 @@
-# -*- test-case-name: twisted.application.test.test_internet,twisted.test.test_application,twisted.test.test_cooperator -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Reactor-based Services
-
-Here are services to run clients, servers and periodic services using
-the reactor.
-
-If you want to run a server service, L{StreamServerEndpointService} defines a
-service that can wrap an arbitrary L{IStreamServerEndpoint
-}
-as an L{IService}. See also L{twisted.application.strports.service} for
-constructing one of these directly from a descriptive string.
-
-Additionally, this module (dynamically) defines various Service subclasses that
-let you represent clients and servers in a Service hierarchy. Endpoints APIs
-should be preferred for stream server services, but since those APIs do not yet
-exist for clients or datagram services, many of these are still useful.
-
-They are as follows::
-
- TCPServer, TCPClient,
- UNIXServer, UNIXClient,
- SSLServer, SSLClient,
- UDPServer,
- UNIXDatagramServer, UNIXDatagramClient,
- MulticastServer
-
-These classes take arbitrary arguments in their constructors and pass
-them straight on to their respective reactor.listenXXX or
-reactor.connectXXX calls.
-
-For example, the following service starts a web server on port 8080:
-C{TCPServer(8080, server.Site(r))}. See the documentation for the
-reactor.listen/connect* methods for more information.
-"""
-
-from twisted.python import log
-from twisted.python.deprecate import deprecatedModuleAttribute
-from twisted.python.versions import Version
-from twisted.application import service
-from twisted.internet import task
-
-from twisted.internet.defer import CancelledError
-
-
-def _maybeGlobalReactor(maybeReactor):
- """
- @return: the argument, or the global reactor if the argument is C{None}.
- """
- if maybeReactor is None:
- from twisted.internet import reactor
- return reactor
- else:
- return maybeReactor
-
-
-class _VolatileDataService(service.Service):
-
- volatile = []
-
- def __getstate__(self):
- d = service.Service.__getstate__(self)
- for attr in self.volatile:
- if attr in d:
- del d[attr]
- return d
-
-
-
-class _AbstractServer(_VolatileDataService):
- """
- @cvar volatile: list of attribute to remove from pickling.
- @type volatile: C{list}
-
- @ivar method: the type of method to call on the reactor, one of B{TCP},
- B{UDP}, B{SSL} or B{UNIX}.
- @type method: C{str}
-
- @ivar reactor: the current running reactor.
- @type reactor: a provider of C{IReactorTCP}, C{IReactorUDP},
- C{IReactorSSL} or C{IReactorUnix}.
-
- @ivar _port: instance of port set when the service is started.
- @type _port: a provider of L{twisted.internet.interfaces.IListeningPort}.
- """
-
- volatile = ['_port']
- method = None
- reactor = None
-
- _port = None
-
- def __init__(self, *args, **kwargs):
- self.args = args
- if 'reactor' in kwargs:
- self.reactor = kwargs.pop("reactor")
- self.kwargs = kwargs
-
-
- def privilegedStartService(self):
- service.Service.privilegedStartService(self)
- self._port = self._getPort()
-
-
- def startService(self):
- service.Service.startService(self)
- if self._port is None:
- self._port = self._getPort()
-
-
- def stopService(self):
- service.Service.stopService(self)
- # TODO: if startup failed, should shutdown skip stopListening?
- # _port won't exist
- if self._port is not None:
- d = self._port.stopListening()
- del self._port
- return d
-
-
- def _getPort(self):
- """
- Wrapper around the appropriate listen method of the reactor.
-
- @return: the port object returned by the listen method.
- @rtype: an object providing
- L{twisted.internet.interfaces.IListeningPort}.
- """
- return getattr(_maybeGlobalReactor(self.reactor),
- 'listen%s' % (self.method,))(*self.args, **self.kwargs)
-
-
-
-class _AbstractClient(_VolatileDataService):
- """
- @cvar volatile: list of attribute to remove from pickling.
- @type volatile: C{list}
-
- @ivar method: the type of method to call on the reactor, one of B{TCP},
- B{UDP}, B{SSL} or B{UNIX}.
- @type method: C{str}
-
- @ivar reactor: the current running reactor.
- @type reactor: a provider of C{IReactorTCP}, C{IReactorUDP},
- C{IReactorSSL} or C{IReactorUnix}.
-
- @ivar _connection: instance of connection set when the service is started.
- @type _connection: a provider of L{twisted.internet.interfaces.IConnector}.
- """
- volatile = ['_connection']
- method = None
- reactor = None
-
- _connection = None
-
- def __init__(self, *args, **kwargs):
- self.args = args
- if 'reactor' in kwargs:
- self.reactor = kwargs.pop("reactor")
- self.kwargs = kwargs
-
-
- def startService(self):
- service.Service.startService(self)
- self._connection = self._getConnection()
-
-
- def stopService(self):
- service.Service.stopService(self)
- if self._connection is not None:
- self._connection.disconnect()
- del self._connection
-
-
- def _getConnection(self):
- """
- Wrapper around the appropriate connect method of the reactor.
-
- @return: the port object returned by the connect method.
- @rtype: an object providing L{twisted.internet.interfaces.IConnector}.
- """
- return getattr(_maybeGlobalReactor(self.reactor),
- 'connect%s' % (self.method,))(*self.args, **self.kwargs)
-
-
-
-_doc={
-'Client':
-"""Connect to %(tran)s
-
-Call reactor.connect%(tran)s when the service starts, with the
-arguments given to the constructor.
-""",
-'Server':
-"""Serve %(tran)s clients
-
-Call reactor.listen%(tran)s when the service starts, with the
-arguments given to the constructor. When the service stops,
-stop listening. See twisted.internet.interfaces for documentation
-on arguments to the reactor method.
-""",
-}
-
-import types
-for tran in 'TCP UNIX SSL UDP UNIXDatagram Multicast'.split():
- for side in 'Server Client'.split():
- if tran == "Multicast" and side == "Client":
- continue
- base = globals()['_Abstract'+side]
- doc = _doc[side] % vars()
- klass = types.ClassType(tran+side, (base,),
- {'method': tran, '__doc__': doc})
- globals()[tran+side] = klass
-
-
-
-deprecatedModuleAttribute(
- Version("Twisted", 13, 1, 0),
- "It relies upon IReactorUDP.connectUDP "
- "which was removed in Twisted 10. "
- "Use twisted.application.internet.UDPServer instead.",
- "twisted.application.internet", "UDPClient")
-
-
-
-class TimerService(_VolatileDataService):
- """
- Service to periodically call a function
-
- Every C{step} seconds call the given function with the given arguments.
- The service starts the calls when it starts, and cancels them
- when it stops.
-
- @ivar clock: Source of time. This defaults to L{None} which is
- causes L{twisted.internet.reactor} to be used.
- Feel free to set this to something else, but it probably ought to be
- set *before* calling L{startService}.
- @type clock: L{IReactorTime}
-
- @ivar call: Function and arguments to call periodically.
- @type call: L{tuple} of C{(callable, args, kwargs)}
- """
-
- volatile = ['_loop', '_loopFinished']
-
- def __init__(self, step, callable, *args, **kwargs):
- """
- @param step: The number of seconds between calls.
- @type step: L{float}
-
- @param callable: Function to call
- @type callable: L{callable}
-
- @param args: Positional arguments to pass to function
- @param kwargs: Keyword arguments to pass to function
- """
- self.step = step
- self.call = (callable, args, kwargs)
- self.clock = None
-
- def startService(self):
- service.Service.startService(self)
- callable, args, kwargs = self.call
- # we have to make a new LoopingCall each time we're started, because
- # an active LoopingCall remains active when serialized. If
- # LoopingCall were a _VolatileDataService, we wouldn't need to do
- # this.
- self._loop = task.LoopingCall(callable, *args, **kwargs)
- self._loop.clock = _maybeGlobalReactor(self.clock)
- self._loopFinished = self._loop.start(self.step, now=True)
- self._loopFinished.addErrback(self._failed)
-
- def _failed(self, why):
- # make a note that the LoopingCall is no longer looping, so we don't
- # try to shut it down a second time in stopService. I think this
- # should be in LoopingCall. -warner
- self._loop.running = False
- log.err(why)
-
- def stopService(self):
- """
- Stop the service.
-
- @rtype: L{Deferred}
- @return: a L{Deferred} which is fired when the
- currently running call (if any) is finished.
- """
- if self._loop.running:
- self._loop.stop()
- self._loopFinished.addCallback(lambda _:
- service.Service.stopService(self))
- return self._loopFinished
-
-
-
-class CooperatorService(service.Service):
- """
- Simple L{service.IService} which starts and stops a L{twisted.internet.task.Cooperator}.
- """
- def __init__(self):
- self.coop = task.Cooperator(started=False)
-
-
- def coiterate(self, iterator):
- return self.coop.coiterate(iterator)
-
-
- def startService(self):
- self.coop.start()
-
-
- def stopService(self):
- self.coop.stop()
-
-
-
-class StreamServerEndpointService(service.Service, object):
- """
- A L{StreamServerEndpointService} is an L{IService} which runs a server on a
- listening port described by an L{IStreamServerEndpoint
- }.
-
- @ivar factory: A server factory which will be used to listen on the
- endpoint.
-
- @ivar endpoint: An L{IStreamServerEndpoint
- } provider
- which will be used to listen when the service starts.
-
- @ivar _waitingForPort: a Deferred, if C{listen} has yet been invoked on the
- endpoint, otherwise None.
-
- @ivar _raiseSynchronously: Defines error-handling behavior for the case
- where C{listen(...)} raises an exception before C{startService} or
- C{privilegedStartService} have completed.
-
- @type _raiseSynchronously: C{bool}
-
- @since: 10.2
- """
-
- _raiseSynchronously = None
-
- def __init__(self, endpoint, factory):
- self.endpoint = endpoint
- self.factory = factory
- self._waitingForPort = None
-
-
- def privilegedStartService(self):
- """
- Start listening on the endpoint.
- """
- service.Service.privilegedStartService(self)
- self._waitingForPort = self.endpoint.listen(self.factory)
- raisedNow = []
- def handleIt(err):
- if self._raiseSynchronously:
- raisedNow.append(err)
- elif not err.check(CancelledError):
- log.err(err)
- self._waitingForPort.addErrback(handleIt)
- if raisedNow:
- raisedNow[0].raiseException()
-
-
- def startService(self):
- """
- Start listening on the endpoint, unless L{privilegedStartService} got
- around to it already.
- """
- service.Service.startService(self)
- if self._waitingForPort is None:
- self.privilegedStartService()
-
-
- def stopService(self):
- """
- Stop listening on the port if it is already listening, otherwise,
- cancel the attempt to listen.
-
- @return: a L{Deferred} which fires
- with C{None} when the port has stopped listening.
- """
- self._waitingForPort.cancel()
- def stopIt(port):
- if port is not None:
- return port.stopListening()
- d = self._waitingForPort.addCallback(stopIt)
- def stop(passthrough):
- self.running = False
- return passthrough
- d.addBoth(stop)
- return d
-
-
-
-__all__ = (['TimerService', 'CooperatorService', 'MulticastServer',
- 'StreamServerEndpointService'] +
- [tran+side
- for tran in 'TCP UNIX SSL UDP UNIXDatagram'.split()
- for side in 'Server Client'.split()])
diff --git a/Darwin/lib/python2.7/site-packages/twisted/application/reactors.py b/Darwin/lib/python2.7/site-packages/twisted/application/reactors.py
deleted file mode 100644
index cccddd1..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/application/reactors.py
+++ /dev/null
@@ -1,85 +0,0 @@
-# -*- test-case-name: twisted.test.test_application -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Plugin-based system for enumerating available reactors and installing one of
-them.
-"""
-
-from zope.interface import Interface, Attribute, implements
-
-from twisted.plugin import IPlugin, getPlugins
-from twisted.python.reflect import namedAny
-
-
-class IReactorInstaller(Interface):
- """
- Definition of a reactor which can probably be installed.
- """
- shortName = Attribute("""
- A brief string giving the user-facing name of this reactor.
- """)
-
- description = Attribute("""
- A longer string giving a user-facing description of this reactor.
- """)
-
- def install():
- """
- Install this reactor.
- """
-
- # TODO - A method which provides a best-guess as to whether this reactor
- # can actually be used in the execution environment.
-
-
-
-class NoSuchReactor(KeyError):
- """
- Raised when an attempt is made to install a reactor which cannot be found.
- """
-
-
-class Reactor(object):
- """
- @ivar moduleName: The fully-qualified Python name of the module of which
- the install callable is an attribute.
- """
- implements(IPlugin, IReactorInstaller)
-
-
- def __init__(self, shortName, moduleName, description):
- self.shortName = shortName
- self.moduleName = moduleName
- self.description = description
-
-
- def install(self):
- namedAny(self.moduleName).install()
-
-
-
-def getReactorTypes():
- """
- Return an iterator of L{IReactorInstaller} plugins.
- """
- return getPlugins(IReactorInstaller)
-
-
-
-def installReactor(shortName):
- """
- Install the reactor with the given C{shortName} attribute.
-
- @raise NoSuchReactor: If no reactor is found with a matching C{shortName}.
-
- @raise: anything that the specified reactor can raise when installed.
- """
- for installer in getReactorTypes():
- if installer.shortName == shortName:
- installer.install()
- from twisted.internet import reactor
- return reactor
- raise NoSuchReactor(shortName)
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/application/service.py b/Darwin/lib/python2.7/site-packages/twisted/application/service.py
deleted file mode 100644
index 66fef85..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/application/service.py
+++ /dev/null
@@ -1,413 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Service architecture for Twisted.
-
-Services are arranged in a hierarchy. At the leafs of the hierarchy,
-the services which actually interact with the outside world are started.
-Services can be named or anonymous -- usually, they will be named if
-there is need to access them through the hierarchy (from a parent or
-a sibling).
-
-Maintainer: Moshe Zadka
-"""
-
-from zope.interface import implements, Interface, Attribute
-
-from twisted.python.reflect import namedAny
-from twisted.python import components
-from twisted.internet import defer
-from twisted.persisted import sob
-from twisted.plugin import IPlugin
-
-
-class IServiceMaker(Interface):
- """
- An object which can be used to construct services in a flexible
- way.
-
- This interface should most often be implemented along with
- L{twisted.plugin.IPlugin}, and will most often be used by the
- 'twistd' command.
- """
- tapname = Attribute(
- "A short string naming this Twisted plugin, for example 'web' or "
- "'pencil'. This name will be used as the subcommand of 'twistd'.")
-
- description = Attribute(
- "A brief summary of the features provided by this "
- "Twisted application plugin.")
-
- options = Attribute(
- "A C{twisted.python.usage.Options} subclass defining the "
- "configuration options for this application.")
-
-
- def makeService(options):
- """
- Create and return an object providing
- L{twisted.application.service.IService}.
-
- @param options: A mapping (typically a C{dict} or
- L{twisted.python.usage.Options} instance) of configuration
- options to desired configuration values.
- """
-
-
-
-class ServiceMaker(object):
- """
- Utility class to simplify the definition of L{IServiceMaker} 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())
-
-
-
-class IService(Interface):
- """
- A service.
-
- Run start-up and shut-down code at the appropriate times.
-
- @type name: C{string}
- @ivar name: The name of the service (or None)
- @type running: C{boolean}
- @ivar running: Whether the service is running.
- """
-
- def setName(name):
- """
- Set the name of the service.
-
- @type name: C{str}
- @raise RuntimeError: Raised if the service already has a parent.
- """
-
- def setServiceParent(parent):
- """
- Set the parent of the service. This method is responsible for setting
- the C{parent} attribute on this service (the child service).
-
- @type parent: L{IServiceCollection}
- @raise RuntimeError: Raised if the service already has a parent
- or if the service has a name and the parent already has a child
- by that name.
- """
-
- def disownServiceParent():
- """
- Use this API to remove an L{IService} from an L{IServiceCollection}.
-
- This method is used symmetrically with L{setServiceParent} in that it
- sets the C{parent} attribute on the child.
-
- @rtype: L{Deferred}
- @return: a L{Deferred} which is triggered when the
- service has finished shutting down. If shutting down is immediate,
- a value can be returned (usually, C{None}).
- """
-
- def startService():
- """
- Start the service.
- """
-
- def stopService():
- """
- Stop the service.
-
- @rtype: L{Deferred}
- @return: a L{Deferred} which is triggered when the
- service has finished shutting down. If shutting down is immediate,
- a value can be returned (usually, C{None}).
- """
-
- def privilegedStartService():
- """
- Do preparation work for starting the service.
-
- Here things which should be done before changing directory,
- root or shedding privileges are done.
- """
-
-
-class Service:
- """
- Base class for services.
-
- Most services should inherit from this class. It handles the
- book-keeping reponsibilities of starting and stopping, as well
- as not serializing this book-keeping information.
- """
-
- implements(IService)
-
- running = 0
- name = None
- parent = None
-
- def __getstate__(self):
- dict = self.__dict__.copy()
- if "running" in dict:
- del dict['running']
- return dict
-
- def setName(self, name):
- if self.parent is not None:
- raise RuntimeError("cannot change name when parent exists")
- self.name = name
-
- def setServiceParent(self, parent):
- if self.parent is not None:
- self.disownServiceParent()
- parent = IServiceCollection(parent, parent)
- self.parent = parent
- self.parent.addService(self)
-
- def disownServiceParent(self):
- d = self.parent.removeService(self)
- self.parent = None
- return d
-
- def privilegedStartService(self):
- pass
-
- def startService(self):
- self.running = 1
-
- def stopService(self):
- self.running = 0
-
-
-
-class IServiceCollection(Interface):
- """
- Collection of services.
-
- Contain several services, and manage their start-up/shut-down.
- Services can be accessed by name if they have a name, and it
- is always possible to iterate over them.
- """
-
- def getServiceNamed(name):
- """
- Get the child service with a given name.
-
- @type name: C{str}
- @rtype: L{IService}
- @raise KeyError: Raised if the service has no child with the
- given name.
- """
-
- def __iter__():
- """
- Get an iterator over all child services.
- """
-
- def addService(service):
- """
- Add a child service.
-
- Only implementations of L{IService.setServiceParent} should use this
- method.
-
- @type service: L{IService}
- @raise RuntimeError: Raised if the service has a child with
- the given name.
- """
-
- def removeService(service):
- """
- Remove a child service.
-
- Only implementations of L{IService.disownServiceParent} should
- use this method.
-
- @type service: L{IService}
- @raise ValueError: Raised if the given service is not a child.
- @rtype: L{Deferred}
- @return: a L{Deferred} which is triggered when the
- service has finished shutting down. If shutting down is immediate,
- a value can be returned (usually, C{None}).
- """
-
-
-
-class MultiService(Service):
- """
- Straightforward Service Container.
-
- Hold a collection of services, and manage them in a simplistic
- way. No service will wait for another, but this object itself
- will not finish shutting down until all of its child services
- will finish.
- """
-
- implements(IServiceCollection)
-
- def __init__(self):
- self.services = []
- self.namedServices = {}
- self.parent = None
-
- def privilegedStartService(self):
- Service.privilegedStartService(self)
- for service in self:
- service.privilegedStartService()
-
- def startService(self):
- Service.startService(self)
- for service in self:
- service.startService()
-
- def stopService(self):
- Service.stopService(self)
- l = []
- services = list(self)
- services.reverse()
- for service in services:
- l.append(defer.maybeDeferred(service.stopService))
- return defer.DeferredList(l)
-
- def getServiceNamed(self, name):
- return self.namedServices[name]
-
- def __iter__(self):
- return iter(self.services)
-
- def addService(self, service):
- if service.name is not None:
- if service.name in self.namedServices:
- raise RuntimeError("cannot have two services with same name"
- " '%s'" % service.name)
- self.namedServices[service.name] = service
- self.services.append(service)
- if self.running:
- # It may be too late for that, but we will do our best
- service.privilegedStartService()
- service.startService()
-
- def removeService(self, service):
- if service.name:
- del self.namedServices[service.name]
- self.services.remove(service)
- if self.running:
- # Returning this so as not to lose information from the
- # MultiService.stopService deferred.
- return service.stopService()
- else:
- return None
-
-
-
-class IProcess(Interface):
- """
- Process running parameters.
-
- Represents parameters for how processes should be run.
- """
- processName = Attribute(
- """
- A C{str} giving the name the process should have in ps (or C{None}
- to leave the name alone).
- """)
-
- uid = Attribute(
- """
- An C{int} giving the user id as which the process should run (or
- C{None} to leave the UID alone).
- """)
-
- gid = Attribute(
- """
- An C{int} giving the group id as which the process should run (or
- C{None} to leave the GID alone).
- """)
-
-
-
-class Process:
- """
- Process running parameters.
-
- Sets up uid/gid in the constructor, and has a default
- of C{None} as C{processName}.
- """
- implements(IProcess)
- processName = None
-
- def __init__(self, uid=None, gid=None):
- """
- Set uid and gid.
-
- @param uid: The user ID as whom to execute the process. If
- this is C{None}, no attempt will be made to change the UID.
-
- @param gid: The group ID as whom to execute the process. If
- this is C{None}, no attempt will be made to change the GID.
- """
- self.uid = uid
- self.gid = gid
-
-
-def Application(name, uid=None, gid=None):
- """
- Return a compound class.
-
- Return an object supporting the L{IService}, L{IServiceCollection},
- L{IProcess} and L{sob.IPersistable} interfaces, with the given
- parameters. Always access the return value by explicit casting to
- one of the interfaces.
- """
- ret = components.Componentized()
- for comp in (MultiService(), sob.Persistent(ret, name), Process(uid, gid)):
- ret.addComponent(comp, ignoreClass=1)
- IService(ret).setName(name)
- return ret
-
-
-
-def loadApplication(filename, kind, passphrase=None):
- """
- Load Application from a given file.
-
- The serialization format it was saved in should be given as
- C{kind}, and is one of C{pickle}, C{source}, C{xml} or C{python}. If
- C{passphrase} is given, the application was encrypted with the
- given passphrase.
-
- @type filename: C{str}
- @type kind: C{str}
- @type passphrase: C{str}
- """
- if kind == 'python':
- application = sob.loadValueFromFile(filename, 'application', passphrase)
- else:
- application = sob.load(filename, kind, passphrase)
- return application
-
-
-__all__ = ['IServiceMaker', 'IService', 'Service',
- 'IServiceCollection', 'MultiService',
- 'IProcess', 'Process', 'Application', 'loadApplication']
diff --git a/Darwin/lib/python2.7/site-packages/twisted/application/strports.py b/Darwin/lib/python2.7/site-packages/twisted/application/strports.py
deleted file mode 100644
index 117d76f..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/application/strports.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# -*- test-case-name: twisted.test.test_strports -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Construct listening port services from a simple string description.
-
-@see: L{twisted.internet.endpoints.serverFromString}
-@see: L{twisted.internet.endpoints.clientFromString}
-"""
-
-import warnings
-
-from twisted.internet import endpoints
-from twisted.python.deprecate import deprecatedModuleAttribute
-from twisted.python.versions import Version
-from twisted.application.internet import StreamServerEndpointService
-
-
-
-def parse(description, factory, default='tcp'):
- """
- This function is deprecated as of Twisted 10.2.
-
- @see: L{twisted.internet.endpoints.server}
- """
- return endpoints._parseServer(description, factory, default)
-
-deprecatedModuleAttribute(
- Version("Twisted", 10, 2, 0),
- "in favor of twisted.internet.endpoints.serverFromString",
- __name__, "parse")
-
-
-
-_DEFAULT = object()
-
-def service(description, factory, default=_DEFAULT, reactor=None):
- """
- Return the service corresponding to a description.
-
- @param description: The description of the listening port, in the syntax
- described by L{twisted.internet.endpoints.server}.
-
- @type description: C{str}
-
- @param factory: The protocol factory which will build protocols for
- connections to this service.
-
- @type factory: L{twisted.internet.interfaces.IProtocolFactory}
-
- @type default: C{str} or C{None}
-
- @param default: Do not use this parameter. It has been deprecated since
- Twisted 10.2.0.
-
- @rtype: C{twisted.application.service.IService}
-
- @return: the service corresponding to a description of a reliable
- stream server.
-
- @see: L{twisted.internet.endpoints.serverFromString}
- """
- if reactor is None:
- from twisted.internet import reactor
- if default is _DEFAULT:
- default = None
- else:
- message = "The 'default' parameter was deprecated in Twisted 10.2.0."
- if default is not None:
- message += (
- " Use qualified endpoint descriptions; for example, "
- "'tcp:%s'." % (description,))
- warnings.warn(
- message=message, category=DeprecationWarning, stacklevel=2)
- svc = StreamServerEndpointService(
- endpoints._serverFromStringLegacy(reactor, description, default),
- factory)
- svc._raiseSynchronously = True
- return svc
-
-
-
-def listen(description, factory, default=None):
- """Listen on a port corresponding to a description
-
- @type description: C{str}
- @type factory: L{twisted.internet.interfaces.IProtocolFactory}
- @type default: C{str} or C{None}
- @rtype: C{twisted.internet.interfaces.IListeningPort}
- @return: the port corresponding to a description of a reliable
- virtual circuit server.
-
- See the documentation of the C{parse} function for description
- of the semantics of the arguments.
- """
- from twisted.internet import reactor
- name, args, kw = parse(description, factory, default)
- return getattr(reactor, 'listen'+name)(*args, **kw)
-
-
-
-__all__ = ['parse', 'service', 'listen']
diff --git a/Darwin/lib/python2.7/site-packages/twisted/application/test/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/application/test/__init__.py
deleted file mode 100644
index 3cb9635..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/application/test/__init__.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.internet.application}.
-"""
diff --git a/Darwin/lib/python2.7/site-packages/twisted/application/test/test_internet.py b/Darwin/lib/python2.7/site-packages/twisted/application/test/test_internet.py
deleted file mode 100644
index c019f7a..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/application/test/test_internet.py
+++ /dev/null
@@ -1,403 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for (new code in) L{twisted.application.internet}.
-"""
-
-import pickle
-
-from zope.interface import implements
-from zope.interface.verify import verifyClass
-
-from twisted.internet.protocol import Factory
-from twisted.trial.unittest import TestCase
-from twisted.application import internet
-from twisted.application.internet import (
- StreamServerEndpointService, TimerService)
-from twisted.internet.interfaces import IStreamServerEndpoint, IListeningPort
-from twisted.internet.defer import Deferred, CancelledError
-from twisted.internet import task
-from twisted.python.failure import Failure
-
-
-def fakeTargetFunction():
- """
- A fake target function for testing TimerService which does nothing.
- """
- pass
-
-
-
-class FakeServer(object):
- """
- In-memory implementation of L{IStreamServerEndpoint}.
-
- @ivar result: The L{Deferred} resulting from the call to C{listen}, after
- C{listen} has been called.
-
- @ivar factory: The factory passed to C{listen}.
-
- @ivar cancelException: The exception to errback C{self.result} when it is
- cancelled.
-
- @ivar port: The L{IListeningPort} which C{listen}'s L{Deferred} will fire
- with.
-
- @ivar listenAttempts: The number of times C{listen} has been invoked.
-
- @ivar failImmediately: If set, the exception to fail the L{Deferred}
- returned from C{listen} before it is returned.
- """
-
- implements(IStreamServerEndpoint)
-
- result = None
- factory = None
- failImmediately = None
- cancelException = CancelledError()
- listenAttempts = 0
-
- def __init__(self):
- self.port = FakePort()
-
-
- def listen(self, factory):
- """
- Return a Deferred and store it for future use. (Implementation of
- L{IStreamServerEndpoint}).
- """
- self.listenAttempts += 1
- self.factory = factory
- self.result = Deferred(
- canceller=lambda d: d.errback(self.cancelException))
- if self.failImmediately is not None:
- self.result.errback(self.failImmediately)
- return self.result
-
-
- def startedListening(self):
- """
- Test code should invoke this method after causing C{listen} to be
- invoked in order to fire the L{Deferred} previously returned from
- C{listen}.
- """
- self.result.callback(self.port)
-
-
- def stoppedListening(self):
- """
- Test code should invoke this method after causing C{stopListening} to
- be invoked on the port fired from the L{Deferred} returned from
- C{listen} in order to cause the L{Deferred} returned from
- C{stopListening} to fire.
- """
- self.port.deferred.callback(None)
-
-verifyClass(IStreamServerEndpoint, FakeServer)
-
-
-
-class FakePort(object):
- """
- Fake L{IListeningPort} implementation.
-
- @ivar deferred: The L{Deferred} returned by C{stopListening}.
- """
-
- implements(IListeningPort)
-
- deferred = None
-
- def stopListening(self):
- self.deferred = Deferred()
- return self.deferred
-
-verifyClass(IStreamServerEndpoint, FakeServer)
-
-
-
-class TestEndpointService(TestCase):
- """
- Tests for L{twisted.application.internet}.
- """
-
- def setUp(self):
- """
- Construct a stub server, a stub factory, and a
- L{StreamServerEndpointService} to test.
- """
- self.fakeServer = FakeServer()
- self.factory = Factory()
- self.svc = StreamServerEndpointService(self.fakeServer, self.factory)
-
-
- def test_privilegedStartService(self):
- """
- L{StreamServerEndpointService.privilegedStartService} calls its
- endpoint's C{listen} method with its factory.
- """
- self.svc.privilegedStartService()
- self.assertIdentical(self.factory, self.fakeServer.factory)
-
-
- def test_synchronousRaiseRaisesSynchronously(self, thunk=None):
- """
- L{StreamServerEndpointService.startService} should raise synchronously
- if the L{Deferred} returned by its wrapped
- L{IStreamServerEndpoint.listen} has already fired with an errback and
- the L{StreamServerEndpointService}'s C{_raiseSynchronously} flag has
- been set. This feature is necessary to preserve compatibility with old
- behavior of L{twisted.internet.strports.service}, which is to return a
- service which synchronously raises an exception from C{startService}
- (so that, among other things, twistd will not start running). However,
- since L{IStreamServerEndpoint.listen} may fail asynchronously, it is
- a bad idea to rely on this behavior.
- """
- self.fakeServer.failImmediately = ZeroDivisionError()
- self.svc._raiseSynchronously = True
- self.assertRaises(ZeroDivisionError, thunk or self.svc.startService)
-
-
- def test_synchronousRaisePrivileged(self):
- """
- L{StreamServerEndpointService.privilegedStartService} should behave the
- same as C{startService} with respect to
- L{TestEndpointService.test_synchronousRaiseRaisesSynchronously}.
- """
- self.test_synchronousRaiseRaisesSynchronously(
- self.svc.privilegedStartService)
-
-
- def test_failReportsError(self):
- """
- L{StreamServerEndpointService.startService} and
- L{StreamServerEndpointService.privilegedStartService} should both log
- an exception when the L{Deferred} returned from their wrapped
- L{IStreamServerEndpoint.listen} fails.
- """
- self.svc.startService()
- self.fakeServer.result.errback(ZeroDivisionError())
- logged = self.flushLoggedErrors(ZeroDivisionError)
- self.assertEqual(len(logged), 1)
-
-
- def test_synchronousFailReportsError(self):
- """
- Without the C{_raiseSynchronously} compatibility flag, failing
- immediately has the same behavior as failing later; it logs the error.
- """
- self.fakeServer.failImmediately = ZeroDivisionError()
- self.svc.startService()
- logged = self.flushLoggedErrors(ZeroDivisionError)
- self.assertEqual(len(logged), 1)
-
-
- def test_startServiceUnstarted(self):
- """
- L{StreamServerEndpointService.startService} sets the C{running} flag,
- and calls its endpoint's C{listen} method with its factory, if it
- has not yet been started.
- """
- self.svc.startService()
- self.assertIdentical(self.factory, self.fakeServer.factory)
- self.assertEqual(self.svc.running, True)
-
-
- def test_startServiceStarted(self):
- """
- L{StreamServerEndpointService.startService} sets the C{running} flag,
- but nothing else, if the service has already been started.
- """
- self.test_privilegedStartService()
- self.svc.startService()
- self.assertEqual(self.fakeServer.listenAttempts, 1)
- self.assertEqual(self.svc.running, True)
-
-
- def test_stopService(self):
- """
- L{StreamServerEndpointService.stopService} calls C{stopListening} on
- the L{IListeningPort} returned from its endpoint, returns the
- C{Deferred} from stopService, and sets C{running} to C{False}.
- """
- self.svc.privilegedStartService()
- self.fakeServer.startedListening()
- # Ensure running gets set to true
- self.svc.startService()
- result = self.svc.stopService()
- l = []
- result.addCallback(l.append)
- self.assertEqual(len(l), 0)
- self.fakeServer.stoppedListening()
- self.assertEqual(len(l), 1)
- self.assertFalse(self.svc.running)
-
-
- def test_stopServiceBeforeStartFinished(self):
- """
- L{StreamServerEndpointService.stopService} cancels the L{Deferred}
- returned by C{listen} if it has not yet fired. No error will be logged
- about the cancellation of the listen attempt.
- """
- self.svc.privilegedStartService()
- result = self.svc.stopService()
- l = []
- result.addBoth(l.append)
- self.assertEqual(l, [None])
- self.assertEqual(self.flushLoggedErrors(CancelledError), [])
-
-
- def test_stopServiceCancelStartError(self):
- """
- L{StreamServerEndpointService.stopService} cancels the L{Deferred}
- returned by C{listen} if it has not fired yet. An error will be logged
- if the resulting exception is not L{CancelledError}.
- """
- self.fakeServer.cancelException = ZeroDivisionError()
- self.svc.privilegedStartService()
- result = self.svc.stopService()
- l = []
- result.addCallback(l.append)
- self.assertEqual(l, [None])
- stoppingErrors = self.flushLoggedErrors(ZeroDivisionError)
- self.assertEqual(len(stoppingErrors), 1)
-
-
-
-class TestTimerService(TestCase):
- """
- Tests for L{twisted.application.internet.TimerService}.
-
- @type timer: L{TimerService}
- @ivar timer: service to test
-
- @type clock: L{task.Clock}
- @ivar clock: source of time
-
- @type deferred: L{Deferred}
- @ivar deferred: deferred returned by L{TestTimerService.call}.
- """
-
- def setUp(self):
- self.timer = TimerService(2, self.call)
- self.clock = self.timer.clock = task.Clock()
- self.deferred = Deferred()
-
-
- def call(self):
- """
- Function called by L{TimerService} being tested.
-
- @returns: C{self.deferred}
- @rtype: L{Deferred}
- """
- return self.deferred
-
-
- def test_startService(self):
- """
- When L{TimerService.startService} is called, it marks itself
- as running, creates a L{task.LoopingCall} and starts it.
- """
- self.timer.startService()
- self.assertTrue(self.timer.running, "Service is started")
- self.assertIsInstance(self.timer._loop, task.LoopingCall)
- self.assertIdentical(self.clock, self.timer._loop.clock)
- self.assertTrue(self.timer._loop.running, "LoopingCall is started")
-
-
- def test_startServiceRunsCallImmediately(self):
- """
- When L{TimerService.startService} is called, it calls the function
- immediately.
- """
- result = []
- self.timer.call = (result.append, (None,), {})
- self.timer.startService()
- self.assertEqual([None], result)
-
-
- def test_startServiceUsesGlobalReactor(self):
- """
- L{TimerService.startService} uses L{internet._maybeGlobalReactor} to
- choose the reactor to pass to L{task.LoopingCall}
- uses the global reactor.
- """
- otherClock = task.Clock()
- def getOtherClock(maybeReactor):
- return otherClock
- self.patch(internet, "_maybeGlobalReactor", getOtherClock)
- self.timer.startService()
- self.assertIdentical(otherClock, self.timer._loop.clock)
-
-
- def test_stopServiceWaits(self):
- """
- When L{TimerService.stopService} is called while a call is in progress.
- the L{Deferred} returned doesn't fire until after the call finishes.
- """
- self.timer.startService()
- d = self.timer.stopService()
- self.assertNoResult(d)
- self.assertEqual(True, self.timer.running)
- self.deferred.callback(object())
- self.assertIdentical(self.successResultOf(d), None)
-
-
- def test_stopServiceImmediately(self):
- """
- When L{TimerService.stopService} is called while a call isn't in progress.
- the L{Deferred} returned has already been fired.
- """
- self.timer.startService()
- self.deferred.callback(object())
- d = self.timer.stopService()
- self.assertIdentical(self.successResultOf(d), None)
-
-
- def test_failedCallLogsError(self):
- """
- When function passed to L{TimerService} returns a deferred that errbacks,
- the exception is logged, and L{TimerService.stopService} doesn't raise an error.
- """
- self.timer.startService()
- self.deferred.errback(Failure(ZeroDivisionError()))
- errors = self.flushLoggedErrors(ZeroDivisionError)
- self.assertEqual(1, len(errors))
- d = self.timer.stopService()
- self.assertIdentical(self.successResultOf(d), None)
-
-
- def test_pickleTimerServiceNotPickleLoop(self):
- """
- When pickling L{internet.TimerService}, it won't pickle
- L{internet.TimerService._loop}.
- """
- # We need a pickleable callable to test pickling TimerService. So we
- # can't use self.timer
- timer = TimerService(1, fakeTargetFunction)
- timer.startService()
- dumpedTimer = pickle.dumps(timer)
- timer.stopService()
- loadedTimer = pickle.loads(dumpedTimer)
- nothing = object()
- value = getattr(loadedTimer, "_loop", nothing)
- self.assertIdentical(nothing, value)
-
-
- def test_pickleTimerServiceNotPickleLoopFinished(self):
- """
- When pickling L{internet.TimerService}, it won't pickle
- L{internet.TimerService._loopFinished}.
- """
- # We need a pickleable callable to test pickling TimerService. So we
- # can't use self.timer
- timer = TimerService(1, fakeTargetFunction)
- timer.startService()
- dumpedTimer = pickle.dumps(timer)
- timer.stopService()
- loadedTimer = pickle.loads(dumpedTimer)
- nothing = object()
- value = getattr(loadedTimer, "_loopFinished", nothing)
- self.assertIdentical(nothing, value)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/conch/__init__.py
deleted file mode 100644
index d7ce597..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/__init__.py
+++ /dev/null
@@ -1,18 +0,0 @@
-# -*- test-case-name: twisted.conch.test -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-
-"""
-Twisted.Conch: The Twisted Shell. Terminal emulation, SSHv2 and telnet.
-
-Currently this contains the SSHv2 implementation, but it may work over other
-protocols in the future. (i.e. Telnet)
-
-Maintainer: Paul Swartz
-"""
-
-from twisted.conch._version import version
-__version__ = version.short()
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/_version.py b/Darwin/lib/python2.7/site-packages/twisted/conch/_version.py
deleted file mode 100644
index 225f342..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/_version.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-# This is an auto-generated file. Do not edit it.
-
-"""
-Provides Twisted version information.
-"""
-
-from twisted.python import versions
-version = versions.Version('twisted.conch', 14, 0, 0)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/avatar.py b/Darwin/lib/python2.7/site-packages/twisted/conch/avatar.py
deleted file mode 100644
index 0de3733..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/avatar.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_conch -*-
-from interfaces import IConchUser
-from error import ConchError
-from ssh.connection import OPEN_UNKNOWN_CHANNEL_TYPE
-from twisted.python import log
-from zope import interface
-
-class ConchUser:
- interface.implements(IConchUser)
-
- def __init__(self):
- self.channelLookup = {}
- self.subsystemLookup = {}
-
- def lookupChannel(self, channelType, windowSize, maxPacket, data):
- klass = self.channelLookup.get(channelType, None)
- if not klass:
- raise ConchError(OPEN_UNKNOWN_CHANNEL_TYPE, "unknown channel")
- else:
- return klass(remoteWindow=windowSize,
- remoteMaxPacket=maxPacket,
- data=data, avatar=self)
-
- def lookupSubsystem(self, subsystem, data):
- log.msg(repr(self.subsystemLookup))
- klass = self.subsystemLookup.get(subsystem, None)
- if not klass:
- return False
- return klass(data, avatar=self)
-
- def gotGlobalRequest(self, requestType, data):
- # XXX should this use method dispatch?
- requestType = requestType.replace('-','_')
- f = getattr(self, "global_%s" % requestType, None)
- if not f:
- return 0
- return f(data)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/checkers.py b/Darwin/lib/python2.7/site-packages/twisted/conch/checkers.py
deleted file mode 100644
index e071d7e..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/checkers.py
+++ /dev/null
@@ -1,307 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_checkers -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Provide L{ICredentialsChecker} implementations to be used in Conch protocols.
-"""
-
-import base64, binascii, errno
-try:
- import pwd
-except ImportError:
- pwd = None
-else:
- import crypt
-
-try:
- # Python 2.5 got spwd to interface with shadow passwords
- import spwd
-except ImportError:
- spwd = None
- try:
- import shadow
- except ImportError:
- shadow = None
-else:
- shadow = None
-
-try:
- from twisted.cred import pamauth
-except ImportError:
- pamauth = None
-
-from zope.interface import implements, providedBy
-
-from twisted.conch import error
-from twisted.conch.ssh import keys
-from twisted.cred.checkers import ICredentialsChecker
-from twisted.cred.credentials import IUsernamePassword, ISSHPrivateKey
-from twisted.cred.error import UnauthorizedLogin, UnhandledCredentials
-from twisted.internet import defer
-from twisted.python import failure, reflect, log
-from twisted.python.util import runAsEffectiveUser
-from twisted.python.filepath import FilePath
-
-
-
-def verifyCryptedPassword(crypted, pw):
- return crypt.crypt(pw, crypted) == crypted
-
-
-
-def _pwdGetByName(username):
- """
- Look up a user in the /etc/passwd database using the pwd module. If the
- pwd module is not available, return None.
-
- @param username: the username of the user to return the passwd database
- information for.
- """
- if pwd is None:
- return None
- return pwd.getpwnam(username)
-
-
-
-def _shadowGetByName(username):
- """
- Look up a user in the /etc/shadow database using the spwd or shadow
- modules. If neither module is available, return None.
-
- @param username: the username of the user to return the shadow database
- information for.
- """
- if spwd is not None:
- f = spwd.getspnam
- elif shadow is not None:
- f = shadow.getspnam
- else:
- return None
- return runAsEffectiveUser(0, 0, f, username)
-
-
-
-class UNIXPasswordDatabase:
- """
- A checker which validates users out of the UNIX password databases, or
- databases of a compatible format.
-
- @ivar _getByNameFunctions: a C{list} of functions which are called in order
- to valid a user. The default value is such that the /etc/passwd
- database will be tried first, followed by the /etc/shadow database.
- """
- credentialInterfaces = IUsernamePassword,
- implements(ICredentialsChecker)
-
-
- def __init__(self, getByNameFunctions=None):
- if getByNameFunctions is None:
- getByNameFunctions = [_pwdGetByName, _shadowGetByName]
- self._getByNameFunctions = getByNameFunctions
-
-
- def requestAvatarId(self, credentials):
- for func in self._getByNameFunctions:
- try:
- pwnam = func(credentials.username)
- except KeyError:
- return defer.fail(UnauthorizedLogin("invalid username"))
- else:
- if pwnam is not None:
- crypted = pwnam[1]
- if crypted == '':
- continue
- if verifyCryptedPassword(crypted, credentials.password):
- return defer.succeed(credentials.username)
- # fallback
- return defer.fail(UnauthorizedLogin("unable to verify password"))
-
-
-
-class SSHPublicKeyDatabase:
- """
- Checker that authenticates SSH public keys, based on public keys listed in
- authorized_keys and authorized_keys2 files in user .ssh/ directories.
- """
- implements(ICredentialsChecker)
-
- credentialInterfaces = (ISSHPrivateKey,)
-
- _userdb = pwd
-
- def requestAvatarId(self, credentials):
- d = defer.maybeDeferred(self.checkKey, credentials)
- d.addCallback(self._cbRequestAvatarId, credentials)
- d.addErrback(self._ebRequestAvatarId)
- return d
-
- def _cbRequestAvatarId(self, validKey, credentials):
- """
- Check whether the credentials themselves are valid, now that we know
- if the key matches the user.
-
- @param validKey: A boolean indicating whether or not the public key
- matches a key in the user's authorized_keys file.
-
- @param credentials: The credentials offered by the user.
- @type credentials: L{ISSHPrivateKey} provider
-
- @raise UnauthorizedLogin: (as a failure) if the key does not match the
- user in C{credentials}. Also raised if the user provides an invalid
- signature.
-
- @raise ValidPublicKey: (as a failure) if the key matches the user but
- the credentials do not include a signature. See
- L{error.ValidPublicKey} for more information.
-
- @return: The user's username, if authentication was successful.
- """
- if not validKey:
- return failure.Failure(UnauthorizedLogin("invalid key"))
- if not credentials.signature:
- return failure.Failure(error.ValidPublicKey())
- else:
- try:
- pubKey = keys.Key.fromString(credentials.blob)
- if pubKey.verify(credentials.signature, credentials.sigData):
- return credentials.username
- except: # any error should be treated as a failed login
- log.err()
- return failure.Failure(UnauthorizedLogin('error while verifying key'))
- return failure.Failure(UnauthorizedLogin("unable to verify key"))
-
-
- def getAuthorizedKeysFiles(self, credentials):
- """
- Return a list of L{FilePath} instances for I{authorized_keys} files
- which might contain information about authorized keys for the given
- credentials.
-
- On OpenSSH servers, the default location of the file containing the
- list of authorized public keys is
- U{$HOME/.ssh/authorized_keys}.
-
- I{$HOME/.ssh/authorized_keys2} is also returned, though it has been
- U{deprecated by OpenSSH since
- 2001}.
-
- @return: A list of L{FilePath} instances to files with the authorized keys.
- """
- pwent = self._userdb.getpwnam(credentials.username)
- root = FilePath(pwent.pw_dir).child('.ssh')
- files = ['authorized_keys', 'authorized_keys2']
- return [root.child(f) for f in files]
-
-
- def checkKey(self, credentials):
- """
- Retrieve files containing authorized keys and check against user
- credentials.
- """
- ouid, ogid = self._userdb.getpwnam(credentials.username)[2:4]
- for filepath in self.getAuthorizedKeysFiles(credentials):
- if not filepath.exists():
- continue
- try:
- lines = filepath.open()
- except IOError, e:
- if e.errno == errno.EACCES:
- lines = runAsEffectiveUser(ouid, ogid, filepath.open)
- else:
- raise
- for l in lines:
- l2 = l.split()
- if len(l2) < 2:
- continue
- try:
- if base64.decodestring(l2[1]) == credentials.blob:
- return True
- except binascii.Error:
- continue
- return False
-
- def _ebRequestAvatarId(self, f):
- if not f.check(UnauthorizedLogin):
- log.msg(f)
- return failure.Failure(UnauthorizedLogin("unable to get avatar id"))
- return f
-
-
-class SSHProtocolChecker:
- """
- SSHProtocolChecker is a checker that requires multiple authentications
- to succeed. To add a checker, call my registerChecker method with
- the checker and the interface.
-
- After each successful authenticate, I call my areDone method with the
- avatar id. To get a list of the successful credentials for an avatar id,
- use C{SSHProcotolChecker.successfulCredentials[avatarId]}. If L{areDone}
- returns True, the authentication has succeeded.
- """
-
- implements(ICredentialsChecker)
-
- def __init__(self):
- self.checkers = {}
- self.successfulCredentials = {}
-
- def get_credentialInterfaces(self):
- return self.checkers.keys()
-
- credentialInterfaces = property(get_credentialInterfaces)
-
- def registerChecker(self, checker, *credentialInterfaces):
- if not credentialInterfaces:
- credentialInterfaces = checker.credentialInterfaces
- for credentialInterface in credentialInterfaces:
- self.checkers[credentialInterface] = checker
-
- def requestAvatarId(self, credentials):
- """
- Part of the L{ICredentialsChecker} interface. Called by a portal with
- some credentials to check if they'll authenticate a user. We check the
- interfaces that the credentials provide against our list of acceptable
- checkers. If one of them matches, we ask that checker to verify the
- credentials. If they're valid, we call our L{_cbGoodAuthentication}
- method to continue.
-
- @param credentials: the credentials the L{Portal} wants us to verify
- """
- ifac = providedBy(credentials)
- for i in ifac:
- c = self.checkers.get(i)
- if c is not None:
- d = defer.maybeDeferred(c.requestAvatarId, credentials)
- return d.addCallback(self._cbGoodAuthentication,
- credentials)
- return defer.fail(UnhandledCredentials("No checker for %s" % \
- ', '.join(map(reflect.qual, ifac))))
-
- def _cbGoodAuthentication(self, avatarId, credentials):
- """
- Called if a checker has verified the credentials. We call our
- L{areDone} method to see if the whole of the successful authentications
- are enough. If they are, we return the avatar ID returned by the first
- checker.
- """
- if avatarId not in self.successfulCredentials:
- self.successfulCredentials[avatarId] = []
- self.successfulCredentials[avatarId].append(credentials)
- if self.areDone(avatarId):
- del self.successfulCredentials[avatarId]
- return avatarId
- else:
- raise error.NotEnoughAuthentication()
-
- def areDone(self, avatarId):
- """
- Override to determine if the authentication is finished for a given
- avatarId.
-
- @param avatarId: the avatar returned by the first checker. For
- this checker to function correctly, all the checkers must
- return the same avatar ID.
- """
- return True
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/client/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/conch/client/__init__.py
deleted file mode 100644
index f55d474..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/client/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-"""
-Client support code for Conch.
-
-Maintainer: Paul Swartz
-"""
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/client/agent.py b/Darwin/lib/python2.7/site-packages/twisted/conch/client/agent.py
deleted file mode 100644
index 50a8fea..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/client/agent.py
+++ /dev/null
@@ -1,73 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_default -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Accesses the key agent for user authentication.
-
-Maintainer: Paul Swartz
-"""
-
-import os
-
-from twisted.conch.ssh import agent, channel, keys
-from twisted.internet import protocol, reactor
-from twisted.python import log
-
-
-
-class SSHAgentClient(agent.SSHAgentClient):
-
- def __init__(self):
- agent.SSHAgentClient.__init__(self)
- self.blobs = []
-
-
- def getPublicKeys(self):
- return self.requestIdentities().addCallback(self._cbPublicKeys)
-
-
- def _cbPublicKeys(self, blobcomm):
- log.msg('got %i public keys' % len(blobcomm))
- self.blobs = [x[0] for x in blobcomm]
-
-
- def getPublicKey(self):
- """
- Return a L{Key} from the first blob in C{self.blobs}, if any, or
- return C{None}.
- """
- if self.blobs:
- return keys.Key.fromString(self.blobs.pop(0))
- return None
-
-
-
-class SSHAgentForwardingChannel(channel.SSHChannel):
-
- def channelOpen(self, specificData):
- cc = protocol.ClientCreator(reactor, SSHAgentForwardingLocal)
- d = cc.connectUNIX(os.environ['SSH_AUTH_SOCK'])
- d.addCallback(self._cbGotLocal)
- d.addErrback(lambda x:self.loseConnection())
- self.buf = ''
-
-
- def _cbGotLocal(self, local):
- self.local = local
- self.dataReceived = self.local.transport.write
- self.local.dataReceived = self.write
-
-
- def dataReceived(self, data):
- self.buf += data
-
-
- def closed(self):
- if self.local:
- self.local.loseConnection()
- self.local = None
-
-
-class SSHAgentForwardingLocal(protocol.Protocol):
- pass
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/client/connect.py b/Darwin/lib/python2.7/site-packages/twisted/conch/client/connect.py
deleted file mode 100644
index dc5fe22..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/client/connect.py
+++ /dev/null
@@ -1,21 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-import direct
-
-connectTypes = {"direct" : direct.connect}
-
-def connect(host, port, options, verifyHostKey, userAuthObject):
- useConnects = ['direct']
- return _ebConnect(None, useConnects, host, port, options, verifyHostKey,
- userAuthObject)
-
-def _ebConnect(f, useConnects, host, port, options, vhk, uao):
- if not useConnects:
- return f
- connectType = useConnects.pop(0)
- f = connectTypes[connectType]
- d = f(host, port, options, vhk, uao)
- d.addErrback(_ebConnect, useConnects, host, port, options, vhk, uao)
- return d
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/client/default.py b/Darwin/lib/python2.7/site-packages/twisted/conch/client/default.py
deleted file mode 100644
index 42c3c7a..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/client/default.py
+++ /dev/null
@@ -1,260 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_knownhosts,twisted.conch.test.test_default -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Various classes and functions for implementing user-interaction in the
-command-line conch client.
-
-You probably shouldn't use anything in this module directly, since it assumes
-you are sitting at an interactive terminal. For example, to programmatically
-interact with a known_hosts database, use L{twisted.conch.client.knownhosts}.
-"""
-
-from twisted.python import log
-from twisted.python.filepath import FilePath
-
-from twisted.conch.error import ConchError
-from twisted.conch.ssh import common, keys, userauth
-from twisted.internet import defer, protocol, reactor
-
-from twisted.conch.client.knownhosts import KnownHostsFile, ConsoleUI
-
-from twisted.conch.client import agent
-
-import os, sys, base64, getpass
-
-# The default location of the known hosts file (probably should be parsed out
-# of an ssh config file someday).
-_KNOWN_HOSTS = "~/.ssh/known_hosts"
-
-
-# This name is bound so that the unit tests can use 'patch' to override it.
-_open = open
-
-def verifyHostKey(transport, host, pubKey, fingerprint):
- """
- Verify a host's key.
-
- This function is a gross vestige of some bad factoring in the client
- internals. The actual implementation, and a better signature of this logic
- is in L{KnownHostsFile.verifyHostKey}. This function is not deprecated yet
- because the callers have not yet been rehabilitated, but they should
- eventually be changed to call that method instead.
-
- However, this function does perform two functions not implemented by
- L{KnownHostsFile.verifyHostKey}. It determines the path to the user's
- known_hosts file based on the options (which should really be the options
- object's job), and it provides an opener to L{ConsoleUI} which opens
- '/dev/tty' so that the user will be prompted on the tty of the process even
- if the input and output of the process has been redirected. This latter
- part is, somewhat obviously, not portable, but I don't know of a portable
- equivalent that could be used.
-
- @param host: Due to a bug in L{SSHClientTransport.verifyHostKey}, this is
- always the dotted-quad IP address of the host being connected to.
- @type host: L{str}
-
- @param transport: the client transport which is attempting to connect to
- the given host.
- @type transport: L{SSHClientTransport}
-
- @param fingerprint: the fingerprint of the given public key, in
- xx:xx:xx:... format. This is ignored in favor of getting the fingerprint
- from the key itself.
- @type fingerprint: L{str}
-
- @param pubKey: The public key of the server being connected to.
- @type pubKey: L{str}
-
- @return: a L{Deferred} which fires with C{1} if the key was successfully
- verified, or fails if the key could not be successfully verified. Failure
- types may include L{HostKeyChanged}, L{UserRejectedKey}, L{IOError} or
- L{KeyboardInterrupt}.
- """
- actualHost = transport.factory.options['host']
- actualKey = keys.Key.fromString(pubKey)
- kh = KnownHostsFile.fromPath(FilePath(
- transport.factory.options['known-hosts']
- or os.path.expanduser(_KNOWN_HOSTS)
- ))
- ui = ConsoleUI(lambda : _open("/dev/tty", "r+b"))
- return kh.verifyHostKey(ui, actualHost, host, actualKey)
-
-
-def isInKnownHosts(host, pubKey, options):
- """checks to see if host is in the known_hosts file for the user.
- returns 0 if it isn't, 1 if it is and is the same, 2 if it's changed.
- """
- keyType = common.getNS(pubKey)[0]
- retVal = 0
-
- if not options['known-hosts'] and not os.path.exists(os.path.expanduser('~/.ssh/')):
- print 'Creating ~/.ssh directory...'
- os.mkdir(os.path.expanduser('~/.ssh'))
- kh_file = options['known-hosts'] or _KNOWN_HOSTS
- try:
- known_hosts = open(os.path.expanduser(kh_file))
- except IOError:
- return 0
- for line in known_hosts.xreadlines():
- split = line.split()
- if len(split) < 3:
- continue
- hosts, hostKeyType, encodedKey = split[:3]
- if host not in hosts.split(','): # incorrect host
- continue
- if hostKeyType != keyType: # incorrect type of key
- continue
- try:
- decodedKey = base64.decodestring(encodedKey)
- except:
- continue
- if decodedKey == pubKey:
- return 1
- else:
- retVal = 2
- return retVal
-
-
-
-class SSHUserAuthClient(userauth.SSHUserAuthClient):
-
- def __init__(self, user, options, *args):
- userauth.SSHUserAuthClient.__init__(self, user, *args)
- self.keyAgent = None
- self.options = options
- self.usedFiles = []
- if not options.identitys:
- options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa']
-
- def serviceStarted(self):
- if 'SSH_AUTH_SOCK' in os.environ and not self.options['noagent']:
- log.msg('using agent')
- cc = protocol.ClientCreator(reactor, agent.SSHAgentClient)
- d = cc.connectUNIX(os.environ['SSH_AUTH_SOCK'])
- d.addCallback(self._setAgent)
- d.addErrback(self._ebSetAgent)
- else:
- userauth.SSHUserAuthClient.serviceStarted(self)
-
- def serviceStopped(self):
- if self.keyAgent:
- self.keyAgent.transport.loseConnection()
- self.keyAgent = None
-
- def _setAgent(self, a):
- self.keyAgent = a
- d = self.keyAgent.getPublicKeys()
- d.addBoth(self._ebSetAgent)
- return d
-
- def _ebSetAgent(self, f):
- userauth.SSHUserAuthClient.serviceStarted(self)
-
- def _getPassword(self, prompt):
- try:
- oldout, oldin = sys.stdout, sys.stdin
- sys.stdin = sys.stdout = open('/dev/tty','r+')
- p=getpass.getpass(prompt)
- sys.stdout,sys.stdin=oldout,oldin
- return p
- except (KeyboardInterrupt, IOError):
- print
- raise ConchError('PEBKAC')
-
- def getPassword(self, prompt = None):
- if not prompt:
- prompt = "%s@%s's password: " % (self.user, self.transport.transport.getPeer().host)
- try:
- p = self._getPassword(prompt)
- return defer.succeed(p)
- except ConchError:
- return defer.fail()
-
-
- def getPublicKey(self):
- """
- Get a public key from the key agent if possible, otherwise look in
- the next configured identity file for one.
- """
- if self.keyAgent:
- key = self.keyAgent.getPublicKey()
- if key is not None:
- return key
- files = [x for x in self.options.identitys if x not in self.usedFiles]
- log.msg(str(self.options.identitys))
- log.msg(str(files))
- if not files:
- return None
- file = files[0]
- log.msg(file)
- self.usedFiles.append(file)
- file = os.path.expanduser(file)
- file += '.pub'
- if not os.path.exists(file):
- return self.getPublicKey() # try again
- try:
- return keys.Key.fromFile(file)
- except keys.BadKeyError:
- return self.getPublicKey() # try again
-
-
- def signData(self, publicKey, signData):
- """
- Extend the base signing behavior by using an SSH agent to sign the
- data, if one is available.
-
- @type publicKey: L{Key}
- @type signData: C{str}
- """
- if not self.usedFiles: # agent key
- return self.keyAgent.signData(publicKey.blob(), signData)
- else:
- return userauth.SSHUserAuthClient.signData(self, publicKey, signData)
-
-
- def getPrivateKey(self):
- """
- Try to load the private key from the last used file identified by
- C{getPublicKey}, potentially asking for the passphrase if the key is
- encrypted.
- """
- file = os.path.expanduser(self.usedFiles[-1])
- if not os.path.exists(file):
- return None
- try:
- return defer.succeed(keys.Key.fromFile(file))
- except keys.EncryptedKeyError:
- for i in range(3):
- prompt = "Enter passphrase for key '%s': " % \
- self.usedFiles[-1]
- try:
- p = self._getPassword(prompt)
- return defer.succeed(keys.Key.fromFile(file, passphrase=p))
- except (keys.BadKeyError, ConchError):
- pass
- return defer.fail(ConchError('bad password'))
- raise
- except KeyboardInterrupt:
- print
- reactor.stop()
-
-
- def getGenericAnswers(self, name, instruction, prompts):
- responses = []
- try:
- oldout, oldin = sys.stdout, sys.stdin
- sys.stdin = sys.stdout = open('/dev/tty','r+')
- if name:
- print name
- if instruction:
- print instruction
- for prompt, echo in prompts:
- if echo:
- responses.append(raw_input(prompt))
- else:
- responses.append(getpass.getpass(prompt))
- finally:
- sys.stdout,sys.stdin=oldout,oldin
- return defer.succeed(responses)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/client/direct.py b/Darwin/lib/python2.7/site-packages/twisted/conch/client/direct.py
deleted file mode 100644
index f95a14a..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/client/direct.py
+++ /dev/null
@@ -1,107 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-from twisted.internet import defer, protocol, reactor
-from twisted.conch import error
-from twisted.conch.ssh import transport
-from twisted.python import log
-
-
-
-class SSHClientFactory(protocol.ClientFactory):
-
- def __init__(self, d, options, verifyHostKey, userAuthObject):
- self.d = d
- self.options = options
- self.verifyHostKey = verifyHostKey
- self.userAuthObject = userAuthObject
-
-
- def clientConnectionLost(self, connector, reason):
- if self.options['reconnect']:
- connector.connect()
-
-
- def clientConnectionFailed(self, connector, reason):
- if self.d is None:
- return
- d, self.d = self.d, None
- d.errback(reason)
-
-
- def buildProtocol(self, addr):
- trans = SSHClientTransport(self)
- if self.options['ciphers']:
- trans.supportedCiphers = self.options['ciphers']
- if self.options['macs']:
- trans.supportedMACs = self.options['macs']
- if self.options['compress']:
- trans.supportedCompressions[0:1] = ['zlib']
- if self.options['host-key-algorithms']:
- trans.supportedPublicKeys = self.options['host-key-algorithms']
- return trans
-
-
-
-class SSHClientTransport(transport.SSHClientTransport):
-
- def __init__(self, factory):
- self.factory = factory
- self.unixServer = None
-
-
- def connectionLost(self, reason):
- if self.unixServer:
- d = self.unixServer.stopListening()
- self.unixServer = None
- else:
- d = defer.succeed(None)
- d.addCallback(lambda x:
- transport.SSHClientTransport.connectionLost(self, reason))
-
-
- def receiveError(self, code, desc):
- if self.factory.d is None:
- return
- d, self.factory.d = self.factory.d, None
- d.errback(error.ConchError(desc, code))
-
-
- def sendDisconnect(self, code, reason):
- if self.factory.d is None:
- return
- d, self.factory.d = self.factory.d, None
- transport.SSHClientTransport.sendDisconnect(self, code, reason)
- d.errback(error.ConchError(reason, code))
-
-
- def receiveDebug(self, alwaysDisplay, message, lang):
- log.msg('Received Debug Message: %s' % message)
- if alwaysDisplay: # XXX what should happen here?
- print message
-
-
- def verifyHostKey(self, pubKey, fingerprint):
- return self.factory.verifyHostKey(self, self.transport.getPeer().host, pubKey,
- fingerprint)
-
-
- def setService(self, service):
- log.msg('setting client server to %s' % service)
- transport.SSHClientTransport.setService(self, service)
- if service.name != 'ssh-userauth' and self.factory.d is not None:
- d, self.factory.d = self.factory.d, None
- d.callback(None)
-
-
- def connectionSecure(self):
- self.requestService(self.factory.userAuthObject)
-
-
-
-def connect(host, port, options, verifyHostKey, userAuthObject):
- d = defer.Deferred()
- factory = SSHClientFactory(d, options, verifyHostKey, userAuthObject)
- reactor.connectTCP(host, port, factory)
- return d
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/client/knownhosts.py b/Darwin/lib/python2.7/site-packages/twisted/conch/client/knownhosts.py
deleted file mode 100644
index 9d4a13a..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/client/knownhosts.py
+++ /dev/null
@@ -1,624 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_knownhosts -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-An implementation of the OpenSSH known_hosts database.
-
-@since: 8.2
-"""
-
-import hmac
-from binascii import Error as DecodeError, b2a_base64
-from hashlib import sha1
-
-from zope.interface import implements
-
-from twisted.python.randbytes import secureRandom
-from twisted.internet import defer
-from twisted.python import log
-from twisted.python.util import FancyEqMixin
-from twisted.conch.interfaces import IKnownHostEntry
-from twisted.conch.error import HostKeyChanged, UserRejectedKey, InvalidEntry
-from twisted.conch.ssh.keys import Key, BadKeyError
-
-
-def _b64encode(s):
- """
- Encode a binary string as base64 with no trailing newline.
-
- @param s: The string to encode.
- @type s: L{bytes}
-
- @return: The base64-encoded string.
- @rtype: L{bytes}
- """
- return b2a_base64(s).strip()
-
-
-
-def _extractCommon(string):
- """
- Extract common elements of base64 keys from an entry in a hosts file.
-
- @param string: A known hosts file entry (a single line).
- @type string: L{bytes}
-
- @return: a 4-tuple of hostname data (L{bytes}), ssh key type (L{bytes}), key
- (L{Key}), and comment (L{bytes} or L{None}). The hostname data is
- simply the beginning of the line up to the first occurrence of
- whitespace.
- @rtype: L{tuple}
- """
- elements = string.split(None, 2)
- if len(elements) != 3:
- raise InvalidEntry()
- hostnames, keyType, keyAndComment = elements
- splitkey = keyAndComment.split(None, 1)
- if len(splitkey) == 2:
- keyString, comment = splitkey
- comment = comment.rstrip("\n")
- else:
- keyString = splitkey[0]
- comment = None
- key = Key.fromString(keyString.decode('base64'))
- return hostnames, keyType, key, comment
-
-
-
-class _BaseEntry(object):
- """
- Abstract base of both hashed and non-hashed entry objects, since they
- represent keys and key types the same way.
-
- @ivar keyType: The type of the key; either ssh-dss or ssh-rsa.
- @type keyType: L{str}
-
- @ivar publicKey: The server public key indicated by this line.
- @type publicKey: L{twisted.conch.ssh.keys.Key}
-
- @ivar comment: Trailing garbage after the key line.
- @type comment: L{str}
- """
-
- def __init__(self, keyType, publicKey, comment):
- self.keyType = keyType
- self.publicKey = publicKey
- self.comment = comment
-
-
- def matchesKey(self, keyObject):
- """
- Check to see if this entry matches a given key object.
-
- @param keyObject: A public key object to check.
- @type keyObject: L{Key}
-
- @return: C{True} if this entry's key matches C{keyObject}, C{False}
- otherwise.
- @rtype: L{bool}
- """
- return self.publicKey == keyObject
-
-
-
-class PlainEntry(_BaseEntry):
- """
- A L{PlainEntry} is a representation of a plain-text entry in a known_hosts
- file.
-
- @ivar _hostnames: the list of all host-names associated with this entry.
- @type _hostnames: L{list} of L{str}
- """
-
- implements(IKnownHostEntry)
-
- def __init__(self, hostnames, keyType, publicKey, comment):
- self._hostnames = hostnames
- super(PlainEntry, self).__init__(keyType, publicKey, comment)
-
-
- def fromString(cls, string):
- """
- Parse a plain-text entry in a known_hosts file, and return a
- corresponding L{PlainEntry}.
-
- @param string: a space-separated string formatted like "hostname
- key-type base64-key-data comment".
-
- @type string: L{str}
-
- @raise DecodeError: if the key is not valid encoded as valid base64.
-
- @raise InvalidEntry: if the entry does not have the right number of
- elements and is therefore invalid.
-
- @raise BadKeyError: if the key, once decoded from base64, is not
- actually an SSH key.
-
- @return: an IKnownHostEntry representing the hostname and key in the
- input line.
-
- @rtype: L{PlainEntry}
- """
- hostnames, keyType, key, comment = _extractCommon(string)
- self = cls(hostnames.split(","), keyType, key, comment)
- return self
-
- fromString = classmethod(fromString)
-
-
- def matchesHost(self, hostname):
- """
- Check to see if this entry matches a given hostname.
-
- @param hostname: A hostname or IP address literal to check against this
- entry.
- @type hostname: L{str}
-
- @return: C{True} if this entry is for the given hostname or IP address,
- C{False} otherwise.
- @rtype: L{bool}
- """
- return hostname in self._hostnames
-
-
- def toString(self):
- """
- Implement L{IKnownHostEntry.toString} by recording the comma-separated
- hostnames, key type, and base-64 encoded key.
-
- @return: The string representation of this entry, with unhashed hostname
- information.
- @rtype: L{bytes}
- """
- fields = [','.join(self._hostnames),
- self.keyType,
- _b64encode(self.publicKey.blob())]
- if self.comment is not None:
- fields.append(self.comment)
- return ' '.join(fields)
-
-
-
-class UnparsedEntry(object):
- """
- L{UnparsedEntry} is an entry in a L{KnownHostsFile} which can't actually be
- parsed; therefore it matches no keys and no hosts.
- """
-
- implements(IKnownHostEntry)
-
- def __init__(self, string):
- """
- Create an unparsed entry from a line in a known_hosts file which cannot
- otherwise be parsed.
- """
- self._string = string
-
-
- def matchesHost(self, hostname):
- """
- Always returns False.
- """
- return False
-
-
- def matchesKey(self, key):
- """
- Always returns False.
- """
- return False
-
-
- def toString(self):
- """
- Returns the input line, without its newline if one was given.
-
- @return: The string representation of this entry, almost exactly as was
- used to initialize this entry but without a trailing newline.
- @rtype: L{bytes}
- """
- return self._string.rstrip("\n")
-
-
-
-def _hmacedString(key, string):
- """
- Return the SHA-1 HMAC hash of the given key and string.
-
- @param key: The HMAC key.
- @type key: L{bytes}
-
- @param string: The string to be hashed.
- @type string: L{bytes}
-
- @return: The keyed hash value.
- @rtype: L{bytes}
- """
- hash = hmac.HMAC(key, digestmod=sha1)
- hash.update(string)
- return hash.digest()
-
-
-
-class HashedEntry(_BaseEntry, FancyEqMixin):
- """
- A L{HashedEntry} is a representation of an entry in a known_hosts file
- where the hostname has been hashed and salted.
-
- @ivar _hostSalt: the salt to combine with a hostname for hashing.
-
- @ivar _hostHash: the hashed representation of the hostname.
-
- @cvar MAGIC: the 'hash magic' string used to identify a hashed line in a
- known_hosts file as opposed to a plaintext one.
- """
-
- implements(IKnownHostEntry)
-
- MAGIC = '|1|'
-
- compareAttributes = (
- "_hostSalt", "_hostHash", "keyType", "publicKey", "comment")
-
- def __init__(self, hostSalt, hostHash, keyType, publicKey, comment):
- self._hostSalt = hostSalt
- self._hostHash = hostHash
- super(HashedEntry, self).__init__(keyType, publicKey, comment)
-
-
- def fromString(cls, string):
- """
- Load a hashed entry from a string representing a line in a known_hosts
- file.
-
- @param string: A complete single line from a I{known_hosts} file,
- formatted as defined by OpenSSH.
- @type string: L{bytes}
-
- @raise DecodeError: if the key, the hostname, or the is not valid
- encoded as valid base64
-
- @raise InvalidEntry: if the entry does not have the right number of
- elements and is therefore invalid, or the host/hash portion contains
- more items than just the host and hash.
-
- @raise BadKeyError: if the key, once decoded from base64, is not
- actually an SSH key.
-
- @return: The newly created L{HashedEntry} instance, initialized with the
- information from C{string}.
- """
- stuff, keyType, key, comment = _extractCommon(string)
- saltAndHash = stuff[len(cls.MAGIC):].split("|")
- if len(saltAndHash) != 2:
- raise InvalidEntry()
- hostSalt, hostHash = saltAndHash
- self = cls(hostSalt.decode("base64"), hostHash.decode("base64"),
- keyType, key, comment)
- return self
-
- fromString = classmethod(fromString)
-
-
- def matchesHost(self, hostname):
- """
- Implement L{IKnownHostEntry.matchesHost} to compare the hash of the
- input to the stored hash.
-
- @param hostname: A hostname or IP address literal to check against this
- entry.
- @type hostname: L{bytes}
-
- @return: C{True} if this entry is for the given hostname or IP address,
- C{False} otherwise.
- @rtype: L{bool}
- """
- return (_hmacedString(self._hostSalt, hostname) == self._hostHash)
-
-
- def toString(self):
- """
- Implement L{IKnownHostEntry.toString} by base64-encoding the salt, host
- hash, and key.
-
- @return: The string representation of this entry, with the hostname part
- hashed.
- @rtype: L{bytes}
- """
- fields = [self.MAGIC + '|'.join([_b64encode(self._hostSalt),
- _b64encode(self._hostHash)]),
- self.keyType,
- _b64encode(self.publicKey.blob())]
- if self.comment is not None:
- fields.append(self.comment)
- return ' '.join(fields)
-
-
-
-class KnownHostsFile(object):
- """
- A structured representation of an OpenSSH-format ~/.ssh/known_hosts file.
-
- @ivar _added: A list of L{IKnownHostEntry} providers which have been added
- to this instance in memory but not yet saved.
-
- @ivar _clobber: A flag indicating whether the current contents of the save
- path will be disregarded and potentially overwritten or not. If
- C{True}, this will be done. If C{False}, entries in the save path will
- be read and new entries will be saved by appending rather than
- overwriting.
- @type _clobber: L{bool}
-
- @ivar _savePath: See C{savePath} parameter of L{__init__}.
- """
-
- def __init__(self, savePath):
- """
- Create a new, empty KnownHostsFile.
-
- Unless you want to erase the current contents of C{savePath}, you want
- to use L{KnownHostsFile.fromPath} instead.
-
- @param savePath: The L{FilePath} to which to save new entries.
- @type savePath: L{FilePath}
- """
- self._added = []
- self._savePath = savePath
- self._clobber = True
-
-
- @property
- def savePath(self):
- """
- @see: C{savePath} parameter of L{__init__}
- """
- return self._savePath
-
-
- def iterentries(self):
- """
- Iterate over the host entries in this file.
-
- @return: An iterable the elements of which provide L{IKnownHostEntry}.
- There is an element for each entry in the file as well as an element
- for each added but not yet saved entry.
- @rtype: iterable of L{IKnownHostEntry} providers
- """
- for entry in self._added:
- yield entry
-
- if self._clobber:
- return
-
- try:
- fp = self._savePath.open()
- except IOError:
- return
-
- try:
- for line in fp:
- try:
- if line.startswith(HashedEntry.MAGIC):
- entry = HashedEntry.fromString(line)
- else:
- entry = PlainEntry.fromString(line)
- except (DecodeError, InvalidEntry, BadKeyError):
- entry = UnparsedEntry(line)
- yield entry
- finally:
- fp.close()
-
-
- def hasHostKey(self, hostname, key):
- """
- Check for an entry with matching hostname and key.
-
- @param hostname: A hostname or IP address literal to check for.
- @type hostname: L{bytes}
-
- @param key: The public key to check for.
- @type key: L{Key}
-
- @return: C{True} if the given hostname and key are present in this file,
- C{False} if they are not.
- @rtype: L{bool}
-
- @raise HostKeyChanged: if the host key found for the given hostname
- does not match the given key.
- """
- for lineidx, entry in enumerate(self.iterentries(), -len(self._added)):
- if entry.matchesHost(hostname):
- if entry.matchesKey(key):
- return True
- else:
- # Notice that lineidx is 0-based but HostKeyChanged.lineno
- # is 1-based.
- if lineidx < 0:
- line = None
- path = None
- else:
- line = lineidx + 1
- path = self._savePath
- raise HostKeyChanged(entry, path, line)
- return False
-
-
- def verifyHostKey(self, ui, hostname, ip, key):
- """
- Verify the given host key for the given IP and host, asking for
- confirmation from, and notifying, the given UI about changes to this
- file.
-
- @param ui: The user interface to request an IP address from.
-
- @param hostname: The hostname that the user requested to connect to.
-
- @param ip: The string representation of the IP address that is actually
- being connected to.
-
- @param key: The public key of the server.
-
- @return: a L{Deferred} that fires with True when the key has been
- verified, or fires with an errback when the key either cannot be
- verified or has changed.
- @rtype: L{Deferred}
- """
- hhk = defer.maybeDeferred(self.hasHostKey, hostname, key)
- def gotHasKey(result):
- if result:
- if not self.hasHostKey(ip, key):
- ui.warn("Warning: Permanently added the %s host key for "
- "IP address '%s' to the list of known hosts." %
- (key.type(), ip))
- self.addHostKey(ip, key)
- self.save()
- return result
- else:
- def promptResponse(response):
- if response:
- self.addHostKey(hostname, key)
- self.addHostKey(ip, key)
- self.save()
- return response
- else:
- raise UserRejectedKey()
- proceed = ui.prompt(
- "The authenticity of host '%s (%s)' "
- "can't be established.\n"
- "RSA key fingerprint is %s.\n"
- "Are you sure you want to continue connecting (yes/no)? " %
- (hostname, ip, key.fingerprint()))
- return proceed.addCallback(promptResponse)
- return hhk.addCallback(gotHasKey)
-
-
- def addHostKey(self, hostname, key):
- """
- Add a new L{HashedEntry} to the key database.
-
- Note that you still need to call L{KnownHostsFile.save} if you wish
- these changes to be persisted.
-
- @param hostname: A hostname or IP address literal to associate with the
- new entry.
- @type hostname: L{bytes}
-
- @param key: The public key to associate with the new entry.
- @type key: L{Key}
-
- @return: The L{HashedEntry} that was added.
- @rtype: L{HashedEntry}
- """
- salt = secureRandom(20)
- keyType = "ssh-" + key.type().lower()
- entry = HashedEntry(salt, _hmacedString(salt, hostname),
- keyType, key, None)
- self._added.append(entry)
- return entry
-
-
- def save(self):
- """
- Save this L{KnownHostsFile} to the path it was loaded from.
- """
- p = self._savePath.parent()
- if not p.isdir():
- p.makedirs()
-
- if self._clobber:
- mode = "w"
- else:
- mode = "a"
-
- with self._savePath.open(mode) as hostsFileObj:
- if self._added:
- hostsFileObj.write(
- "\n".join([entry.toString() for entry in self._added]) +
- "\n")
- self._added = []
- self._clobber = False
-
-
- def fromPath(cls, path):
- """
- Create a new L{KnownHostsFile}, potentially reading existing known
- hosts information from the given file.
-
- @param path: A path object to use for both reading contents from and
- later saving to. If no file exists at this path, it is not an
- error; a L{KnownHostsFile} with no entries is returned.
- @type path: L{FilePath}
-
- @return: A L{KnownHostsFile} initialized with entries from C{path}.
- @rtype: L{KnownHostsFile}
- """
- knownHosts = cls(path)
- knownHosts._clobber = False
- return knownHosts
-
- fromPath = classmethod(fromPath)
-
-
-
-class ConsoleUI(object):
- """
- A UI object that can ask true/false questions and post notifications on the
- console, to be used during key verification.
- """
- def __init__(self, opener):
- """
- @param opener: A no-argument callable which should open a console
- binary-mode file-like object to be used for reading and writing.
- This initializes the C{opener} attribute.
- @type opener: callable taking no arguments and returning a read/write
- file-like object
- """
- self.opener = opener
-
-
- def prompt(self, text):
- """
- Write the given text as a prompt to the console output, then read a
- result from the console input.
-
- @param text: Something to present to a user to solicit a yes or no
- response.
- @type text: L{bytes}
-
- @return: a L{Deferred} which fires with L{True} when the user answers
- 'yes' and L{False} when the user answers 'no'. It may errback if
- there were any I/O errors.
- """
- d = defer.succeed(None)
- def body(ignored):
- f = self.opener()
- f.write(text)
- while True:
- answer = f.readline().strip().lower()
- if answer == 'yes':
- f.close()
- return True
- elif answer == 'no':
- f.close()
- return False
- else:
- f.write("Please type 'yes' or 'no': ")
- return d.addCallback(body)
-
-
- def warn(self, text):
- """
- Notify the user (non-interactively) of the provided text, by writing it
- to the console.
-
- @param text: Some information the user is to be made aware of.
- @type text: L{bytes}
- """
- try:
- f = self.opener()
- f.write(text)
- f.close()
- except:
- log.err()
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/client/options.py b/Darwin/lib/python2.7/site-packages/twisted/conch/client/options.py
deleted file mode 100644
index 8550573..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/client/options.py
+++ /dev/null
@@ -1,96 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-from twisted.conch.ssh.transport import SSHClientTransport, SSHCiphers
-from twisted.python import usage
-
-import sys
-
-class ConchOptions(usage.Options):
-
- optParameters = [['user', 'l', None, 'Log in using this user name.'],
- ['identity', 'i', None],
- ['ciphers', 'c', None],
- ['macs', 'm', None],
- ['port', 'p', None, 'Connect to this port. Server must be on the same port.'],
- ['option', 'o', None, 'Ignored OpenSSH options'],
- ['host-key-algorithms', '', None],
- ['known-hosts', '', None, 'File to check for host keys'],
- ['user-authentications', '', None, 'Types of user authentications to use.'],
- ['logfile', '', None, 'File to log to, or - for stdout'],
- ]
-
- optFlags = [['version', 'V', 'Display version number only.'],
- ['compress', 'C', 'Enable compression.'],
- ['log', 'v', 'Enable logging (defaults to stderr)'],
- ['nox11', 'x', 'Disable X11 connection forwarding (default)'],
- ['agent', 'A', 'Enable authentication agent forwarding'],
- ['noagent', 'a', 'Disable authentication agent forwarding (default)'],
- ['reconnect', 'r', 'Reconnect to the server if the connection is lost.'],
- ]
-
- compData = usage.Completions(
- mutuallyExclusive=[("agent", "noagent")],
- optActions={
- "user": usage.CompleteUsernames(),
- "ciphers": usage.CompleteMultiList(
- SSHCiphers.cipherMap.keys(),
- descr='ciphers to choose from'),
- "macs": usage.CompleteMultiList(
- SSHCiphers.macMap.keys(),
- descr='macs to choose from'),
- "host-key-algorithms": usage.CompleteMultiList(
- SSHClientTransport.supportedPublicKeys,
- descr='host key algorithms to choose from'),
- #"user-authentications": usage.CompleteMultiList(?
- # descr='user authentication types' ),
- },
- extraActions=[usage.CompleteUserAtHost(),
- usage.Completer(descr="command"),
- usage.Completer(descr='argument',
- repeat=True)]
- )
-
- def __init__(self, *args, **kw):
- usage.Options.__init__(self, *args, **kw)
- self.identitys = []
- self.conns = None
-
- def opt_identity(self, i):
- """Identity for public-key authentication"""
- self.identitys.append(i)
-
- def opt_ciphers(self, ciphers):
- "Select encryption algorithms"
- ciphers = ciphers.split(',')
- for cipher in ciphers:
- if not SSHCiphers.cipherMap.has_key(cipher):
- sys.exit("Unknown cipher type '%s'" % cipher)
- self['ciphers'] = ciphers
-
-
- def opt_macs(self, macs):
- "Specify MAC algorithms"
- macs = macs.split(',')
- for mac in macs:
- if not SSHCiphers.macMap.has_key(mac):
- sys.exit("Unknown mac type '%s'" % mac)
- self['macs'] = macs
-
- def opt_host_key_algorithms(self, hkas):
- "Select host key algorithms"
- hkas = hkas.split(',')
- for hka in hkas:
- if hka not in SSHClientTransport.supportedPublicKeys:
- sys.exit("Unknown host key type '%s'" % hka)
- self['host-key-algorithms'] = hkas
-
- def opt_user_authentications(self, uas):
- "Choose how to authenticate to the remote server"
- self['user-authentications'] = uas.split(',')
-
-# def opt_compress(self):
-# "Enable compression"
-# self.enableCompression = 1
-# SSHClientTransport.supportedCompressions[0:1] = ['zlib']
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/endpoints.py b/Darwin/lib/python2.7/site-packages/twisted/conch/endpoints.py
deleted file mode 100644
index 353ef7f..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/endpoints.py
+++ /dev/null
@@ -1,832 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_endpoints -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Endpoint implementations of various SSH interactions.
-"""
-
-__all__ = [
- 'AuthenticationFailed', 'SSHCommandAddress', 'SSHCommandClientEndpoint']
-
-from struct import unpack
-from os.path import expanduser
-
-from zope.interface import Interface, implementer
-
-from twisted.python.filepath import FilePath
-from twisted.python.failure import Failure
-from twisted.internet.error import ConnectionDone, ProcessTerminated
-from twisted.internet.interfaces import IStreamClientEndpoint
-from twisted.internet.protocol import Factory
-from twisted.internet.defer import Deferred, succeed, CancelledError
-from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol
-
-from twisted.conch.ssh.keys import Key
-from twisted.conch.ssh.common import NS
-from twisted.conch.ssh.transport import SSHClientTransport
-from twisted.conch.ssh.connection import SSHConnection
-from twisted.conch.ssh.userauth import SSHUserAuthClient
-from twisted.conch.ssh.channel import SSHChannel
-from twisted.conch.client.knownhosts import ConsoleUI, KnownHostsFile
-from twisted.conch.client.agent import SSHAgentClient
-from twisted.conch.client.default import _KNOWN_HOSTS
-
-
-class AuthenticationFailed(Exception):
- """
- An SSH session could not be established because authentication was not
- successful.
- """
-
-
-
-# This should be public. See #6541.
-class _ISSHConnectionCreator(Interface):
- """
- An L{_ISSHConnectionCreator} knows how to create SSH connections somehow.
- """
- def secureConnection():
- """
- Return a new, connected, secured, but not yet authenticated instance of
- L{twisted.conch.ssh.transport.SSHServerTransport} or
- L{twisted.conch.ssh.transport.SSHClientTransport}.
- """
-
-
- def cleanupConnection(connection, immediate):
- """
- Perform cleanup necessary for a connection object previously returned
- from this creator's C{secureConnection} method.
-
- @param connection: An L{twisted.conch.ssh.transport.SSHServerTransport}
- or L{twisted.conch.ssh.transport.SSHClientTransport} returned by a
- previous call to C{secureConnection}. It is no longer needed by the
- caller of that method and may be closed or otherwise cleaned up as
- necessary.
-
- @param immediate: If C{True} don't wait for any network communication,
- just close the connection immediately and as aggressively as
- necessary.
- """
-
-
-
-class SSHCommandAddress(object):
- """
- An L{SSHCommandAddress} instance represents the address of an SSH server, a
- username which was used to authenticate with that server, and a command
- which was run there.
-
- @ivar server: See L{__init__}
- @ivar username: See L{__init__}
- @ivar command: See L{__init__}
- """
- def __init__(self, server, username, command):
- """
- @param server: The address of the SSH server on which the command is
- running.
- @type server: L{IAddress} provider
-
- @param username: An authentication username which was used to
- authenticate against the server at the given address.
- @type username: L{bytes}
-
- @param command: A command which was run in a session channel on the
- server at the given address.
- @type command: L{bytes}
- """
- self.server = server
- self.username = username
- self.command = command
-
-
-
-class _CommandChannel(SSHChannel):
- """
- A L{_CommandChannel} executes a command in a session channel and connects
- its input and output to an L{IProtocol} provider.
-
- @ivar _creator: See L{__init__}
- @ivar _command: See L{__init__}
- @ivar _protocolFactory: See L{__init__}
- @ivar _commandConnected: See L{__init__}
- @ivar _protocol: An L{IProtocol} provider created using C{_protocolFactory}
- which is hooked up to the running command's input and output streams.
- """
- name = b'session'
-
- def __init__(self, creator, command, protocolFactory, commandConnected):
- """
- @param creator: The L{_ISSHConnectionCreator} provider which was used
- to get the connection which this channel exists on.
- @type creator: L{_ISSHConnectionCreator} provider
-
- @param command: The command to be executed.
- @type command: L{bytes}
-
- @param protocolFactory: A client factory to use to build a L{IProtocol}
- provider to use to associate with the running command.
-
- @param commandConnected: A L{Deferred} to use to signal that execution
- of the command has failed or that it has succeeded and the command
- is now running.
- @type commandConnected: L{Deferred}
- """
- SSHChannel.__init__(self)
- self._creator = creator
- self._command = command
- self._protocolFactory = protocolFactory
- self._commandConnected = commandConnected
- self._reason = None
-
-
- def openFailed(self, reason):
- """
- When the request to open a new channel to run this command in fails,
- fire the C{commandConnected} deferred with a failure indicating that.
- """
- self._commandConnected.errback(reason)
-
-
- def channelOpen(self, ignored):
- """
- When the request to open a new channel to run this command in succeeds,
- issue an C{"exec"} request to run the command.
- """
- command = self.conn.sendRequest(
- self, 'exec', NS(self._command), wantReply=True)
- command.addCallbacks(self._execSuccess, self._execFailure)
-
-
- def _execFailure(self, reason):
- """
- When the request to execute the command in this channel fails, fire the
- C{commandConnected} deferred with a failure indicating this.
-
- @param reason: The cause of the command execution failure.
- @type reason: L{Failure}
- """
- self._commandConnected.errback(reason)
-
-
- def _execSuccess(self, ignored):
- """
- When the request to execute the command in this channel succeeds, use
- C{protocolFactory} to build a protocol to handle the command's input and
- output and connect the protocol to a transport representing those
- streams.
-
- Also fire C{commandConnected} with the created protocol after it is
- connected to its transport.
-
- @param ignored: The (ignored) result of the execute request
- """
- self._protocol = self._protocolFactory.buildProtocol(
- SSHCommandAddress(
- self.conn.transport.transport.getPeer(),
- self.conn.transport.creator.username,
- self.conn.transport.creator.command))
- self._protocol.makeConnection(self)
- self._commandConnected.callback(self._protocol)
-
-
- def dataReceived(self, data):
- """
- When the command's stdout data arrives over the channel, deliver it to
- the protocol instance.
-
- @param data: The bytes from the command's stdout.
- @type data: L{bytes}
- """
- self._protocol.dataReceived(data)
-
-
- def request_exit_status(self, data):
- """
- When the server sends the command's exit status, record it for later
- delivery to the protocol.
-
- @param data: The network-order four byte representation of the exit
- status of the command.
- @type data: L{bytes}
- """
- (status,) = unpack('>L', data)
- if status != 0:
- self._reason = ProcessTerminated(status, None, None)
-
-
- def request_exit_signal(self, data):
- """
- When the server sends the command's exit status, record it for later
- delivery to the protocol.
-
- @param data: The network-order four byte representation of the exit
- signal of the command.
- @type data: L{bytes}
- """
- (signal,) = unpack('>L', data)
- self._reason = ProcessTerminated(None, signal, None)
-
-
- def closed(self):
- """
- When the channel closes, deliver disconnection notification to the
- protocol.
- """
- self._creator.cleanupConnection(self.conn, False)
- if self._reason is None:
- reason = ConnectionDone("ssh channel closed")
- else:
- reason = self._reason
- self._protocol.connectionLost(Failure(reason))
-
-
-
-class _ConnectionReady(SSHConnection):
- """
- L{_ConnectionReady} is an L{SSHConnection} (an SSH service) which only
- propagates the I{serviceStarted} event to a L{Deferred} to be handled
- elsewhere.
- """
- def __init__(self, ready):
- """
- @param ready: A L{Deferred} which should be fired when
- I{serviceStarted} happens.
- """
- SSHConnection.__init__(self)
- self._ready = ready
-
-
- def serviceStarted(self):
- """
- When the SSH I{connection} I{service} this object represents is ready to
- be used, fire the C{connectionReady} L{Deferred} to publish that event
- to some other interested party.
-
- """
- self._ready.callback(self)
- del self._ready
-
-
-
-class _UserAuth(SSHUserAuthClient):
- """
- L{_UserAuth} implements the client part of SSH user authentication in the
- convenient way a user might expect if they are familiar with the
- interactive I{ssh} command line client.
-
- L{_UserAuth} supports key-based authentication, password-based
- authentication, and delegating authentication to an agent.
- """
- password = None
- keys = None
- agent = None
-
- def getPublicKey(self):
- """
- Retrieve the next public key object to offer to the server, possibly
- delegating to an authentication agent if there is one.
-
- @return: The public part of a key pair that could be used to
- authenticate with the server, or C{None} if there are no more public
- keys to try.
- @rtype: L{twisted.conch.ssh.keys.Key} or L{types.NoneType}
- """
- if self.agent is not None:
- return self.agent.getPublicKey()
-
- if self.keys:
- self.key = self.keys.pop(0)
- else:
- self.key = None
- return self.key.public()
-
-
- def signData(self, publicKey, signData):
- """
- Extend the base signing behavior by using an SSH agent to sign the
- data, if one is available.
-
- @type publicKey: L{Key}
- @type signData: C{str}
- """
- if self.agent is not None:
- return self.agent.signData(publicKey.blob(), signData)
- else:
- return SSHUserAuthClient.signData(self, publicKey, signData)
-
-
- def getPrivateKey(self):
- """
- Get the private part of a key pair to use for authentication. The key
- corresponds to the public part most recently returned from
- C{getPublicKey}.
-
- @return: A L{Deferred} which fires with the private key.
- @rtype: L{Deferred}
- """
- return succeed(self.key)
-
-
- def getPassword(self):
- """
- Get the password to use for authentication.
-
- @return: A L{Deferred} which fires with the password, or C{None} if the
- password was not specified.
- """
- if self.password is None:
- return
- return succeed(self.password)
-
-
- def ssh_USERAUTH_SUCCESS(self, packet):
- """
- Handle user authentication success in the normal way, but also make a
- note of the state change on the L{_CommandTransport}.
- """
- self.transport._state = b'CHANNELLING'
- return SSHUserAuthClient.ssh_USERAUTH_SUCCESS(self, packet)
-
-
-
-class _CommandTransport(SSHClientTransport):
- """
- L{_CommandTransport} is an SSH client I{transport} which includes a host key
- verification step before it will proceed to secure the connection.
-
- L{_CommandTransport} also knows how to set up a connection to an
- authentication agent if it is told where it can connect to one.
- """
- # STARTING -> SECURING -> AUTHENTICATING -> CHANNELLING -> RUNNING
- _state = b'STARTING'
-
- _hostKeyFailure = None
-
-
- def __init__(self, creator):
- """
- @param creator: The L{_NewConnectionHelper} that created this
- connection.
-
- @type creator: L{_NewConnectionHelper}.
- """
- self.connectionReady = Deferred(
- lambda d: self.transport.abortConnection())
- # Clear the reference to that deferred to help the garbage collector
- # and to signal to other parts of this implementation (in particular
- # connectionLost) that it has already been fired and does not need to
- # be fired again.
- def readyFired(result):
- self.connectionReady = None
- return result
- self.connectionReady.addBoth(readyFired)
- self.creator = creator
-
-
- def verifyHostKey(self, hostKey, fingerprint):
- """
- Ask the L{KnownHostsFile} provider available on the factory which
- created this protocol this protocol to verify the given host key.
-
- @return: A L{Deferred} which fires with the result of
- L{KnownHostsFile.verifyHostKey}.
- """
- hostname = self.creator.hostname
- ip = self.transport.getPeer().host
-
- self._state = b'SECURING'
- d = self.creator.knownHosts.verifyHostKey(
- self.creator.ui, hostname, ip, Key.fromString(hostKey))
- d.addErrback(self._saveHostKeyFailure)
- return d
-
-
- def _saveHostKeyFailure(self, reason):
- """
- When host key verification fails, record the reason for the failure in
- order to fire a L{Deferred} with it later.
-
- @param reason: The cause of the host key verification failure.
- @type reason: L{Failure}
-
- @return: C{reason}
- @rtype: L{Failure}
- """
- self._hostKeyFailure = reason
- return reason
-
-
- def connectionSecure(self):
- """
- When the connection is secure, start the authentication process.
- """
- self._state = b'AUTHENTICATING'
-
- command = _ConnectionReady(self.connectionReady)
-
- userauth = _UserAuth(self.creator.username, command)
- userauth.password = self.creator.password
- if self.creator.keys:
- userauth.keys = list(self.creator.keys)
-
- if self.creator.agentEndpoint is not None:
- d = self._connectToAgent(userauth, self.creator.agentEndpoint)
- else:
- d = succeed(None)
-
- def maybeGotAgent(ignored):
- self.requestService(userauth)
- d.addBoth(maybeGotAgent)
-
-
- def _connectToAgent(self, userauth, endpoint):
- """
- Set up a connection to the authentication agent and trigger its
- initialization.
-
- @param userauth: The L{_UserAuth} instance which is in charge of the
- overall authentication process.
- @type userauth: L{_UserAuth}
-
- @param endpoint: An endpoint which can be used to connect to the
- authentication agent.
- @type endpoint: L{IStreamClientEndpoint} provider
-
- @return: A L{Deferred} which fires when the agent connection is ready
- for use.
- """
- factory = Factory()
- factory.protocol = SSHAgentClient
- d = endpoint.connect(factory)
- def connected(agent):
- userauth.agent = agent
- return agent.getPublicKeys()
- d.addCallback(connected)
- return d
-
-
- def connectionLost(self, reason):
- """
- When the underlying connection to the SSH server is lost, if there were
- any connection setup errors, propagate them.
- """
- if self._state == b'RUNNING' or self.connectionReady is None:
- return
- if self._state == b'SECURING' and self._hostKeyFailure is not None:
- reason = self._hostKeyFailure
- elif self._state == b'AUTHENTICATING':
- reason = Failure(
- AuthenticationFailed("Connection lost while authenticating"))
- self.connectionReady.errback(reason)
-
-
-
-@implementer(IStreamClientEndpoint)
-class SSHCommandClientEndpoint(object):
- """
- L{SSHCommandClientEndpoint} exposes the command-executing functionality of
- SSH servers.
-
- L{SSHCommandClientEndpoint} can set up a new SSH connection, authenticate
- it in any one of a number of different ways (keys, passwords, agents),
- launch a command over that connection and then associate its input and
- output with a protocol.
-
- It can also re-use an existing, already-authenticated SSH connection
- (perhaps one which already has some SSH channels being used for other
- purposes). In this case it creates a new SSH channel to use to execute the
- command. Notably this means it supports multiplexing several different
- command invocations over a single SSH connection.
- """
-
- def __init__(self, creator, command):
- """
- @param creator: An L{_ISSHConnectionCreator} provider which will be
- used to set up the SSH connection which will be used to run a
- command.
- @type creator: L{_ISSHConnectionCreator} provider
-
- @param command: The command line to execute on the SSH server. This
- byte string is interpreted by a shell on the SSH server, so it may
- have a value like C{"ls /"}. Take care when trying to run a command
- like C{"/Volumes/My Stuff/a-program"} - spaces (and other special
- bytes) may require escaping.
- @type command: L{bytes}
-
- """
- self._creator = creator
- self._command = command
-
-
- @classmethod
- def newConnection(cls, reactor, command, username, hostname, port=None,
- keys=None, password=None, agentEndpoint=None,
- knownHosts=None, ui=None):
- """
- Create and return a new endpoint which will try to create a new
- connection to an SSH server and run a command over it. It will also
- close the connection if there are problems leading up to the command
- being executed, after the command finishes, or if the connection
- L{Deferred} is cancelled.
-
- @param reactor: The reactor to use to establish the connection.
- @type reactor: L{IReactorTCP} provider
-
- @param command: See L{__init__}'s C{command} argument.
-
- @param username: The username with which to authenticate to the SSH
- server.
- @type username: L{bytes}
-
- @param hostname: The hostname of the SSH server.
- @type hostname: L{bytes}
-
- @param port: The port number of the SSH server. By default, the
- standard SSH port number is used.
- @type port: L{int}
-
- @param keys: Private keys with which to authenticate to the SSH server,
- if key authentication is to be attempted (otherwise C{None}).
- @type keys: L{list} of L{Key}
-
- @param password: The password with which to authenticate to the SSH
- server, if password authentication is to be attempted (otherwise
- C{None}).
- @type password: L{bytes} or L{types.NoneType}
-
- @param agentEndpoint: An L{IStreamClientEndpoint} provider which may be
- used to connect to an SSH agent, if one is to be used to help with
- authentication.
- @type agentEndpoint: L{IStreamClientEndpoint} provider
-
- @param knownHosts: The currently known host keys, used to check the
- host key presented by the server we actually connect to.
- @type knownHosts: L{KnownHostsFile}
-
- @param ui: An object for interacting with users to make decisions about
- whether to accept the server host keys. If C{None}, a L{ConsoleUI}
- connected to /dev/tty will be used; if /dev/tty is unavailable, an
- object which answers C{b"no"} to all prompts will be used.
- @type ui: L{NoneType} or L{ConsoleUI}
-
- @return: A new instance of C{cls} (probably
- L{SSHCommandClientEndpoint}).
- """
- helper = _NewConnectionHelper(
- reactor, hostname, port, command, username, keys, password,
- agentEndpoint, knownHosts, ui)
- return cls(helper, command)
-
-
- @classmethod
- def existingConnection(cls, connection, command):
- """
- Create and return a new endpoint which will try to open a new channel on
- an existing SSH connection and run a command over it. It will B{not}
- close the connection if there is a problem executing the command or
- after the command finishes.
-
- @param connection: An existing connection to an SSH server.
- @type connection: L{SSHConnection}
-
- @param command: See L{SSHCommandClientEndpoint.newConnection}'s
- C{command} parameter.
- @type command: L{bytes}
-
- @return: A new instance of C{cls} (probably
- L{SSHCommandClientEndpoint}).
- """
- helper = _ExistingConnectionHelper(connection)
- return cls(helper, command)
-
-
- def connect(self, protocolFactory):
- """
- Set up an SSH connection, use a channel from that connection to launch
- a command, and hook the stdin and stdout of that command up as a
- transport for a protocol created by the given factory.
-
- @param protocolFactory: A L{Factory} to use to create the protocol
- which will be connected to the stdin and stdout of the command on
- the SSH server.
-
- @return: A L{Deferred} which will fire with an error if the connection
- cannot be set up for any reason or with the protocol instance
- created by C{protocolFactory} once it has been connected to the
- command.
- """
- d = self._creator.secureConnection()
- d.addCallback(self._executeCommand, protocolFactory)
- return d
-
-
- def _executeCommand(self, connection, protocolFactory):
- """
- Given a secured SSH connection, try to execute a command in a new
- channel created on it and associate the result with a protocol from the
- given factory.
-
- @param connection: See L{SSHCommandClientEndpoint.existingConnection}'s
- C{connection} parameter.
-
- @param protocolFactory: See L{SSHCommandClientEndpoint.connect}'s
- C{protocolFactory} parameter.
-
- @return: See L{SSHCommandClientEndpoint.connect}'s return value.
- """
- commandConnected = Deferred()
- def disconnectOnFailure(passthrough):
- # Close the connection immediately in case of cancellation, since
- # that implies user wants it gone immediately (e.g. a timeout):
- immediate = passthrough.check(CancelledError)
- self._creator.cleanupConnection(connection, immediate)
- return passthrough
- commandConnected.addErrback(disconnectOnFailure)
-
- channel = _CommandChannel(
- self._creator, self._command, protocolFactory, commandConnected)
- connection.openChannel(channel)
- return commandConnected
-
-
-
-class _ReadFile(object):
- """
- A weakly file-like object which can be used with L{KnownHostsFile} to
- respond in the negative to all prompts for decisions.
- """
- def __init__(self, contents):
- """
- @param contents: L{bytes} which will be returned from every C{readline}
- call.
- """
- self._contents = contents
-
-
- def write(self, data):
- """
- No-op.
-
- @param data: ignored
- """
-
-
- def readline(self, count=-1):
- """
- Always give back the byte string that this L{_ReadFile} was initialized
- with.
-
- @param count: ignored
-
- @return: A fixed byte-string.
- @rtype: L{bytes}
- """
- return self._contents
-
-
- def close(self):
- """
- No-op.
- """
-
-
-
-@implementer(_ISSHConnectionCreator)
-class _NewConnectionHelper(object):
- """
- L{_NewConnectionHelper} implements L{_ISSHConnectionCreator} by
- establishing a brand new SSH connection, securing it, and authenticating.
- """
- _KNOWN_HOSTS = _KNOWN_HOSTS
- port = 22
-
- def __init__(self, reactor, hostname, port, command, username, keys,
- password, agentEndpoint, knownHosts, ui,
- tty=FilePath(b"/dev/tty")):
- """
- @param tty: The path of the tty device to use in case C{ui} is C{None}.
- @type tty: L{FilePath}
-
- @see: L{SSHCommandClientEndpoint.newConnection}
- """
- self.reactor = reactor
- self.hostname = hostname
- if port is not None:
- self.port = port
- self.command = command
- self.username = username
- self.keys = keys
- self.password = password
- self.agentEndpoint = agentEndpoint
- if knownHosts is None:
- knownHosts = self._knownHosts()
- self.knownHosts = knownHosts
-
- if ui is None:
- ui = ConsoleUI(self._opener)
- self.ui = ui
- self.tty = tty
-
-
- def _opener(self):
- """
- Open the tty if possible, otherwise give back a file-like object from
- which C{b"no"} can be read.
-
- For use as the opener argument to L{ConsoleUI}.
- """
- try:
- return self.tty.open("r+")
- except:
- # Give back a file-like object from which can be read a byte string
- # that KnownHostsFile recognizes as rejecting some option (b"no").
- return _ReadFile(b"no")
-
-
- @classmethod
- def _knownHosts(cls):
- """
- @return: A L{KnownHostsFile} instance pointed at the user's personal
- I{known hosts} file.
- @type: L{KnownHostsFile}
- """
- return KnownHostsFile.fromPath(FilePath(expanduser(cls._KNOWN_HOSTS)))
-
-
- def secureConnection(self):
- """
- Create and return a new SSH connection which has been secured and on
- which authentication has already happened.
-
- @return: A L{Deferred} which fires with the ready-to-use connection or
- with a failure if something prevents the connection from being
- setup, secured, or authenticated.
- """
- protocol = _CommandTransport(self)
- ready = protocol.connectionReady
-
- sshClient = TCP4ClientEndpoint(self.reactor, self.hostname, self.port)
-
- d = connectProtocol(sshClient, protocol)
- d.addCallback(lambda ignored: ready)
- return d
-
-
- def cleanupConnection(self, connection, immediate):
- """
- Clean up the connection by closing it. The command running on the
- endpoint has ended so the connection is no longer needed.
-
- @param connection: The L{SSHConnection} to close.
- @type connection: L{SSHConnection}
-
- @param immediate: Whether to close connection immediately.
- @type immediate: L{bool}.
- """
- if immediate:
- # We're assuming the underlying connection is a ITCPTransport,
- # which is what the current implementation is restricted to:
- connection.transport.transport.abortConnection()
- else:
- connection.transport.loseConnection()
-
-
-
-@implementer(_ISSHConnectionCreator)
-class _ExistingConnectionHelper(object):
- """
- L{_ExistingConnectionHelper} implements L{_ISSHConnectionCreator} by
- handing out an existing SSH connection which is supplied to its
- initializer.
- """
-
- def __init__(self, connection):
- """
- @param connection: See L{SSHCommandClientEndpoint.existingConnection}'s
- C{connection} parameter.
- """
- self.connection = connection
-
-
- def secureConnection(self):
- """
- @return: A L{Deferred} that fires synchronously with the
- already-established connection object.
- """
- return succeed(self.connection)
-
-
- def cleanupConnection(self, connection, immediate):
- """
- Do not do any cleanup on the connection. Leave that responsibility to
- whatever code created it in the first place.
-
- @param connection: The L{SSHConnection} which will not be modified in
- any way.
- @type connection: L{SSHConnection}
-
- @param immediate: An argument which will be ignored.
- @type immediate: L{bool}.
- """
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/error.py b/Darwin/lib/python2.7/site-packages/twisted/conch/error.py
deleted file mode 100644
index a3bcc65..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/error.py
+++ /dev/null
@@ -1,102 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-An error to represent bad things happening in Conch.
-
-Maintainer: Paul Swartz
-"""
-
-from twisted.cred.error import UnauthorizedLogin
-
-
-
-class ConchError(Exception):
- def __init__(self, value, data = None):
- Exception.__init__(self, value, data)
- self.value = value
- self.data = data
-
-
-
-class NotEnoughAuthentication(Exception):
- """
- This is thrown if the authentication is valid, but is not enough to
- successfully verify the user. i.e. don't retry this type of
- authentication, try another one.
- """
-
-
-
-class ValidPublicKey(UnauthorizedLogin):
- """
- Raised by public key checkers when they receive public key credentials
- that don't contain a signature at all, but are valid in every other way.
- (e.g. the public key matches one in the user's authorized_keys file).
-
- Protocol code (eg
- L{SSHUserAuthServer}) which
- attempts to log in using
- L{ISSHPrivateKey} credentials
- should be prepared to handle a failure of this type by telling the user to
- re-authenticate using the same key and to include a signature with the new
- attempt.
-
- See U{http://www.ietf.org/rfc/rfc4252.txt} section 7 for more details.
- """
-
-
-
-class IgnoreAuthentication(Exception):
- """
- This is thrown to let the UserAuthServer know it doesn't need to handle the
- authentication anymore.
- """
-
-
-
-class MissingKeyStoreError(Exception):
- """
- Raised if an SSHAgentServer starts receiving data without its factory
- providing a keys dict on which to read/write key data.
- """
-
-
-
-class UserRejectedKey(Exception):
- """
- The user interactively rejected a key.
- """
-
-
-
-class InvalidEntry(Exception):
- """
- An entry in a known_hosts file could not be interpreted as a valid entry.
- """
-
-
-
-class HostKeyChanged(Exception):
- """
- The host key of a remote host has changed.
-
- @ivar offendingEntry: The entry which contains the persistent host key that
- disagrees with the given host key.
-
- @type offendingEntry: L{twisted.conch.interfaces.IKnownHostEntry}
-
- @ivar path: a reference to the known_hosts file that the offending entry
- was loaded from
-
- @type path: L{twisted.python.filepath.FilePath}
-
- @ivar lineno: The line number of the offending entry in the given path.
-
- @type lineno: L{int}
- """
- def __init__(self, offendingEntry, path, lineno):
- Exception.__init__(self)
- self.offendingEntry = offendingEntry
- self.path = path
- self.lineno = lineno
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/conch/insults/__init__.py
deleted file mode 100644
index c070d4f..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/__init__.py
+++ /dev/null
@@ -1,16 +0,0 @@
-"""
-Insults: a replacement for Curses/S-Lang.
-
-Very basic at the moment."""
-
-from twisted.python import deprecate, versions
-
-deprecate.deprecatedModuleAttribute(
- versions.Version("Twisted", 10, 1, 0),
- "Please use twisted.conch.insults.helper instead.",
- __name__, "colors")
-
-deprecate.deprecatedModuleAttribute(
- versions.Version("Twisted", 10, 1, 0),
- "Please use twisted.conch.insults.insults instead.",
- __name__, "client")
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/client.py b/Darwin/lib/python2.7/site-packages/twisted/conch/insults/client.py
deleted file mode 100644
index 89c79cd..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/client.py
+++ /dev/null
@@ -1,138 +0,0 @@
-"""
-You don't really want to use this module. Try insults.py instead.
-"""
-
-from twisted.internet import protocol
-
-class InsultsClient(protocol.Protocol):
-
- escapeTimeout = 0.2
-
- def __init__(self):
- self.width = self.height = None
- self.xpos = self.ypos = 0
- self.commandQueue = []
- self.inEscape = ''
-
- def setSize(self, width, height):
- call = 0
- if self.width:
- call = 1
- self.width = width
- self.height = height
- if call:
- self.windowSizeChanged()
-
- def dataReceived(self, data):
- from twisted.internet import reactor
- for ch in data:
- if ch == '\x1b':
- if self.inEscape:
- self.keyReceived(ch)
- self.inEscape = ''
- else:
- self.inEscape = ch
- self.escapeCall = reactor.callLater(self.escapeTimeout,
- self.endEscape)
- elif ch in 'ABCD' and self.inEscape:
- self.inEscape = ''
- self.escapeCall.cancel()
- if ch == 'A':
- self.keyReceived('')
- elif ch == 'B':
- self.keyReceived('')
- elif ch == 'C':
- self.keyReceived('')
- elif ch == 'D':
- self.keyReceived('')
- elif self.inEscape:
- self.inEscape += ch
- else:
- self.keyReceived(ch)
-
- def endEscape(self):
- ch = self.inEscape
- self.inEscape = ''
- self.keyReceived(ch)
-
- def initScreen(self):
- self.transport.write('\x1b=\x1b[?1h')
-
- def gotoXY(self, x, y):
- """Go to a position on the screen.
- """
- self.xpos = x
- self.ypos = y
- self.commandQueue.append(('gotoxy', x, y))
-
- def writeCh(self, ch):
- """Write a character to the screen. If we're at the end of the row,
- ignore the write.
- """
- if self.xpos < self.width - 1:
- self.commandQueue.append(('write', ch))
- self.xpos += 1
-
- def writeStr(self, s):
- """Write a string to the screen. This does not wrap a the edge of the
- screen, and stops at \\r and \\n.
- """
- s = s[:self.width-self.xpos]
- if '\n' in s:
- s=s[:s.find('\n')]
- if '\r' in s:
- s=s[:s.find('\r')]
- self.commandQueue.append(('write', s))
- self.xpos += len(s)
-
- def eraseToLine(self):
- """Erase from the current position to the end of the line.
- """
- self.commandQueue.append(('eraseeol',))
-
- def eraseToScreen(self):
- """Erase from the current position to the end of the screen.
- """
- self.commandQueue.append(('eraseeos',))
-
- def clearScreen(self):
- """Clear the screen, and return the cursor to 0, 0.
- """
- self.commandQueue = [('cls',)]
- self.xpos = self.ypos = 0
-
- def setAttributes(self, *attrs):
- """Set the attributes for drawing on the screen.
- """
- self.commandQueue.append(('attributes', attrs))
-
- def refresh(self):
- """Redraw the screen.
- """
- redraw = ''
- for command in self.commandQueue:
- if command[0] == 'gotoxy':
- redraw += '\x1b[%i;%iH' % (command[2]+1, command[1]+1)
- elif command[0] == 'write':
- redraw += command[1]
- elif command[0] == 'eraseeol':
- redraw += '\x1b[0K'
- elif command[0] == 'eraseeos':
- redraw += '\x1b[OJ'
- elif command[0] == 'cls':
- redraw += '\x1b[H\x1b[J'
- elif command[0] == 'attributes':
- redraw += '\x1b[%sm' % ';'.join(map(str, command[1]))
- else:
- print command
- self.commandQueue = []
- self.transport.write(redraw)
-
- def windowSizeChanged(self):
- """Called when the size of the window changes.
- Might want to redraw the screen here, or something.
- """
-
- def keyReceived(self, key):
- """Called when the user hits a key.
- """
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/colors.py b/Darwin/lib/python2.7/site-packages/twisted/conch/insults/colors.py
deleted file mode 100644
index c12ab16..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/colors.py
+++ /dev/null
@@ -1,29 +0,0 @@
-"""
-You don't really want to use this module. Try helper.py instead.
-"""
-
-CLEAR = 0
-BOLD = 1
-DIM = 2
-ITALIC = 3
-UNDERSCORE = 4
-BLINK_SLOW = 5
-BLINK_FAST = 6
-REVERSE = 7
-CONCEALED = 8
-FG_BLACK = 30
-FG_RED = 31
-FG_GREEN = 32
-FG_YELLOW = 33
-FG_BLUE = 34
-FG_MAGENTA = 35
-FG_CYAN = 36
-FG_WHITE = 37
-BG_BLACK = 40
-BG_RED = 41
-BG_GREEN = 42
-BG_YELLOW = 43
-BG_BLUE = 44
-BG_MAGENTA = 45
-BG_CYAN = 46
-BG_WHITE = 47
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/helper.py b/Darwin/lib/python2.7/site-packages/twisted/conch/insults/helper.py
deleted file mode 100644
index e0be0b7..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/helper.py
+++ /dev/null
@@ -1,463 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_helper -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Partial in-memory terminal emulator
-
-@author: Jp Calderone
-"""
-
-import re, string
-
-from zope.interface import implements
-
-from twisted.internet import defer, protocol, reactor
-from twisted.python import log, _textattributes
-from twisted.python.deprecate import deprecated, deprecatedModuleAttribute
-from twisted.python.versions import Version
-from twisted.conch.insults import insults
-
-FOREGROUND = 30
-BACKGROUND = 40
-BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, N_COLORS = range(9)
-
-
-
-class _FormattingState(_textattributes._FormattingStateMixin):
- """
- Represents the formatting state/attributes of a single character.
-
- Character set, intensity, underlinedness, blinkitude, video
- reversal, as well as foreground and background colors made up a
- character's attributes.
- """
- compareAttributes = (
- 'charset', 'bold', 'underline', 'blink', 'reverseVideo', 'foreground',
- 'background', '_subtracting')
-
-
- def __init__(self, charset=insults.G0, bold=False, underline=False,
- blink=False, reverseVideo=False, foreground=WHITE,
- background=BLACK, _subtracting=False):
- self.charset = charset
- self.bold = bold
- self.underline = underline
- self.blink = blink
- self.reverseVideo = reverseVideo
- self.foreground = foreground
- self.background = background
- self._subtracting = _subtracting
-
-
- @deprecated(Version('Twisted', 13, 1, 0))
- def wantOne(self, **kw):
- """
- Add a character attribute to a copy of this formatting state.
-
- @param **kw: An optional attribute name and value can be provided with
- a keyword argument.
-
- @return: A formatting state instance with the new attribute.
-
- @see: L{DefaultFormattingState._withAttribute}.
- """
- k, v = kw.popitem()
- return self._withAttribute(k, v)
-
-
- def toVT102(self):
- # Spit out a vt102 control sequence that will set up
- # all the attributes set here. Except charset.
- attrs = []
- if self._subtracting:
- attrs.append(0)
- if self.bold:
- attrs.append(insults.BOLD)
- if self.underline:
- attrs.append(insults.UNDERLINE)
- if self.blink:
- attrs.append(insults.BLINK)
- if self.reverseVideo:
- attrs.append(insults.REVERSE_VIDEO)
- if self.foreground != WHITE:
- attrs.append(FOREGROUND + self.foreground)
- if self.background != BLACK:
- attrs.append(BACKGROUND + self.background)
- if attrs:
- return '\x1b[' + ';'.join(map(str, attrs)) + 'm'
- return ''
-
-CharacterAttribute = _FormattingState
-
-deprecatedModuleAttribute(
- Version('Twisted', 13, 1, 0),
- 'Use twisted.conch.insults.text.assembleFormattedText instead.',
- 'twisted.conch.insults.helper',
- 'CharacterAttribute')
-
-
-
-# XXX - need to support scroll regions and scroll history
-class TerminalBuffer(protocol.Protocol):
- """
- An in-memory terminal emulator.
- """
- implements(insults.ITerminalTransport)
-
- for keyID in ('UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW',
- 'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN',
- 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
- 'F10', 'F11', 'F12'):
- exec '%s = object()' % (keyID,)
-
- TAB = '\t'
- BACKSPACE = '\x7f'
-
- width = 80
- height = 24
-
- fill = ' '
- void = object()
-
- def getCharacter(self, x, y):
- return self.lines[y][x]
-
- def connectionMade(self):
- self.reset()
-
- def write(self, bytes):
- """
- Add the given printable bytes to the terminal.
-
- Line feeds in C{bytes} will be replaced with carriage return / line
- feed pairs.
- """
- for b in bytes.replace('\n', '\r\n'):
- self.insertAtCursor(b)
-
- def _currentFormattingState(self):
- return _FormattingState(self.activeCharset, **self.graphicRendition)
-
- def insertAtCursor(self, b):
- """
- Add one byte to the terminal at the cursor and make consequent state
- updates.
-
- If b is a carriage return, move the cursor to the beginning of the
- current row.
-
- If b is a line feed, move the cursor to the next row or scroll down if
- the cursor is already in the last row.
-
- Otherwise, if b is printable, put it at the cursor position (inserting
- or overwriting as dictated by the current mode) and move the cursor.
- """
- if b == '\r':
- self.x = 0
- elif b == '\n':
- self._scrollDown()
- elif b in string.printable:
- if self.x >= self.width:
- self.nextLine()
- ch = (b, self._currentFormattingState())
- if self.modes.get(insults.modes.IRM):
- self.lines[self.y][self.x:self.x] = [ch]
- self.lines[self.y].pop()
- else:
- self.lines[self.y][self.x] = ch
- self.x += 1
-
- def _emptyLine(self, width):
- return [(self.void, self._currentFormattingState())
- for i in xrange(width)]
-
- def _scrollDown(self):
- self.y += 1
- if self.y >= self.height:
- self.y -= 1
- del self.lines[0]
- self.lines.append(self._emptyLine(self.width))
-
- def _scrollUp(self):
- self.y -= 1
- if self.y < 0:
- self.y = 0
- del self.lines[-1]
- self.lines.insert(0, self._emptyLine(self.width))
-
- def cursorUp(self, n=1):
- self.y = max(0, self.y - n)
-
- def cursorDown(self, n=1):
- self.y = min(self.height - 1, self.y + n)
-
- def cursorBackward(self, n=1):
- self.x = max(0, self.x - n)
-
- def cursorForward(self, n=1):
- self.x = min(self.width, self.x + n)
-
- def cursorPosition(self, column, line):
- self.x = column
- self.y = line
-
- def cursorHome(self):
- self.x = self.home.x
- self.y = self.home.y
-
- def index(self):
- self._scrollDown()
-
- def reverseIndex(self):
- self._scrollUp()
-
- def nextLine(self):
- """
- Update the cursor position attributes and scroll down if appropriate.
- """
- self.x = 0
- self._scrollDown()
-
- def saveCursor(self):
- self._savedCursor = (self.x, self.y)
-
- def restoreCursor(self):
- self.x, self.y = self._savedCursor
- del self._savedCursor
-
- def setModes(self, modes):
- for m in modes:
- self.modes[m] = True
-
- def resetModes(self, modes):
- for m in modes:
- try:
- del self.modes[m]
- except KeyError:
- pass
-
-
- def setPrivateModes(self, modes):
- """
- Enable the given modes.
-
- Track which modes have been enabled so that the implementations of
- other L{insults.ITerminalTransport} methods can be properly implemented
- to respect these settings.
-
- @see: L{resetPrivateModes}
- @see: L{insults.ITerminalTransport.setPrivateModes}
- """
- for m in modes:
- self.privateModes[m] = True
-
-
- def resetPrivateModes(self, modes):
- """
- Disable the given modes.
-
- @see: L{setPrivateModes}
- @see: L{insults.ITerminalTransport.resetPrivateModes}
- """
- for m in modes:
- try:
- del self.privateModes[m]
- except KeyError:
- pass
-
-
- def applicationKeypadMode(self):
- self.keypadMode = 'app'
-
- def numericKeypadMode(self):
- self.keypadMode = 'num'
-
- def selectCharacterSet(self, charSet, which):
- self.charsets[which] = charSet
-
- def shiftIn(self):
- self.activeCharset = insults.G0
-
- def shiftOut(self):
- self.activeCharset = insults.G1
-
- def singleShift2(self):
- oldActiveCharset = self.activeCharset
- self.activeCharset = insults.G2
- f = self.insertAtCursor
- def insertAtCursor(b):
- f(b)
- del self.insertAtCursor
- self.activeCharset = oldActiveCharset
- self.insertAtCursor = insertAtCursor
-
- def singleShift3(self):
- oldActiveCharset = self.activeCharset
- self.activeCharset = insults.G3
- f = self.insertAtCursor
- def insertAtCursor(b):
- f(b)
- del self.insertAtCursor
- self.activeCharset = oldActiveCharset
- self.insertAtCursor = insertAtCursor
-
- def selectGraphicRendition(self, *attributes):
- for a in attributes:
- if a == insults.NORMAL:
- self.graphicRendition = {
- 'bold': False,
- 'underline': False,
- 'blink': False,
- 'reverseVideo': False,
- 'foreground': WHITE,
- 'background': BLACK}
- elif a == insults.BOLD:
- self.graphicRendition['bold'] = True
- elif a == insults.UNDERLINE:
- self.graphicRendition['underline'] = True
- elif a == insults.BLINK:
- self.graphicRendition['blink'] = True
- elif a == insults.REVERSE_VIDEO:
- self.graphicRendition['reverseVideo'] = True
- else:
- try:
- v = int(a)
- except ValueError:
- log.msg("Unknown graphic rendition attribute: " + repr(a))
- else:
- if FOREGROUND <= v <= FOREGROUND + N_COLORS:
- self.graphicRendition['foreground'] = v - FOREGROUND
- elif BACKGROUND <= v <= BACKGROUND + N_COLORS:
- self.graphicRendition['background'] = v - BACKGROUND
- else:
- log.msg("Unknown graphic rendition attribute: " + repr(a))
-
- def eraseLine(self):
- self.lines[self.y] = self._emptyLine(self.width)
-
- def eraseToLineEnd(self):
- width = self.width - self.x
- self.lines[self.y][self.x:] = self._emptyLine(width)
-
- def eraseToLineBeginning(self):
- self.lines[self.y][:self.x + 1] = self._emptyLine(self.x + 1)
-
- def eraseDisplay(self):
- self.lines = [self._emptyLine(self.width) for i in xrange(self.height)]
-
- def eraseToDisplayEnd(self):
- self.eraseToLineEnd()
- height = self.height - self.y - 1
- self.lines[self.y + 1:] = [self._emptyLine(self.width) for i in range(height)]
-
- def eraseToDisplayBeginning(self):
- self.eraseToLineBeginning()
- self.lines[:self.y] = [self._emptyLine(self.width) for i in range(self.y)]
-
- def deleteCharacter(self, n=1):
- del self.lines[self.y][self.x:self.x+n]
- self.lines[self.y].extend(self._emptyLine(min(self.width - self.x, n)))
-
- def insertLine(self, n=1):
- self.lines[self.y:self.y] = [self._emptyLine(self.width) for i in range(n)]
- del self.lines[self.height:]
-
- def deleteLine(self, n=1):
- del self.lines[self.y:self.y+n]
- self.lines.extend([self._emptyLine(self.width) for i in range(n)])
-
- def reportCursorPosition(self):
- return (self.x, self.y)
-
- def reset(self):
- self.home = insults.Vector(0, 0)
- self.x = self.y = 0
- self.modes = {}
- self.privateModes = {}
- self.setPrivateModes([insults.privateModes.AUTO_WRAP,
- insults.privateModes.CURSOR_MODE])
- self.numericKeypad = 'app'
- self.activeCharset = insults.G0
- self.graphicRendition = {
- 'bold': False,
- 'underline': False,
- 'blink': False,
- 'reverseVideo': False,
- 'foreground': WHITE,
- 'background': BLACK}
- self.charsets = {
- insults.G0: insults.CS_US,
- insults.G1: insults.CS_US,
- insults.G2: insults.CS_ALTERNATE,
- insults.G3: insults.CS_ALTERNATE_SPECIAL}
- self.eraseDisplay()
-
- def unhandledControlSequence(self, buf):
- print 'Could not handle', repr(buf)
-
- def __str__(self):
- lines = []
- for L in self.lines:
- buf = []
- length = 0
- for (ch, attr) in L:
- if ch is not self.void:
- buf.append(ch)
- length = len(buf)
- else:
- buf.append(self.fill)
- lines.append(''.join(buf[:length]))
- return '\n'.join(lines)
-
-class ExpectationTimeout(Exception):
- pass
-
-class ExpectableBuffer(TerminalBuffer):
- _mark = 0
-
- def connectionMade(self):
- TerminalBuffer.connectionMade(self)
- self._expecting = []
-
- def write(self, bytes):
- TerminalBuffer.write(self, bytes)
- self._checkExpected()
-
- def cursorHome(self):
- TerminalBuffer.cursorHome(self)
- self._mark = 0
-
- def _timeoutExpected(self, d):
- d.errback(ExpectationTimeout())
- self._checkExpected()
-
- def _checkExpected(self):
- s = str(self)[self._mark:]
- while self._expecting:
- expr, timer, deferred = self._expecting[0]
- if timer and not timer.active():
- del self._expecting[0]
- continue
- for match in expr.finditer(s):
- if timer:
- timer.cancel()
- del self._expecting[0]
- self._mark += match.end()
- s = s[match.end():]
- deferred.callback(match)
- break
- else:
- return
-
- def expect(self, expression, timeout=None, scheduler=reactor):
- d = defer.Deferred()
- timer = None
- if timeout:
- timer = scheduler.callLater(timeout, self._timeoutExpected, d)
- self._expecting.append((re.compile(expression), timer, d))
- self._checkExpected()
- return d
-
-__all__ = [
- 'CharacterAttribute', 'TerminalBuffer', 'ExpectableBuffer']
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/insults.py b/Darwin/lib/python2.7/site-packages/twisted/conch/insults/insults.py
deleted file mode 100644
index 721551d..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/insults.py
+++ /dev/null
@@ -1,1087 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_insults -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-VT102 and VT220 terminal manipulation.
-
-@author: Jp Calderone
-"""
-
-from zope.interface import implements, Interface
-
-from twisted.internet import protocol, defer, interfaces as iinternet
-
-class ITerminalProtocol(Interface):
- def makeConnection(transport):
- """Called with an L{ITerminalTransport} when a connection is established.
- """
-
- def keystrokeReceived(keyID, modifier):
- """A keystroke was received.
-
- Each keystroke corresponds to one invocation of this method.
- keyID is a string identifier for that key. Printable characters
- are represented by themselves. Control keys, such as arrows and
- function keys, are represented with symbolic constants on
- L{ServerProtocol}.
- """
-
- def terminalSize(width, height):
- """Called to indicate the size of the terminal.
-
- A terminal of 80x24 should be assumed if this method is not
- called. This method might not be called for real terminals.
- """
-
- def unhandledControlSequence(seq):
- """Called when an unsupported control sequence is received.
-
- @type seq: C{str}
- @param seq: The whole control sequence which could not be interpreted.
- """
-
- def connectionLost(reason):
- """Called when the connection has been lost.
-
- reason is a Failure describing why.
- """
-
-class TerminalProtocol(object):
- implements(ITerminalProtocol)
-
- def makeConnection(self, terminal):
- # assert ITerminalTransport.providedBy(transport), "TerminalProtocol.makeConnection must be passed an ITerminalTransport implementor"
- self.terminal = terminal
- self.connectionMade()
-
- def connectionMade(self):
- """Called after a connection has been established.
- """
-
- def keystrokeReceived(self, keyID, modifier):
- pass
-
- def terminalSize(self, width, height):
- pass
-
- def unhandledControlSequence(self, seq):
- pass
-
- def connectionLost(self, reason):
- pass
-
-class ITerminalTransport(iinternet.ITransport):
- def cursorUp(n=1):
- """Move the cursor up n lines.
- """
-
- def cursorDown(n=1):
- """Move the cursor down n lines.
- """
-
- def cursorForward(n=1):
- """Move the cursor right n columns.
- """
-
- def cursorBackward(n=1):
- """Move the cursor left n columns.
- """
-
- def cursorPosition(column, line):
- """Move the cursor to the given line and column.
- """
-
- def cursorHome():
- """Move the cursor home.
- """
-
- def index():
- """Move the cursor down one line, performing scrolling if necessary.
- """
-
- def reverseIndex():
- """Move the cursor up one line, performing scrolling if necessary.
- """
-
- def nextLine():
- """Move the cursor to the first position on the next line, performing scrolling if necessary.
- """
-
- def saveCursor():
- """Save the cursor position, character attribute, character set, and origin mode selection.
- """
-
- def restoreCursor():
- """Restore the previously saved cursor position, character attribute, character set, and origin mode selection.
-
- If no cursor state was previously saved, move the cursor to the home position.
- """
-
- def setModes(modes):
- """Set the given modes on the terminal.
- """
-
- def resetModes(mode):
- """Reset the given modes on the terminal.
- """
-
-
- def setPrivateModes(modes):
- """
- Set the given DEC private modes on the terminal.
- """
-
-
- def resetPrivateModes(modes):
- """
- Reset the given DEC private modes on the terminal.
- """
-
-
- def applicationKeypadMode():
- """Cause keypad to generate control functions.
-
- Cursor key mode selects the type of characters generated by cursor keys.
- """
-
- def numericKeypadMode():
- """Cause keypad to generate normal characters.
- """
-
- def selectCharacterSet(charSet, which):
- """Select a character set.
-
- charSet should be one of CS_US, CS_UK, CS_DRAWING, CS_ALTERNATE, or
- CS_ALTERNATE_SPECIAL.
-
- which should be one of G0 or G1.
- """
-
- def shiftIn():
- """Activate the G0 character set.
- """
-
- def shiftOut():
- """Activate the G1 character set.
- """
-
- def singleShift2():
- """Shift to the G2 character set for a single character.
- """
-
- def singleShift3():
- """Shift to the G3 character set for a single character.
- """
-
- def selectGraphicRendition(*attributes):
- """Enabled one or more character attributes.
-
- Arguments should be one or more of UNDERLINE, REVERSE_VIDEO, BLINK, or BOLD.
- NORMAL may also be specified to disable all character attributes.
- """
-
- def horizontalTabulationSet():
- """Set a tab stop at the current cursor position.
- """
-
- def tabulationClear():
- """Clear the tab stop at the current cursor position.
- """
-
- def tabulationClearAll():
- """Clear all tab stops.
- """
-
- def doubleHeightLine(top=True):
- """Make the current line the top or bottom half of a double-height, double-width line.
-
- If top is True, the current line is the top half. Otherwise, it is the bottom half.
- """
-
- def singleWidthLine():
- """Make the current line a single-width, single-height line.
- """
-
- def doubleWidthLine():
- """Make the current line a double-width line.
- """
-
- def eraseToLineEnd():
- """Erase from the cursor to the end of line, including cursor position.
- """
-
- def eraseToLineBeginning():
- """Erase from the cursor to the beginning of the line, including the cursor position.
- """
-
- def eraseLine():
- """Erase the entire cursor line.
- """
-
- def eraseToDisplayEnd():
- """Erase from the cursor to the end of the display, including the cursor position.
- """
-
- def eraseToDisplayBeginning():
- """Erase from the cursor to the beginning of the display, including the cursor position.
- """
-
- def eraseDisplay():
- """Erase the entire display.
- """
-
- def deleteCharacter(n=1):
- """Delete n characters starting at the cursor position.
-
- Characters to the right of deleted characters are shifted to the left.
- """
-
- def insertLine(n=1):
- """Insert n lines at the cursor position.
-
- Lines below the cursor are shifted down. Lines moved past the bottom margin are lost.
- This command is ignored when the cursor is outside the scroll region.
- """
-
- def deleteLine(n=1):
- """Delete n lines starting at the cursor position.
-
- Lines below the cursor are shifted up. This command is ignored when the cursor is outside
- the scroll region.
- """
-
- def reportCursorPosition():
- """Return a Deferred that fires with a two-tuple of (x, y) indicating the cursor position.
- """
-
- def reset():
- """Reset the terminal to its initial state.
- """
-
- def unhandledControlSequence(seq):
- """Called when an unsupported control sequence is received.
-
- @type seq: C{str}
- @param seq: The whole control sequence which could not be interpreted.
- """
-
-
-CSI = '\x1b'
-CST = {'~': 'tilde'}
-
-class modes:
- """ECMA 48 standardized modes
- """
-
- # BREAKS YOPUR KEYBOARD MOFO
- KEYBOARD_ACTION = KAM = 2
-
- # When set, enables character insertion. New display characters
- # move old display characters to the right. Characters moved past
- # the right margin are lost.
-
- # When reset, enables replacement mode (disables character
- # insertion). New display characters replace old display
- # characters at cursor position. The old character is erased.
- INSERTION_REPLACEMENT = IRM = 4
-
- # Set causes a received linefeed, form feed, or vertical tab to
- # move cursor to first column of next line. RETURN transmits both
- # a carriage return and linefeed. This selection is also called
- # new line option.
-
- # Reset causes a received linefeed, form feed, or vertical tab to
- # move cursor to next line in current column. RETURN transmits a
- # carriage return.
- LINEFEED_NEWLINE = LNM = 20
-
-
-class privateModes:
- """ANSI-Compatible Private Modes
- """
- ERROR = 0
- CURSOR_KEY = 1
- ANSI_VT52 = 2
- COLUMN = 3
- SCROLL = 4
- SCREEN = 5
- ORIGIN = 6
- AUTO_WRAP = 7
- AUTO_REPEAT = 8
- PRINTER_FORM_FEED = 18
- PRINTER_EXTENT = 19
-
- # Toggle cursor visibility (reset hides it)
- CURSOR_MODE = 25
-
-
-# Character sets
-CS_US = 'CS_US'
-CS_UK = 'CS_UK'
-CS_DRAWING = 'CS_DRAWING'
-CS_ALTERNATE = 'CS_ALTERNATE'
-CS_ALTERNATE_SPECIAL = 'CS_ALTERNATE_SPECIAL'
-
-# Groupings (or something?? These are like variables that can be bound to character sets)
-G0 = 'G0'
-G1 = 'G1'
-
-# G2 and G3 cannot be changed, but they can be shifted to.
-G2 = 'G2'
-G3 = 'G3'
-
-# Character attributes
-
-NORMAL = 0
-BOLD = 1
-UNDERLINE = 4
-BLINK = 5
-REVERSE_VIDEO = 7
-
-class Vector:
- def __init__(self, x, y):
- self.x = x
- self.y = y
-
-def log(s):
- file('log', 'a').write(str(s) + '\n')
-
-# XXX TODO - These attributes are really part of the
-# ITerminalTransport interface, I think.
-_KEY_NAMES = ('UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW',
- 'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN', 'NUMPAD_MIDDLE',
- 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
- 'F10', 'F11', 'F12',
-
- 'ALT', 'SHIFT', 'CONTROL')
-
-class _const(object):
- """
- @ivar name: A string naming this constant
- """
- def __init__(self, name):
- self.name = name
-
- def __repr__(self):
- return '[' + self.name + ']'
-
-
-FUNCTION_KEYS = [
- _const(_name) for _name in _KEY_NAMES]
-
-class ServerProtocol(protocol.Protocol):
- implements(ITerminalTransport)
-
- protocolFactory = None
- terminalProtocol = None
-
- TAB = '\t'
- BACKSPACE = '\x7f'
- ##
-
- lastWrite = ''
-
- state = 'data'
-
- termSize = Vector(80, 24)
- cursorPos = Vector(0, 0)
- scrollRegion = None
-
- # Factory who instantiated me
- factory = None
-
- def __init__(self, protocolFactory=None, *a, **kw):
- """
- @param protocolFactory: A callable which will be invoked with
- *a, **kw and should return an ITerminalProtocol implementor.
- This will be invoked when a connection to this ServerProtocol
- is established.
-
- @param a: Any positional arguments to pass to protocolFactory.
- @param kw: Any keyword arguments to pass to protocolFactory.
- """
- # assert protocolFactory is None or ITerminalProtocol.implementedBy(protocolFactory), "ServerProtocol.__init__ must be passed an ITerminalProtocol implementor"
- if protocolFactory is not None:
- self.protocolFactory = protocolFactory
- self.protocolArgs = a
- self.protocolKwArgs = kw
-
- self._cursorReports = []
-
- def connectionMade(self):
- if self.protocolFactory is not None:
- self.terminalProtocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs)
-
- try:
- factory = self.factory
- except AttributeError:
- pass
- else:
- self.terminalProtocol.factory = factory
-
- self.terminalProtocol.makeConnection(self)
-
- def dataReceived(self, data):
- for ch in data:
- if self.state == 'data':
- if ch == '\x1b':
- self.state = 'escaped'
- else:
- self.terminalProtocol.keystrokeReceived(ch, None)
- elif self.state == 'escaped':
- if ch == '[':
- self.state = 'bracket-escaped'
- self.escBuf = []
- elif ch == 'O':
- self.state = 'low-function-escaped'
- else:
- self.state = 'data'
- self._handleShortControlSequence(ch)
- elif self.state == 'bracket-escaped':
- if ch == 'O':
- self.state = 'low-function-escaped'
- elif ch.isalpha() or ch == '~':
- self._handleControlSequence(''.join(self.escBuf) + ch)
- del self.escBuf
- self.state = 'data'
- else:
- self.escBuf.append(ch)
- elif self.state == 'low-function-escaped':
- self._handleLowFunctionControlSequence(ch)
- self.state = 'data'
- else:
- raise ValueError("Illegal state")
-
- def _handleShortControlSequence(self, ch):
- self.terminalProtocol.keystrokeReceived(ch, self.ALT)
-
- def _handleControlSequence(self, buf):
- buf = '\x1b[' + buf
- f = getattr(self.controlSequenceParser, CST.get(buf[-1], buf[-1]), None)
- if f is None:
- self.unhandledControlSequence(buf)
- else:
- f(self, self.terminalProtocol, buf[:-1])
-
- def unhandledControlSequence(self, buf):
- self.terminalProtocol.unhandledControlSequence(buf)
-
- def _handleLowFunctionControlSequence(self, ch):
- map = {'P': self.F1, 'Q': self.F2, 'R': self.F3, 'S': self.F4}
- keyID = map.get(ch)
- if keyID is not None:
- self.terminalProtocol.keystrokeReceived(keyID, None)
- else:
- self.terminalProtocol.unhandledControlSequence('\x1b[O' + ch)
-
- class ControlSequenceParser:
- def A(self, proto, handler, buf):
- if buf == '\x1b[':
- handler.keystrokeReceived(proto.UP_ARROW, None)
- else:
- handler.unhandledControlSequence(buf + 'A')
-
- def B(self, proto, handler, buf):
- if buf == '\x1b[':
- handler.keystrokeReceived(proto.DOWN_ARROW, None)
- else:
- handler.unhandledControlSequence(buf + 'B')
-
- def C(self, proto, handler, buf):
- if buf == '\x1b[':
- handler.keystrokeReceived(proto.RIGHT_ARROW, None)
- else:
- handler.unhandledControlSequence(buf + 'C')
-
- def D(self, proto, handler, buf):
- if buf == '\x1b[':
- handler.keystrokeReceived(proto.LEFT_ARROW, None)
- else:
- handler.unhandledControlSequence(buf + 'D')
-
- def E(self, proto, handler, buf):
- if buf == '\x1b[':
- handler.keystrokeReceived(proto.NUMPAD_MIDDLE, None)
- else:
- handler.unhandledControlSequence(buf + 'E')
-
- def F(self, proto, handler, buf):
- if buf == '\x1b[':
- handler.keystrokeReceived(proto.END, None)
- else:
- handler.unhandledControlSequence(buf + 'F')
-
- def H(self, proto, handler, buf):
- if buf == '\x1b[':
- handler.keystrokeReceived(proto.HOME, None)
- else:
- handler.unhandledControlSequence(buf + 'H')
-
- def R(self, proto, handler, buf):
- if not proto._cursorReports:
- handler.unhandledControlSequence(buf + 'R')
- elif buf.startswith('\x1b['):
- report = buf[2:]
- parts = report.split(';')
- if len(parts) != 2:
- handler.unhandledControlSequence(buf + 'R')
- else:
- Pl, Pc = parts
- try:
- Pl, Pc = int(Pl), int(Pc)
- except ValueError:
- handler.unhandledControlSequence(buf + 'R')
- else:
- d = proto._cursorReports.pop(0)
- d.callback((Pc - 1, Pl - 1))
- else:
- handler.unhandledControlSequence(buf + 'R')
-
- def Z(self, proto, handler, buf):
- if buf == '\x1b[':
- handler.keystrokeReceived(proto.TAB, proto.SHIFT)
- else:
- handler.unhandledControlSequence(buf + 'Z')
-
- def tilde(self, proto, handler, buf):
- map = {1: proto.HOME, 2: proto.INSERT, 3: proto.DELETE,
- 4: proto.END, 5: proto.PGUP, 6: proto.PGDN,
-
- 15: proto.F5, 17: proto.F6, 18: proto.F7,
- 19: proto.F8, 20: proto.F9, 21: proto.F10,
- 23: proto.F11, 24: proto.F12}
-
- if buf.startswith('\x1b['):
- ch = buf[2:]
- try:
- v = int(ch)
- except ValueError:
- handler.unhandledControlSequence(buf + '~')
- else:
- symbolic = map.get(v)
- if symbolic is not None:
- handler.keystrokeReceived(map[v], None)
- else:
- handler.unhandledControlSequence(buf + '~')
- else:
- handler.unhandledControlSequence(buf + '~')
-
- controlSequenceParser = ControlSequenceParser()
-
- # ITerminalTransport
- def cursorUp(self, n=1):
- assert n >= 1
- self.cursorPos.y = max(self.cursorPos.y - n, 0)
- self.write('\x1b[%dA' % (n,))
-
- def cursorDown(self, n=1):
- assert n >= 1
- self.cursorPos.y = min(self.cursorPos.y + n, self.termSize.y - 1)
- self.write('\x1b[%dB' % (n,))
-
- def cursorForward(self, n=1):
- assert n >= 1
- self.cursorPos.x = min(self.cursorPos.x + n, self.termSize.x - 1)
- self.write('\x1b[%dC' % (n,))
-
- def cursorBackward(self, n=1):
- assert n >= 1
- self.cursorPos.x = max(self.cursorPos.x - n, 0)
- self.write('\x1b[%dD' % (n,))
-
- def cursorPosition(self, column, line):
- self.write('\x1b[%d;%dH' % (line + 1, column + 1))
-
- def cursorHome(self):
- self.cursorPos.x = self.cursorPos.y = 0
- self.write('\x1b[H')
-
- def index(self):
- self.cursorPos.y = min(self.cursorPos.y + 1, self.termSize.y - 1)
- self.write('\x1bD')
-
- def reverseIndex(self):
- self.cursorPos.y = max(self.cursorPos.y - 1, 0)
- self.write('\x1bM')
-
- def nextLine(self):
- self.cursorPos.x = 0
- self.cursorPos.y = min(self.cursorPos.y + 1, self.termSize.y - 1)
- self.write('\n')
-
- def saveCursor(self):
- self._savedCursorPos = Vector(self.cursorPos.x, self.cursorPos.y)
- self.write('\x1b7')
-
- def restoreCursor(self):
- self.cursorPos = self._savedCursorPos
- del self._savedCursorPos
- self.write('\x1b8')
-
- def setModes(self, modes):
- # XXX Support ANSI-Compatible private modes
- self.write('\x1b[%sh' % (';'.join(map(str, modes)),))
-
- def setPrivateModes(self, modes):
- self.write('\x1b[?%sh' % (';'.join(map(str, modes)),))
-
- def resetModes(self, modes):
- # XXX Support ANSI-Compatible private modes
- self.write('\x1b[%sl' % (';'.join(map(str, modes)),))
-
- def resetPrivateModes(self, modes):
- self.write('\x1b[?%sl' % (';'.join(map(str, modes)),))
-
- def applicationKeypadMode(self):
- self.write('\x1b=')
-
- def numericKeypadMode(self):
- self.write('\x1b>')
-
- def selectCharacterSet(self, charSet, which):
- # XXX Rewrite these as dict lookups
- if which == G0:
- which = '('
- elif which == G1:
- which = ')'
- else:
- raise ValueError("`which' argument to selectCharacterSet must be G0 or G1")
- if charSet == CS_UK:
- charSet = 'A'
- elif charSet == CS_US:
- charSet = 'B'
- elif charSet == CS_DRAWING:
- charSet = '0'
- elif charSet == CS_ALTERNATE:
- charSet = '1'
- elif charSet == CS_ALTERNATE_SPECIAL:
- charSet = '2'
- else:
- raise ValueError("Invalid `charSet' argument to selectCharacterSet")
- self.write('\x1b' + which + charSet)
-
- def shiftIn(self):
- self.write('\x15')
-
- def shiftOut(self):
- self.write('\x14')
-
- def singleShift2(self):
- self.write('\x1bN')
-
- def singleShift3(self):
- self.write('\x1bO')
-
- def selectGraphicRendition(self, *attributes):
- attrs = []
- for a in attributes:
- attrs.append(a)
- self.write('\x1b[%sm' % (';'.join(attrs),))
-
- def horizontalTabulationSet(self):
- self.write('\x1bH')
-
- def tabulationClear(self):
- self.write('\x1b[q')
-
- def tabulationClearAll(self):
- self.write('\x1b[3q')
-
- def doubleHeightLine(self, top=True):
- if top:
- self.write('\x1b#3')
- else:
- self.write('\x1b#4')
-
- def singleWidthLine(self):
- self.write('\x1b#5')
-
- def doubleWidthLine(self):
- self.write('\x1b#6')
-
- def eraseToLineEnd(self):
- self.write('\x1b[K')
-
- def eraseToLineBeginning(self):
- self.write('\x1b[1K')
-
- def eraseLine(self):
- self.write('\x1b[2K')
-
- def eraseToDisplayEnd(self):
- self.write('\x1b[J')
-
- def eraseToDisplayBeginning(self):
- self.write('\x1b[1J')
-
- def eraseDisplay(self):
- self.write('\x1b[2J')
-
- def deleteCharacter(self, n=1):
- self.write('\x1b[%dP' % (n,))
-
- def insertLine(self, n=1):
- self.write('\x1b[%dL' % (n,))
-
- def deleteLine(self, n=1):
- self.write('\x1b[%dM' % (n,))
-
- def setScrollRegion(self, first=None, last=None):
- if first is not None:
- first = '%d' % (first,)
- else:
- first = ''
- if last is not None:
- last = '%d' % (last,)
- else:
- last = ''
- self.write('\x1b[%s;%sr' % (first, last))
-
- def resetScrollRegion(self):
- self.setScrollRegion()
-
- def reportCursorPosition(self):
- d = defer.Deferred()
- self._cursorReports.append(d)
- self.write('\x1b[6n')
- return d
-
- def reset(self):
- self.cursorPos.x = self.cursorPos.y = 0
- try:
- del self._savedCursorPos
- except AttributeError:
- pass
- self.write('\x1bc')
-
- # ITransport
- def write(self, bytes):
- if bytes:
- self.lastWrite = bytes
- self.transport.write('\r\n'.join(bytes.split('\n')))
-
- def writeSequence(self, bytes):
- self.write(''.join(bytes))
-
- def loseConnection(self):
- self.reset()
- self.transport.loseConnection()
-
- def connectionLost(self, reason):
- if self.terminalProtocol is not None:
- try:
- self.terminalProtocol.connectionLost(reason)
- finally:
- self.terminalProtocol = None
-# Add symbolic names for function keys
-for name, const in zip(_KEY_NAMES, FUNCTION_KEYS):
- setattr(ServerProtocol, name, const)
-
-
-
-class ClientProtocol(protocol.Protocol):
-
- terminalFactory = None
- terminal = None
-
- state = 'data'
-
- _escBuf = None
-
- _shorts = {
- 'D': 'index',
- 'M': 'reverseIndex',
- 'E': 'nextLine',
- '7': 'saveCursor',
- '8': 'restoreCursor',
- '=': 'applicationKeypadMode',
- '>': 'numericKeypadMode',
- 'N': 'singleShift2',
- 'O': 'singleShift3',
- 'H': 'horizontalTabulationSet',
- 'c': 'reset'}
-
- _longs = {
- '[': 'bracket-escape',
- '(': 'select-g0',
- ')': 'select-g1',
- '#': 'select-height-width'}
-
- _charsets = {
- 'A': CS_UK,
- 'B': CS_US,
- '0': CS_DRAWING,
- '1': CS_ALTERNATE,
- '2': CS_ALTERNATE_SPECIAL}
-
- # Factory who instantiated me
- factory = None
-
- def __init__(self, terminalFactory=None, *a, **kw):
- """
- @param terminalFactory: A callable which will be invoked with
- *a, **kw and should return an ITerminalTransport provider.
- This will be invoked when this ClientProtocol establishes a
- connection.
-
- @param a: Any positional arguments to pass to terminalFactory.
- @param kw: Any keyword arguments to pass to terminalFactory.
- """
- # assert terminalFactory is None or ITerminalTransport.implementedBy(terminalFactory), "ClientProtocol.__init__ must be passed an ITerminalTransport implementor"
- if terminalFactory is not None:
- self.terminalFactory = terminalFactory
- self.terminalArgs = a
- self.terminalKwArgs = kw
-
- def connectionMade(self):
- if self.terminalFactory is not None:
- self.terminal = self.terminalFactory(*self.terminalArgs, **self.terminalKwArgs)
- self.terminal.factory = self.factory
- self.terminal.makeConnection(self)
-
- def connectionLost(self, reason):
- if self.terminal is not None:
- try:
- self.terminal.connectionLost(reason)
- finally:
- del self.terminal
-
- def dataReceived(self, bytes):
- """
- Parse the given data from a terminal server, dispatching to event
- handlers defined by C{self.terminal}.
- """
- toWrite = []
- for b in bytes:
- if self.state == 'data':
- if b == '\x1b':
- if toWrite:
- self.terminal.write(''.join(toWrite))
- del toWrite[:]
- self.state = 'escaped'
- elif b == '\x14':
- if toWrite:
- self.terminal.write(''.join(toWrite))
- del toWrite[:]
- self.terminal.shiftOut()
- elif b == '\x15':
- if toWrite:
- self.terminal.write(''.join(toWrite))
- del toWrite[:]
- self.terminal.shiftIn()
- elif b == '\x08':
- if toWrite:
- self.terminal.write(''.join(toWrite))
- del toWrite[:]
- self.terminal.cursorBackward()
- else:
- toWrite.append(b)
- elif self.state == 'escaped':
- fName = self._shorts.get(b)
- if fName is not None:
- self.state = 'data'
- getattr(self.terminal, fName)()
- else:
- state = self._longs.get(b)
- if state is not None:
- self.state = state
- else:
- self.terminal.unhandledControlSequence('\x1b' + b)
- self.state = 'data'
- elif self.state == 'bracket-escape':
- if self._escBuf is None:
- self._escBuf = []
- if b.isalpha() or b == '~':
- self._handleControlSequence(''.join(self._escBuf), b)
- del self._escBuf
- self.state = 'data'
- else:
- self._escBuf.append(b)
- elif self.state == 'select-g0':
- self.terminal.selectCharacterSet(self._charsets.get(b, b), G0)
- self.state = 'data'
- elif self.state == 'select-g1':
- self.terminal.selectCharacterSet(self._charsets.get(b, b), G1)
- self.state = 'data'
- elif self.state == 'select-height-width':
- self._handleHeightWidth(b)
- self.state = 'data'
- else:
- raise ValueError("Illegal state")
- if toWrite:
- self.terminal.write(''.join(toWrite))
-
-
- def _handleControlSequence(self, buf, terminal):
- f = getattr(self.controlSequenceParser, CST.get(terminal, terminal), None)
- if f is None:
- self.terminal.unhandledControlSequence('\x1b[' + buf + terminal)
- else:
- f(self, self.terminal, buf)
-
- class ControlSequenceParser:
- def _makeSimple(ch, fName):
- n = 'cursor' + fName
- def simple(self, proto, handler, buf):
- if not buf:
- getattr(handler, n)(1)
- else:
- try:
- m = int(buf)
- except ValueError:
- handler.unhandledControlSequence('\x1b[' + buf + ch)
- else:
- getattr(handler, n)(m)
- return simple
- for (ch, fName) in (('A', 'Up'),
- ('B', 'Down'),
- ('C', 'Forward'),
- ('D', 'Backward')):
- exec ch + " = _makeSimple(ch, fName)"
- del _makeSimple
-
- def h(self, proto, handler, buf):
- # XXX - Handle '?' to introduce ANSI-Compatible private modes.
- try:
- modes = map(int, buf.split(';'))
- except ValueError:
- handler.unhandledControlSequence('\x1b[' + buf + 'h')
- else:
- handler.setModes(modes)
-
- def l(self, proto, handler, buf):
- # XXX - Handle '?' to introduce ANSI-Compatible private modes.
- try:
- modes = map(int, buf.split(';'))
- except ValueError:
- handler.unhandledControlSequence('\x1b[' + buf + 'l')
- else:
- handler.resetModes(modes)
-
- def r(self, proto, handler, buf):
- parts = buf.split(';')
- if len(parts) == 1:
- handler.setScrollRegion(None, None)
- elif len(parts) == 2:
- try:
- if parts[0]:
- pt = int(parts[0])
- else:
- pt = None
- if parts[1]:
- pb = int(parts[1])
- else:
- pb = None
- except ValueError:
- handler.unhandledControlSequence('\x1b[' + buf + 'r')
- else:
- handler.setScrollRegion(pt, pb)
- else:
- handler.unhandledControlSequence('\x1b[' + buf + 'r')
-
- def K(self, proto, handler, buf):
- if not buf:
- handler.eraseToLineEnd()
- elif buf == '1':
- handler.eraseToLineBeginning()
- elif buf == '2':
- handler.eraseLine()
- else:
- handler.unhandledControlSequence('\x1b[' + buf + 'K')
-
- def H(self, proto, handler, buf):
- handler.cursorHome()
-
- def J(self, proto, handler, buf):
- if not buf:
- handler.eraseToDisplayEnd()
- elif buf == '1':
- handler.eraseToDisplayBeginning()
- elif buf == '2':
- handler.eraseDisplay()
- else:
- handler.unhandledControlSequence('\x1b[' + buf + 'J')
-
- def P(self, proto, handler, buf):
- if not buf:
- handler.deleteCharacter(1)
- else:
- try:
- n = int(buf)
- except ValueError:
- handler.unhandledControlSequence('\x1b[' + buf + 'P')
- else:
- handler.deleteCharacter(n)
-
- def L(self, proto, handler, buf):
- if not buf:
- handler.insertLine(1)
- else:
- try:
- n = int(buf)
- except ValueError:
- handler.unhandledControlSequence('\x1b[' + buf + 'L')
- else:
- handler.insertLine(n)
-
- def M(self, proto, handler, buf):
- if not buf:
- handler.deleteLine(1)
- else:
- try:
- n = int(buf)
- except ValueError:
- handler.unhandledControlSequence('\x1b[' + buf + 'M')
- else:
- handler.deleteLine(n)
-
- def n(self, proto, handler, buf):
- if buf == '6':
- x, y = handler.reportCursorPosition()
- proto.transport.write('\x1b[%d;%dR' % (x + 1, y + 1))
- else:
- handler.unhandledControlSequence('\x1b[' + buf + 'n')
-
- def m(self, proto, handler, buf):
- if not buf:
- handler.selectGraphicRendition(NORMAL)
- else:
- attrs = []
- for a in buf.split(';'):
- try:
- a = int(a)
- except ValueError:
- pass
- attrs.append(a)
- handler.selectGraphicRendition(*attrs)
-
- controlSequenceParser = ControlSequenceParser()
-
- def _handleHeightWidth(self, b):
- if b == '3':
- self.terminal.doubleHeightLine(True)
- elif b == '4':
- self.terminal.doubleHeightLine(False)
- elif b == '5':
- self.terminal.singleWidthLine()
- elif b == '6':
- self.terminal.doubleWidthLine()
- else:
- self.terminal.unhandledControlSequence('\x1b#' + b)
-
-
-__all__ = [
- # Interfaces
- 'ITerminalProtocol', 'ITerminalTransport',
-
- # Symbolic constants
- 'modes', 'privateModes', 'FUNCTION_KEYS',
-
- 'CS_US', 'CS_UK', 'CS_DRAWING', 'CS_ALTERNATE', 'CS_ALTERNATE_SPECIAL',
- 'G0', 'G1', 'G2', 'G3',
-
- 'UNDERLINE', 'REVERSE_VIDEO', 'BLINK', 'BOLD', 'NORMAL',
-
- # Protocol classes
- 'ServerProtocol', 'ClientProtocol']
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/text.py b/Darwin/lib/python2.7/site-packages/twisted/conch/insults/text.py
deleted file mode 100644
index a0d2c5f..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/text.py
+++ /dev/null
@@ -1,175 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_text -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Character attribute manipulation API.
-
-This module provides a domain-specific language (using Python syntax)
-for the creation of text with additional display attributes associated
-with it. It is intended as an alternative to manually building up
-strings containing ECMA 48 character attribute control codes. It
-currently supports foreground and background colors (black, red,
-green, yellow, blue, magenta, cyan, and white), intensity selection,
-underlining, blinking and reverse video. Character set selection
-support is planned.
-
-Character attributes are specified by using two Python operations:
-attribute lookup and indexing. For example, the string \"Hello
-world\" with red foreground and all other attributes set to their
-defaults, assuming the name twisted.conch.insults.text.attributes has
-been imported and bound to the name \"A\" (with the statement C{from
-twisted.conch.insults.text import attributes as A}, for example) one
-uses this expression::
-
- A.fg.red[\"Hello world\"]
-
-Other foreground colors are set by substituting their name for
-\"red\". To set both a foreground and a background color, this
-expression is used::
-
- A.fg.red[A.bg.green[\"Hello world\"]]
-
-Note that either A.bg.green can be nested within A.fg.red or vice
-versa. Also note that multiple items can be nested within a single
-index operation by separating them with commas::
-
- A.bg.green[A.fg.red[\"Hello\"], " ", A.fg.blue[\"world\"]]
-
-Other character attributes are set in a similar fashion. To specify a
-blinking version of the previous expression::
-
- A.blink[A.bg.green[A.fg.red[\"Hello\"], " ", A.fg.blue[\"world\"]]]
-
-C{A.reverseVideo}, C{A.underline}, and C{A.bold} are also valid.
-
-A third operation is actually supported: unary negation. This turns
-off an attribute when an enclosing expression would otherwise have
-caused it to be on. For example::
-
- A.underline[A.fg.red[\"Hello\", -A.underline[\" world\"]]]
-
-A formatting structure can then be serialized into a string containing the
-necessary VT102 control codes with L{assembleFormattedText}.
-
-@see: L{twisted.conch.insults.text.attributes}
-@author: Jp Calderone
-"""
-
-from twisted.conch.insults import helper, insults
-from twisted.python import _textattributes
-from twisted.python.deprecate import deprecatedModuleAttribute
-from twisted.python.versions import Version
-
-
-
-flatten = _textattributes.flatten
-
-deprecatedModuleAttribute(
- Version('Twisted', 13, 1, 0),
- 'Use twisted.conch.insults.text.assembleFormattedText instead.',
- 'twisted.conch.insults.text',
- 'flatten')
-
-_TEXT_COLORS = {
- 'black': helper.BLACK,
- 'red': helper.RED,
- 'green': helper.GREEN,
- 'yellow': helper.YELLOW,
- 'blue': helper.BLUE,
- 'magenta': helper.MAGENTA,
- 'cyan': helper.CYAN,
- 'white': helper.WHITE}
-
-
-
-class _CharacterAttributes(_textattributes.CharacterAttributesMixin):
- """
- Factory for character attributes, including foreground and background color
- and non-color attributes such as bold, reverse video and underline.
-
- Character attributes are applied to actual text by using object
- indexing-syntax (C{obj['abc']}) after accessing a factory attribute, for
- example::
-
- attributes.bold['Some text']
-
- These can be nested to mix attributes::
-
- attributes.bold[attributes.underline['Some text']]
-
- And multiple values can be passed::
-
- attributes.normal[attributes.bold['Some'], ' text']
-
- Non-color attributes can be accessed by attribute name, available
- attributes are:
-
- - bold
- - blink
- - reverseVideo
- - underline
-
- Available colors are:
-
- 0. black
- 1. red
- 2. green
- 3. yellow
- 4. blue
- 5. magenta
- 6. cyan
- 7. white
-
- @ivar fg: Foreground colors accessed by attribute name, see above
- for possible names.
-
- @ivar bg: Background colors accessed by attribute name, see above
- for possible names.
- """
- fg = _textattributes._ColorAttribute(
- _textattributes._ForegroundColorAttr, _TEXT_COLORS)
- bg = _textattributes._ColorAttribute(
- _textattributes._BackgroundColorAttr, _TEXT_COLORS)
-
- attrs = {
- 'bold': insults.BOLD,
- 'blink': insults.BLINK,
- 'underline': insults.UNDERLINE,
- 'reverseVideo': insults.REVERSE_VIDEO}
-
-
-
-def assembleFormattedText(formatted):
- """
- Assemble formatted text from structured information.
-
- Currently handled formatting includes: bold, blink, reverse, underline and
- color codes.
-
- For example::
-
- from twisted.conch.insults.text import attributes as A
- assembleFormattedText(
- A.normal[A.bold['Time: '], A.fg.lightRed['Now!']])
-
- Would produce "Time: " in bold formatting, followed by "Now!" with a
- foreground color of light red and without any additional formatting.
-
- @param formatted: Structured text and attributes.
-
- @rtype: C{str}
- @return: String containing VT102 control sequences that mimic those
- specified by L{formatted}.
-
- @see: L{twisted.conch.insults.text.attributes}
- @since: 13.1
- """
- return _textattributes.flatten(
- formatted, helper._FormattingState(), 'toVT102')
-
-
-
-attributes = _CharacterAttributes()
-
-__all__ = ['attributes', 'flatten']
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/window.py b/Darwin/lib/python2.7/site-packages/twisted/conch/insults/window.py
deleted file mode 100644
index 9901327..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/insults/window.py
+++ /dev/null
@@ -1,868 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_window -*-
-
-"""
-Simple insults-based widget library
-
-@author: Jp Calderone
-"""
-
-import array
-
-from twisted.conch.insults import insults, helper
-from twisted.python import text as tptext
-
-class YieldFocus(Exception):
- """Input focus manipulation exception
- """
-
-class BoundedTerminalWrapper(object):
- def __init__(self, terminal, width, height, xoff, yoff):
- self.width = width
- self.height = height
- self.xoff = xoff
- self.yoff = yoff
- self.terminal = terminal
- self.cursorForward = terminal.cursorForward
- self.selectCharacterSet = terminal.selectCharacterSet
- self.selectGraphicRendition = terminal.selectGraphicRendition
- self.saveCursor = terminal.saveCursor
- self.restoreCursor = terminal.restoreCursor
-
- def cursorPosition(self, x, y):
- return self.terminal.cursorPosition(
- self.xoff + min(self.width, x),
- self.yoff + min(self.height, y)
- )
-
- def cursorHome(self):
- return self.terminal.cursorPosition(
- self.xoff, self.yoff)
-
- def write(self, bytes):
- return self.terminal.write(bytes)
-
-class Widget(object):
- focused = False
- parent = None
- dirty = False
- width = height = None
-
- def repaint(self):
- if not self.dirty:
- self.dirty = True
- if self.parent is not None and not self.parent.dirty:
- self.parent.repaint()
-
- def filthy(self):
- self.dirty = True
-
- def redraw(self, width, height, terminal):
- self.filthy()
- self.draw(width, height, terminal)
-
- def draw(self, width, height, terminal):
- if width != self.width or height != self.height or self.dirty:
- self.width = width
- self.height = height
- self.dirty = False
- self.render(width, height, terminal)
-
- def render(self, width, height, terminal):
- pass
-
- def sizeHint(self):
- return None
-
- def keystrokeReceived(self, keyID, modifier):
- if keyID == '\t':
- self.tabReceived(modifier)
- elif keyID == '\x7f':
- self.backspaceReceived()
- elif keyID in insults.FUNCTION_KEYS:
- self.functionKeyReceived(keyID, modifier)
- else:
- self.characterReceived(keyID, modifier)
-
- def tabReceived(self, modifier):
- # XXX TODO - Handle shift+tab
- raise YieldFocus()
-
- def focusReceived(self):
- """Called when focus is being given to this widget.
-
- May raise YieldFocus is this widget does not want focus.
- """
- self.focused = True
- self.repaint()
-
- def focusLost(self):
- self.focused = False
- self.repaint()
-
- def backspaceReceived(self):
- pass
-
- def functionKeyReceived(self, keyID, modifier):
- func = getattr(self, 'func_' + keyID.name, None)
- if func is not None:
- func(modifier)
-
- def characterReceived(self, keyID, modifier):
- pass
-
-class ContainerWidget(Widget):
- """
- @ivar focusedChild: The contained widget which currently has
- focus, or None.
- """
- focusedChild = None
- focused = False
-
- def __init__(self):
- Widget.__init__(self)
- self.children = []
-
- def addChild(self, child):
- assert child.parent is None
- child.parent = self
- self.children.append(child)
- if self.focusedChild is None and self.focused:
- try:
- child.focusReceived()
- except YieldFocus:
- pass
- else:
- self.focusedChild = child
- self.repaint()
-
- def remChild(self, child):
- assert child.parent is self
- child.parent = None
- self.children.remove(child)
- self.repaint()
-
- def filthy(self):
- for ch in self.children:
- ch.filthy()
- Widget.filthy(self)
-
- def render(self, width, height, terminal):
- for ch in self.children:
- ch.draw(width, height, terminal)
-
- def changeFocus(self):
- self.repaint()
-
- if self.focusedChild is not None:
- self.focusedChild.focusLost()
- focusedChild = self.focusedChild
- self.focusedChild = None
- try:
- curFocus = self.children.index(focusedChild) + 1
- except ValueError:
- raise YieldFocus()
- else:
- curFocus = 0
- while curFocus < len(self.children):
- try:
- self.children[curFocus].focusReceived()
- except YieldFocus:
- curFocus += 1
- else:
- self.focusedChild = self.children[curFocus]
- return
- # None of our children wanted focus
- raise YieldFocus()
-
-
- def focusReceived(self):
- self.changeFocus()
- self.focused = True
-
-
- def keystrokeReceived(self, keyID, modifier):
- if self.focusedChild is not None:
- try:
- self.focusedChild.keystrokeReceived(keyID, modifier)
- except YieldFocus:
- self.changeFocus()
- self.repaint()
- else:
- Widget.keystrokeReceived(self, keyID, modifier)
-
-
-class TopWindow(ContainerWidget):
- """
- A top-level container object which provides focus wrap-around and paint
- scheduling.
-
- @ivar painter: A no-argument callable which will be invoked when this
- widget needs to be redrawn.
-
- @ivar scheduler: A one-argument callable which will be invoked with a
- no-argument callable and should arrange for it to invoked at some point in
- the near future. The no-argument callable will cause this widget and all
- its children to be redrawn. It is typically beneficial for the no-argument
- callable to be invoked at the end of handling for whatever event is
- currently active; for example, it might make sense to call it at the end of
- L{twisted.conch.insults.insults.ITerminalProtocol.keystrokeReceived}.
- Note, however, that since calls to this may also be made in response to no
- apparent event, arrangements should be made for the function to be called
- even if an event handler such as C{keystrokeReceived} is not on the call
- stack (eg, using C{reactor.callLater} with a short timeout).
- """
- focused = True
-
- def __init__(self, painter, scheduler):
- ContainerWidget.__init__(self)
- self.painter = painter
- self.scheduler = scheduler
-
- _paintCall = None
- def repaint(self):
- if self._paintCall is None:
- self._paintCall = object()
- self.scheduler(self._paint)
- ContainerWidget.repaint(self)
-
- def _paint(self):
- self._paintCall = None
- self.painter()
-
- def changeFocus(self):
- try:
- ContainerWidget.changeFocus(self)
- except YieldFocus:
- try:
- ContainerWidget.changeFocus(self)
- except YieldFocus:
- pass
-
- def keystrokeReceived(self, keyID, modifier):
- try:
- ContainerWidget.keystrokeReceived(self, keyID, modifier)
- except YieldFocus:
- self.changeFocus()
-
-
-class AbsoluteBox(ContainerWidget):
- def moveChild(self, child, x, y):
- for n in range(len(self.children)):
- if self.children[n][0] is child:
- self.children[n] = (child, x, y)
- break
- else:
- raise ValueError("No such child", child)
-
- def render(self, width, height, terminal):
- for (ch, x, y) in self.children:
- wrap = BoundedTerminalWrapper(terminal, width - x, height - y, x, y)
- ch.draw(width, height, wrap)
-
-
-class _Box(ContainerWidget):
- TOP, CENTER, BOTTOM = range(3)
-
- def __init__(self, gravity=CENTER):
- ContainerWidget.__init__(self)
- self.gravity = gravity
-
- def sizeHint(self):
- height = 0
- width = 0
- for ch in self.children:
- hint = ch.sizeHint()
- if hint is None:
- hint = (None, None)
-
- if self.variableDimension == 0:
- if hint[0] is None:
- width = None
- elif width is not None:
- width += hint[0]
- if hint[1] is None:
- height = None
- elif height is not None:
- height = max(height, hint[1])
- else:
- if hint[0] is None:
- width = None
- elif width is not None:
- width = max(width, hint[0])
- if hint[1] is None:
- height = None
- elif height is not None:
- height += hint[1]
-
- return width, height
-
-
- def render(self, width, height, terminal):
- if not self.children:
- return
-
- greedy = 0
- wants = []
- for ch in self.children:
- hint = ch.sizeHint()
- if hint is None:
- hint = (None, None)
- if hint[self.variableDimension] is None:
- greedy += 1
- wants.append(hint[self.variableDimension])
-
- length = (width, height)[self.variableDimension]
- totalWant = sum([w for w in wants if w is not None])
- if greedy:
- leftForGreedy = int((length - totalWant) / greedy)
-
- widthOffset = heightOffset = 0
-
- for want, ch in zip(wants, self.children):
- if want is None:
- want = leftForGreedy
-
- subWidth, subHeight = width, height
- if self.variableDimension == 0:
- subWidth = want
- else:
- subHeight = want
-
- wrap = BoundedTerminalWrapper(
- terminal,
- subWidth,
- subHeight,
- widthOffset,
- heightOffset,
- )
- ch.draw(subWidth, subHeight, wrap)
- if self.variableDimension == 0:
- widthOffset += want
- else:
- heightOffset += want
-
-
-class HBox(_Box):
- variableDimension = 0
-
-class VBox(_Box):
- variableDimension = 1
-
-
-class Packer(ContainerWidget):
- def render(self, width, height, terminal):
- if not self.children:
- return
-
- root = int(len(self.children) ** 0.5 + 0.5)
- boxes = [VBox() for n in range(root)]
- for n, ch in enumerate(self.children):
- boxes[n % len(boxes)].addChild(ch)
- h = HBox()
- map(h.addChild, boxes)
- h.render(width, height, terminal)
-
-
-class Canvas(Widget):
- focused = False
-
- contents = None
-
- def __init__(self):
- Widget.__init__(self)
- self.resize(1, 1)
-
- def resize(self, width, height):
- contents = array.array('c', ' ' * width * height)
- if self.contents is not None:
- for x in range(min(width, self._width)):
- for y in range(min(height, self._height)):
- contents[width * y + x] = self[x, y]
- self.contents = contents
- self._width = width
- self._height = height
- if self.x >= width:
- self.x = width - 1
- if self.y >= height:
- self.y = height - 1
-
- def __getitem__(self, (x, y)):
- return self.contents[(self._width * y) + x]
-
- def __setitem__(self, (x, y), value):
- self.contents[(self._width * y) + x] = value
-
- def clear(self):
- self.contents = array.array('c', ' ' * len(self.contents))
-
- def render(self, width, height, terminal):
- if not width or not height:
- return
-
- if width != self._width or height != self._height:
- self.resize(width, height)
- for i in range(height):
- terminal.cursorPosition(0, i)
- terminal.write(''.join(self.contents[self._width * i:self._width * i + self._width])[:width])
-
-
-def horizontalLine(terminal, y, left, right):
- terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
- terminal.cursorPosition(left, y)
- terminal.write(chr(0161) * (right - left))
- terminal.selectCharacterSet(insults.CS_US, insults.G0)
-
-def verticalLine(terminal, x, top, bottom):
- terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
- for n in xrange(top, bottom):
- terminal.cursorPosition(x, n)
- terminal.write(chr(0170))
- terminal.selectCharacterSet(insults.CS_US, insults.G0)
-
-
-def rectangle(terminal, (top, left), (width, height)):
- terminal.selectCharacterSet(insults.CS_DRAWING, insults.G0)
-
- terminal.cursorPosition(top, left)
- terminal.write(chr(0154))
- terminal.write(chr(0161) * (width - 2))
- terminal.write(chr(0153))
- for n in range(height - 2):
- terminal.cursorPosition(left, top + n + 1)
- terminal.write(chr(0170))
- terminal.cursorForward(width - 2)
- terminal.write(chr(0170))
- terminal.cursorPosition(0, top + height - 1)
- terminal.write(chr(0155))
- terminal.write(chr(0161) * (width - 2))
- terminal.write(chr(0152))
-
- terminal.selectCharacterSet(insults.CS_US, insults.G0)
-
-class Border(Widget):
- def __init__(self, containee):
- Widget.__init__(self)
- self.containee = containee
- self.containee.parent = self
-
- def focusReceived(self):
- return self.containee.focusReceived()
-
- def focusLost(self):
- return self.containee.focusLost()
-
- def keystrokeReceived(self, keyID, modifier):
- return self.containee.keystrokeReceived(keyID, modifier)
-
- def sizeHint(self):
- hint = self.containee.sizeHint()
- if hint is None:
- hint = (None, None)
- if hint[0] is None:
- x = None
- else:
- x = hint[0] + 2
- if hint[1] is None:
- y = None
- else:
- y = hint[1] + 2
- return x, y
-
- def filthy(self):
- self.containee.filthy()
- Widget.filthy(self)
-
- def render(self, width, height, terminal):
- if self.containee.focused:
- terminal.write('\x1b[31m')
- rectangle(terminal, (0, 0), (width, height))
- terminal.write('\x1b[0m')
- wrap = BoundedTerminalWrapper(terminal, width - 2, height - 2, 1, 1)
- self.containee.draw(width - 2, height - 2, wrap)
-
-
-class Button(Widget):
- def __init__(self, label, onPress):
- Widget.__init__(self)
- self.label = label
- self.onPress = onPress
-
- def sizeHint(self):
- return len(self.label), 1
-
- def characterReceived(self, keyID, modifier):
- if keyID == '\r':
- self.onPress()
-
- def render(self, width, height, terminal):
- terminal.cursorPosition(0, 0)
- if self.focused:
- terminal.write('\x1b[1m' + self.label + '\x1b[0m')
- else:
- terminal.write(self.label)
-
-class TextInput(Widget):
- def __init__(self, maxwidth, onSubmit):
- Widget.__init__(self)
- self.onSubmit = onSubmit
- self.maxwidth = maxwidth
- self.buffer = ''
- self.cursor = 0
-
- def setText(self, text):
- self.buffer = text[:self.maxwidth]
- self.cursor = len(self.buffer)
- self.repaint()
-
- def func_LEFT_ARROW(self, modifier):
- if self.cursor > 0:
- self.cursor -= 1
- self.repaint()
-
- def func_RIGHT_ARROW(self, modifier):
- if self.cursor < len(self.buffer):
- self.cursor += 1
- self.repaint()
-
- def backspaceReceived(self):
- if self.cursor > 0:
- self.buffer = self.buffer[:self.cursor - 1] + self.buffer[self.cursor:]
- self.cursor -= 1
- self.repaint()
-
- def characterReceived(self, keyID, modifier):
- if keyID == '\r':
- self.onSubmit(self.buffer)
- else:
- if len(self.buffer) < self.maxwidth:
- self.buffer = self.buffer[:self.cursor] + keyID + self.buffer[self.cursor:]
- self.cursor += 1
- self.repaint()
-
- def sizeHint(self):
- return self.maxwidth + 1, 1
-
- def render(self, width, height, terminal):
- currentText = self._renderText()
- terminal.cursorPosition(0, 0)
- if self.focused:
- terminal.write(currentText[:self.cursor])
- cursor(terminal, currentText[self.cursor:self.cursor+1] or ' ')
- terminal.write(currentText[self.cursor+1:])
- terminal.write(' ' * (self.maxwidth - len(currentText) + 1))
- else:
- more = self.maxwidth - len(currentText)
- terminal.write(currentText + '_' * more)
-
- def _renderText(self):
- return self.buffer
-
-class PasswordInput(TextInput):
- def _renderText(self):
- return '*' * len(self.buffer)
-
-class TextOutput(Widget):
- text = ''
-
- def __init__(self, size=None):
- Widget.__init__(self)
- self.size = size
-
- def sizeHint(self):
- return self.size
-
- def render(self, width, height, terminal):
- terminal.cursorPosition(0, 0)
- text = self.text[:width]
- terminal.write(text + ' ' * (width - len(text)))
-
- def setText(self, text):
- self.text = text
- self.repaint()
-
- def focusReceived(self):
- raise YieldFocus()
-
-class TextOutputArea(TextOutput):
- WRAP, TRUNCATE = range(2)
-
- def __init__(self, size=None, longLines=WRAP):
- TextOutput.__init__(self, size)
- self.longLines = longLines
-
- def render(self, width, height, terminal):
- n = 0
- inputLines = self.text.splitlines()
- outputLines = []
- while inputLines:
- if self.longLines == self.WRAP:
- wrappedLines = tptext.greedyWrap(inputLines.pop(0), width)
- outputLines.extend(wrappedLines or [''])
- else:
- outputLines.append(inputLines.pop(0)[:width])
- if len(outputLines) >= height:
- break
- for n, L in enumerate(outputLines[:height]):
- terminal.cursorPosition(0, n)
- terminal.write(L)
-
-class Viewport(Widget):
- _xOffset = 0
- _yOffset = 0
-
- def xOffset():
- def get(self):
- return self._xOffset
- def set(self, value):
- if self._xOffset != value:
- self._xOffset = value
- self.repaint()
- return get, set
- xOffset = property(*xOffset())
-
- def yOffset():
- def get(self):
- return self._yOffset
- def set(self, value):
- if self._yOffset != value:
- self._yOffset = value
- self.repaint()
- return get, set
- yOffset = property(*yOffset())
-
- _width = 160
- _height = 24
-
- def __init__(self, containee):
- Widget.__init__(self)
- self.containee = containee
- self.containee.parent = self
-
- self._buf = helper.TerminalBuffer()
- self._buf.width = self._width
- self._buf.height = self._height
- self._buf.connectionMade()
-
- def filthy(self):
- self.containee.filthy()
- Widget.filthy(self)
-
- def render(self, width, height, terminal):
- self.containee.draw(self._width, self._height, self._buf)
-
- # XXX /Lame/
- for y, line in enumerate(self._buf.lines[self._yOffset:self._yOffset + height]):
- terminal.cursorPosition(0, y)
- n = 0
- for n, (ch, attr) in enumerate(line[self._xOffset:self._xOffset + width]):
- if ch is self._buf.void:
- ch = ' '
- terminal.write(ch)
- if n < width:
- terminal.write(' ' * (width - n - 1))
-
-
-class _Scrollbar(Widget):
- def __init__(self, onScroll):
- Widget.__init__(self)
- self.onScroll = onScroll
- self.percent = 0.0
-
- def smaller(self):
- self.percent = min(1.0, max(0.0, self.onScroll(-1)))
- self.repaint()
-
- def bigger(self):
- self.percent = min(1.0, max(0.0, self.onScroll(+1)))
- self.repaint()
-
-
-class HorizontalScrollbar(_Scrollbar):
- def sizeHint(self):
- return (None, 1)
-
- def func_LEFT_ARROW(self, modifier):
- self.smaller()
-
- def func_RIGHT_ARROW(self, modifier):
- self.bigger()
-
- _left = u'\N{BLACK LEFT-POINTING TRIANGLE}'
- _right = u'\N{BLACK RIGHT-POINTING TRIANGLE}'
- _bar = u'\N{LIGHT SHADE}'
- _slider = u'\N{DARK SHADE}'
- def render(self, width, height, terminal):
- terminal.cursorPosition(0, 0)
- n = width - 3
- before = int(n * self.percent)
- after = n - before
- me = self._left + (self._bar * before) + self._slider + (self._bar * after) + self._right
- terminal.write(me.encode('utf-8'))
-
-
-class VerticalScrollbar(_Scrollbar):
- def sizeHint(self):
- return (1, None)
-
- def func_UP_ARROW(self, modifier):
- self.smaller()
-
- def func_DOWN_ARROW(self, modifier):
- self.bigger()
-
- _up = u'\N{BLACK UP-POINTING TRIANGLE}'
- _down = u'\N{BLACK DOWN-POINTING TRIANGLE}'
- _bar = u'\N{LIGHT SHADE}'
- _slider = u'\N{DARK SHADE}'
- def render(self, width, height, terminal):
- terminal.cursorPosition(0, 0)
- knob = int(self.percent * (height - 2))
- terminal.write(self._up.encode('utf-8'))
- for i in xrange(1, height - 1):
- terminal.cursorPosition(0, i)
- if i != (knob + 1):
- terminal.write(self._bar.encode('utf-8'))
- else:
- terminal.write(self._slider.encode('utf-8'))
- terminal.cursorPosition(0, height - 1)
- terminal.write(self._down.encode('utf-8'))
-
-
-class ScrolledArea(Widget):
- """
- A L{ScrolledArea} contains another widget wrapped in a viewport and
- vertical and horizontal scrollbars for moving the viewport around.
- """
- def __init__(self, containee):
- Widget.__init__(self)
- self._viewport = Viewport(containee)
- self._horiz = HorizontalScrollbar(self._horizScroll)
- self._vert = VerticalScrollbar(self._vertScroll)
-
- for w in self._viewport, self._horiz, self._vert:
- w.parent = self
-
- def _horizScroll(self, n):
- self._viewport.xOffset += n
- self._viewport.xOffset = max(0, self._viewport.xOffset)
- return self._viewport.xOffset / 25.0
-
- def _vertScroll(self, n):
- self._viewport.yOffset += n
- self._viewport.yOffset = max(0, self._viewport.yOffset)
- return self._viewport.yOffset / 25.0
-
- def func_UP_ARROW(self, modifier):
- self._vert.smaller()
-
- def func_DOWN_ARROW(self, modifier):
- self._vert.bigger()
-
- def func_LEFT_ARROW(self, modifier):
- self._horiz.smaller()
-
- def func_RIGHT_ARROW(self, modifier):
- self._horiz.bigger()
-
- def filthy(self):
- self._viewport.filthy()
- self._horiz.filthy()
- self._vert.filthy()
- Widget.filthy(self)
-
- def render(self, width, height, terminal):
- wrapper = BoundedTerminalWrapper(terminal, width - 2, height - 2, 1, 1)
- self._viewport.draw(width - 2, height - 2, wrapper)
- if self.focused:
- terminal.write('\x1b[31m')
- horizontalLine(terminal, 0, 1, width - 1)
- verticalLine(terminal, 0, 1, height - 1)
- self._vert.draw(1, height - 1, BoundedTerminalWrapper(terminal, 1, height - 1, width - 1, 0))
- self._horiz.draw(width, 1, BoundedTerminalWrapper(terminal, width, 1, 0, height - 1))
- terminal.write('\x1b[0m')
-
-def cursor(terminal, ch):
- terminal.saveCursor()
- terminal.selectGraphicRendition(str(insults.REVERSE_VIDEO))
- terminal.write(ch)
- terminal.restoreCursor()
- terminal.cursorForward()
-
-class Selection(Widget):
- # Index into the sequence
- focusedIndex = 0
-
- # Offset into the displayed subset of the sequence
- renderOffset = 0
-
- def __init__(self, sequence, onSelect, minVisible=None):
- Widget.__init__(self)
- self.sequence = sequence
- self.onSelect = onSelect
- self.minVisible = minVisible
- if minVisible is not None:
- self._width = max(map(len, self.sequence))
-
- def sizeHint(self):
- if self.minVisible is not None:
- return self._width, self.minVisible
-
- def func_UP_ARROW(self, modifier):
- if self.focusedIndex > 0:
- self.focusedIndex -= 1
- if self.renderOffset > 0:
- self.renderOffset -= 1
- self.repaint()
-
- def func_PGUP(self, modifier):
- if self.renderOffset != 0:
- self.focusedIndex -= self.renderOffset
- self.renderOffset = 0
- else:
- self.focusedIndex = max(0, self.focusedIndex - self.height)
- self.repaint()
-
- def func_DOWN_ARROW(self, modifier):
- if self.focusedIndex < len(self.sequence) - 1:
- self.focusedIndex += 1
- if self.renderOffset < self.height - 1:
- self.renderOffset += 1
- self.repaint()
-
-
- def func_PGDN(self, modifier):
- if self.renderOffset != self.height - 1:
- change = self.height - self.renderOffset - 1
- if change + self.focusedIndex >= len(self.sequence):
- change = len(self.sequence) - self.focusedIndex - 1
- self.focusedIndex += change
- self.renderOffset = self.height - 1
- else:
- self.focusedIndex = min(len(self.sequence) - 1, self.focusedIndex + self.height)
- self.repaint()
-
- def characterReceived(self, keyID, modifier):
- if keyID == '\r':
- self.onSelect(self.sequence[self.focusedIndex])
-
- def render(self, width, height, terminal):
- self.height = height
- start = self.focusedIndex - self.renderOffset
- if start > len(self.sequence) - height:
- start = max(0, len(self.sequence) - height)
-
- elements = self.sequence[start:start+height]
-
- for n, ele in enumerate(elements):
- terminal.cursorPosition(0, n)
- if n == self.renderOffset:
- terminal.saveCursor()
- if self.focused:
- modes = str(insults.REVERSE_VIDEO), str(insults.BOLD)
- else:
- modes = str(insults.REVERSE_VIDEO),
- terminal.selectGraphicRendition(*modes)
- text = ele[:width]
- terminal.write(text + (' ' * (width - len(text))))
- if n == self.renderOffset:
- terminal.restoreCursor()
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/interfaces.py b/Darwin/lib/python2.7/site-packages/twisted/conch/interfaces.py
deleted file mode 100644
index 3eb0217..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/interfaces.py
+++ /dev/null
@@ -1,408 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-This module contains interfaces defined for the L{twisted.conch} package.
-"""
-
-from zope.interface import Interface, Attribute
-
-class IConchUser(Interface):
- """
- A user who has been authenticated to Cred through Conch. This is
- the interface between the SSH connection and the user.
- """
-
- conn = Attribute('The SSHConnection object for this user.')
-
- def lookupChannel(channelType, windowSize, maxPacket, data):
- """
- The other side requested a channel of some sort.
- channelType is the type of channel being requested,
- windowSize is the initial size of the remote window,
- maxPacket is the largest packet we should send,
- data is any other packet data (often nothing).
-
- We return a subclass of L{SSHChannel}. If
- an appropriate channel can not be found, an exception will be
- raised. If a L{ConchError} is raised, the .value
- will be the message, and the .data will be the error code.
-
- @type channelType: C{str}
- @type windowSize: C{int}
- @type maxPacket: C{int}
- @type data: C{str}
- @rtype: subclass of L{SSHChannel}/C{tuple}
- """
-
- def lookupSubsystem(subsystem, data):
- """
- The other side requested a subsystem.
- subsystem is the name of the subsystem being requested.
- data is any other packet data (often nothing).
-
- We return a L{Protocol}.
- """
-
- def gotGlobalRequest(requestType, data):
- """
- A global request was sent from the other side.
-
- By default, this dispatches to a method 'channel_channelType' with any
- non-alphanumerics in the channelType replace with _'s. If it cannot
- find a suitable method, it returns an OPEN_UNKNOWN_CHANNEL_TYPE error.
- The method is called with arguments of windowSize, maxPacket, data.
- """
-
-class ISession(Interface):
-
- def getPty(term, windowSize, modes):
- """
- Get a psuedo-terminal for use by a shell or command.
-
- If a psuedo-terminal is not available, or the request otherwise
- fails, raise an exception.
- """
-
- def openShell(proto):
- """
- Open a shell and connect it to proto.
-
- @param proto: a L{ProcessProtocol} instance.
- """
-
- def execCommand(proto, command):
- """
- Execute a command.
-
- @param proto: a L{ProcessProtocol} instance.
- """
-
- def windowChanged(newWindowSize):
- """
- Called when the size of the remote screen has changed.
- """
-
- def eofReceived():
- """
- Called when the other side has indicated no more data will be sent.
- """
-
- def closed():
- """
- Called when the session is closed.
- """
-
-
-class ISFTPServer(Interface):
- """
- SFTP subsystem for server-side communication.
-
- Each method should check to verify that the user has permission for
- their actions.
- """
-
- avatar = Attribute(
- """
- The avatar returned by the Realm that we are authenticated with,
- and represents the logged-in user.
- """)
-
- def gotVersion(otherVersion, extData):
- """
- Called when the client sends their version info.
-
- otherVersion is an integer representing the version of the SFTP
- protocol they are claiming.
- extData is a dictionary of extended_name : extended_data items.
- These items are sent by the client to indicate additional features.
-
- This method should return a dictionary of extended_name : extended_data
- items. These items are the additional features (if any) supported
- by the server.
- """
- return {}
-
- def openFile(filename, flags, attrs):
- """
- Called when the clients asks to open a file.
-
- @param filename: a string representing the file to open.
-
- @param flags: an integer of the flags to open the file with, ORed together.
- The flags and their values are listed at the bottom of this file.
-
- @param attrs: a list of attributes to open the file with. It is a
- dictionary, consisting of 0 or more keys. The possible keys are::
-
- size: the size of the file in bytes
- uid: the user ID of the file as an integer
- gid: the group ID of the file as an integer
- permissions: the permissions of the file with as an integer.
- the bit representation of this field is defined by POSIX.
- atime: the access time of the file as seconds since the epoch.
- mtime: the modification time of the file as seconds since the epoch.
- ext_*: extended attributes. The server is not required to
- understand this, but it may.
-
- NOTE: there is no way to indicate text or binary files. it is up
- to the SFTP client to deal with this.
-
- This method returns an object that meets the ISFTPFile interface.
- Alternatively, it can return a L{Deferred} that will be called back
- with the object.
- """
-
- def removeFile(filename):
- """
- Remove the given file.
-
- This method returns when the remove succeeds, or a Deferred that is
- called back when it succeeds.
-
- @param filename: the name of the file as a string.
- """
-
- def renameFile(oldpath, newpath):
- """
- Rename the given file.
-
- This method returns when the rename succeeds, or a L{Deferred} that is
- called back when it succeeds. If the rename fails, C{renameFile} will
- raise an implementation-dependent exception.
-
- @param oldpath: the current location of the file.
- @param newpath: the new file name.
- """
-
- def makeDirectory(path, attrs):
- """
- Make a directory.
-
- This method returns when the directory is created, or a Deferred that
- is called back when it is created.
-
- @param path: the name of the directory to create as a string.
- @param attrs: a dictionary of attributes to create the directory with.
- Its meaning is the same as the attrs in the L{openFile} method.
- """
-
- def removeDirectory(path):
- """
- Remove a directory (non-recursively)
-
- It is an error to remove a directory that has files or directories in
- it.
-
- This method returns when the directory is removed, or a Deferred that
- is called back when it is removed.
-
- @param path: the directory to remove.
- """
-
- def openDirectory(path):
- """
- Open a directory for scanning.
-
- This method returns an iterable object that has a close() method,
- or a Deferred that is called back with same.
-
- The close() method is called when the client is finished reading
- from the directory. At this point, the iterable will no longer
- be used.
-
- The iterable should return triples of the form (filename,
- longname, attrs) or Deferreds that return the same. The
- sequence must support __getitem__, but otherwise may be any
- 'sequence-like' object.
-
- filename is the name of the file relative to the directory.
- logname is an expanded format of the filename. The recommended format
- is:
- -rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer
- 1234567890 123 12345678 12345678 12345678 123456789012
-
- The first line is sample output, the second is the length of the field.
- The fields are: permissions, link count, user owner, group owner,
- size in bytes, modification time.
-
- attrs is a dictionary in the format of the attrs argument to openFile.
-
- @param path: the directory to open.
- """
-
- def getAttrs(path, followLinks):
- """
- Return the attributes for the given path.
-
- This method returns a dictionary in the same format as the attrs
- argument to openFile or a Deferred that is called back with same.
-
- @param path: the path to return attributes for as a string.
- @param followLinks: a boolean. If it is True, follow symbolic links
- and return attributes for the real path at the base. If it is False,
- return attributes for the specified path.
- """
-
- def setAttrs(path, attrs):
- """
- Set the attributes for the path.
-
- This method returns when the attributes are set or a Deferred that is
- called back when they are.
-
- @param path: the path to set attributes for as a string.
- @param attrs: a dictionary in the same format as the attrs argument to
- L{openFile}.
- """
-
- def readLink(path):
- """
- Find the root of a set of symbolic links.
-
- This method returns the target of the link, or a Deferred that
- returns the same.
-
- @param path: the path of the symlink to read.
- """
-
- def makeLink(linkPath, targetPath):
- """
- Create a symbolic link.
-
- This method returns when the link is made, or a Deferred that
- returns the same.
-
- @param linkPath: the pathname of the symlink as a string.
- @param targetPath: the path of the target of the link as a string.
- """
-
- def realPath(path):
- """
- Convert any path to an absolute path.
-
- This method returns the absolute path as a string, or a Deferred
- that returns the same.
-
- @param path: the path to convert as a string.
- """
-
- def extendedRequest(extendedName, extendedData):
- """
- This is the extension mechanism for SFTP. The other side can send us
- arbitrary requests.
-
- If we don't implement the request given by extendedName, raise
- NotImplementedError.
-
- The return value is a string, or a Deferred that will be called
- back with a string.
-
- @param extendedName: the name of the request as a string.
- @param extendedData: the data the other side sent with the request,
- as a string.
- """
-
-
-
-class IKnownHostEntry(Interface):
- """
- A L{IKnownHostEntry} is an entry in an OpenSSH-formatted C{known_hosts}
- file.
-
- @since: 8.2
- """
-
- def matchesKey(key):
- """
- Return True if this entry matches the given Key object, False
- otherwise.
-
- @param key: The key object to match against.
- @type key: L{twisted.conch.ssh.Key}
- """
-
-
- def matchesHost(hostname):
- """
- Return True if this entry matches the given hostname, False otherwise.
-
- Note that this does no name resolution; if you want to match an IP
- address, you have to resolve it yourself, and pass it in as a dotted
- quad string.
-
- @param key: The hostname to match against.
- @type key: L{str}
- """
-
-
- def toString():
- """
- @return: a serialized string representation of this entry, suitable for
- inclusion in a known_hosts file. (Newline not included.)
-
- @rtype: L{str}
- """
-
-
-
-class ISFTPFile(Interface):
- """
- This represents an open file on the server. An object adhering to this
- interface should be returned from L{openFile}().
- """
-
- def close():
- """
- Close the file.
-
- This method returns nothing if the close succeeds immediately, or a
- Deferred that is called back when the close succeeds.
- """
-
- def readChunk(offset, length):
- """
- Read from the file.
-
- If EOF is reached before any data is read, raise EOFError.
-
- This method returns the data as a string, or a Deferred that is
- called back with same.
-
- @param offset: an integer that is the index to start from in the file.
- @param length: the maximum length of data to return. The actual amount
- returned may less than this. For normal disk files, however,
- this should read the requested number (up to the end of the file).
- """
-
- def writeChunk(offset, data):
- """
- Write to the file.
-
- This method returns when the write completes, or a Deferred that is
- called when it completes.
-
- @param offset: an integer that is the index to start from in the file.
- @param data: a string that is the data to write.
- """
-
- def getAttrs():
- """
- Return the attributes for the file.
-
- This method returns a dictionary in the same format as the attrs
- argument to L{openFile} or a L{Deferred} that is called back with same.
- """
-
- def setAttrs(attrs):
- """
- Set the attributes for the file.
-
- This method returns when the attributes are set or a Deferred that is
- called back when they are.
-
- @param attrs: a dictionary in the same format as the attrs argument to
- L{openFile}.
- """
-
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ls.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ls.py
deleted file mode 100644
index ab44f85..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ls.py
+++ /dev/null
@@ -1,75 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_cftp -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-import array
-import stat
-
-from time import time, strftime, localtime
-
-# locale-independent month names to use instead of strftime's
-_MONTH_NAMES = dict(zip(
- range(1, 13),
- "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()))
-
-
-def lsLine(name, s):
- """
- Build an 'ls' line for a file ('file' in its generic sense, it
- can be of any type).
- """
- mode = s.st_mode
- perms = array.array('c', '-'*10)
- ft = stat.S_IFMT(mode)
- if stat.S_ISDIR(ft): perms[0] = 'd'
- elif stat.S_ISCHR(ft): perms[0] = 'c'
- elif stat.S_ISBLK(ft): perms[0] = 'b'
- elif stat.S_ISREG(ft): perms[0] = '-'
- elif stat.S_ISFIFO(ft): perms[0] = 'f'
- elif stat.S_ISLNK(ft): perms[0] = 'l'
- elif stat.S_ISSOCK(ft): perms[0] = 's'
- else: perms[0] = '!'
- # user
- if mode&stat.S_IRUSR:perms[1] = 'r'
- if mode&stat.S_IWUSR:perms[2] = 'w'
- if mode&stat.S_IXUSR:perms[3] = 'x'
- # group
- if mode&stat.S_IRGRP:perms[4] = 'r'
- if mode&stat.S_IWGRP:perms[5] = 'w'
- if mode&stat.S_IXGRP:perms[6] = 'x'
- # other
- if mode&stat.S_IROTH:perms[7] = 'r'
- if mode&stat.S_IWOTH:perms[8] = 'w'
- if mode&stat.S_IXOTH:perms[9] = 'x'
- # suid/sgid
- if mode&stat.S_ISUID:
- if perms[3] == 'x': perms[3] = 's'
- else: perms[3] = 'S'
- if mode&stat.S_ISGID:
- if perms[6] == 'x': perms[6] = 's'
- else: perms[6] = 'S'
-
- lsresult = [
- perms.tostring(),
- str(s.st_nlink).rjust(5),
- ' ',
- str(s.st_uid).ljust(9),
- str(s.st_gid).ljust(9),
- str(s.st_size).rjust(8),
- ' ',
- ]
-
- # need to specify the month manually, as strftime depends on locale
- ttup = localtime(s.st_mtime)
- sixmonths = 60 * 60 * 24 * 7 * 26
- if s.st_mtime + sixmonths < time(): # last edited more than 6mo ago
- strtime = strftime("%%s %d %Y ", ttup)
- else:
- strtime = strftime("%%s %d %H:%M ", ttup)
- lsresult.append(strtime % (_MONTH_NAMES[ttup[1]],))
-
- lsresult.append(name)
- return ''.join(lsresult)
-
-
-__all__ = ['lsLine']
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/manhole.py b/Darwin/lib/python2.7/site-packages/twisted/conch/manhole.py
deleted file mode 100644
index dee6a02..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/manhole.py
+++ /dev/null
@@ -1,340 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_manhole -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Line-input oriented interactive interpreter loop.
-
-Provides classes for handling Python source input and arbitrary output
-interactively from a Twisted application. Also included is syntax coloring
-code with support for VT102 terminals, control code handling (^C, ^D, ^Q),
-and reasonable handling of Deferreds.
-
-@author: Jp Calderone
-"""
-
-import code, sys, StringIO, tokenize
-
-from twisted.conch import recvline
-
-from twisted.internet import defer
-from twisted.python.htmlizer import TokenPrinter
-
-class FileWrapper:
- """Minimal write-file-like object.
-
- Writes are translated into addOutput calls on an object passed to
- __init__. Newlines are also converted from network to local style.
- """
-
- softspace = 0
- state = 'normal'
-
- def __init__(self, o):
- self.o = o
-
- def flush(self):
- pass
-
- def write(self, data):
- self.o.addOutput(data.replace('\r\n', '\n'))
-
- def writelines(self, lines):
- self.write(''.join(lines))
-
-class ManholeInterpreter(code.InteractiveInterpreter):
- """Interactive Interpreter with special output and Deferred support.
-
- Aside from the features provided by L{code.InteractiveInterpreter}, this
- class captures sys.stdout output and redirects it to the appropriate
- location (the Manhole protocol instance). It also treats Deferreds
- which reach the top-level specially: each is formatted to the user with
- a unique identifier and a new callback and errback added to it, each of
- which will format the unique identifier and the result with which the
- Deferred fires and then pass it on to the next participant in the
- callback chain.
- """
-
- numDeferreds = 0
- def __init__(self, handler, locals=None, filename=""):
- code.InteractiveInterpreter.__init__(self, locals)
- self._pendingDeferreds = {}
- self.handler = handler
- self.filename = filename
- self.resetBuffer()
-
- def resetBuffer(self):
- """Reset the input buffer."""
- self.buffer = []
-
- def push(self, line):
- """Push a line to the interpreter.
-
- The line should not have a trailing newline; it may have
- internal newlines. The line is appended to a buffer and the
- interpreter's runsource() method is called with the
- concatenated contents of the buffer as source. If this
- indicates that the command was executed or invalid, the buffer
- is reset; otherwise, the command is incomplete, and the buffer
- is left as it was after the line was appended. The return
- value is 1 if more input is required, 0 if the line was dealt
- with in some way (this is the same as runsource()).
-
- """
- self.buffer.append(line)
- source = "\n".join(self.buffer)
- more = self.runsource(source, self.filename)
- if not more:
- self.resetBuffer()
- return more
-
- def runcode(self, *a, **kw):
- orighook, sys.displayhook = sys.displayhook, self.displayhook
- try:
- origout, sys.stdout = sys.stdout, FileWrapper(self.handler)
- try:
- code.InteractiveInterpreter.runcode(self, *a, **kw)
- finally:
- sys.stdout = origout
- finally:
- sys.displayhook = orighook
-
- def displayhook(self, obj):
- self.locals['_'] = obj
- if isinstance(obj, defer.Deferred):
- # XXX Ick, where is my "hasFired()" interface?
- if hasattr(obj, "result"):
- self.write(repr(obj))
- elif id(obj) in self._pendingDeferreds:
- self.write("" % (self._pendingDeferreds[id(obj)][0],))
- else:
- d = self._pendingDeferreds
- k = self.numDeferreds
- d[id(obj)] = (k, obj)
- self.numDeferreds += 1
- obj.addCallbacks(self._cbDisplayDeferred, self._ebDisplayDeferred,
- callbackArgs=(k, obj), errbackArgs=(k, obj))
- self.write("" % (k,))
- elif obj is not None:
- self.write(repr(obj))
-
- def _cbDisplayDeferred(self, result, k, obj):
- self.write("Deferred #%d called back: %r" % (k, result), True)
- del self._pendingDeferreds[id(obj)]
- return result
-
- def _ebDisplayDeferred(self, failure, k, obj):
- self.write("Deferred #%d failed: %r" % (k, failure.getErrorMessage()), True)
- del self._pendingDeferreds[id(obj)]
- return failure
-
- def write(self, data, async=False):
- self.handler.addOutput(data, async)
-
-CTRL_C = '\x03'
-CTRL_D = '\x04'
-CTRL_BACKSLASH = '\x1c'
-CTRL_L = '\x0c'
-CTRL_A = '\x01'
-CTRL_E = '\x05'
-
-class Manhole(recvline.HistoricRecvLine):
- """Mediator between a fancy line source and an interactive interpreter.
-
- This accepts lines from its transport and passes them on to a
- L{ManholeInterpreter}. Control commands (^C, ^D, ^\) are also handled
- with something approximating their normal terminal-mode behavior. It
- can optionally be constructed with a dict which will be used as the
- local namespace for any code executed.
- """
-
- namespace = None
-
- def __init__(self, namespace=None):
- recvline.HistoricRecvLine.__init__(self)
- if namespace is not None:
- self.namespace = namespace.copy()
-
- def connectionMade(self):
- recvline.HistoricRecvLine.connectionMade(self)
- self.interpreter = ManholeInterpreter(self, self.namespace)
- self.keyHandlers[CTRL_C] = self.handle_INT
- self.keyHandlers[CTRL_D] = self.handle_EOF
- self.keyHandlers[CTRL_L] = self.handle_FF
- self.keyHandlers[CTRL_A] = self.handle_HOME
- self.keyHandlers[CTRL_E] = self.handle_END
- self.keyHandlers[CTRL_BACKSLASH] = self.handle_QUIT
-
-
- def handle_INT(self):
- """
- Handle ^C as an interrupt keystroke by resetting the current input
- variables to their initial state.
- """
- self.pn = 0
- self.lineBuffer = []
- self.lineBufferIndex = 0
- self.interpreter.resetBuffer()
-
- self.terminal.nextLine()
- self.terminal.write("KeyboardInterrupt")
- self.terminal.nextLine()
- self.terminal.write(self.ps[self.pn])
-
-
- def handle_EOF(self):
- if self.lineBuffer:
- self.terminal.write('\a')
- else:
- self.handle_QUIT()
-
-
- def handle_FF(self):
- """
- Handle a 'form feed' byte - generally used to request a screen
- refresh/redraw.
- """
- self.terminal.eraseDisplay()
- self.terminal.cursorHome()
- self.drawInputLine()
-
-
- def handle_QUIT(self):
- self.terminal.loseConnection()
-
-
- def _needsNewline(self):
- w = self.terminal.lastWrite
- return not w.endswith('\n') and not w.endswith('\x1bE')
-
- def addOutput(self, bytes, async=False):
- if async:
- self.terminal.eraseLine()
- self.terminal.cursorBackward(len(self.lineBuffer) + len(self.ps[self.pn]))
-
- self.terminal.write(bytes)
-
- if async:
- if self._needsNewline():
- self.terminal.nextLine()
-
- self.terminal.write(self.ps[self.pn])
-
- if self.lineBuffer:
- oldBuffer = self.lineBuffer
- self.lineBuffer = []
- self.lineBufferIndex = 0
-
- self._deliverBuffer(oldBuffer)
-
- def lineReceived(self, line):
- more = self.interpreter.push(line)
- self.pn = bool(more)
- if self._needsNewline():
- self.terminal.nextLine()
- self.terminal.write(self.ps[self.pn])
-
-class VT102Writer:
- """Colorizer for Python tokens.
-
- A series of tokens are written to instances of this object. Each is
- colored in a particular way. The final line of the result of this is
- generally added to the output.
- """
-
- typeToColor = {
- 'identifier': '\x1b[31m',
- 'keyword': '\x1b[32m',
- 'parameter': '\x1b[33m',
- 'variable': '\x1b[1;33m',
- 'string': '\x1b[35m',
- 'number': '\x1b[36m',
- 'op': '\x1b[37m'}
-
- normalColor = '\x1b[0m'
-
- def __init__(self):
- self.written = []
-
- def color(self, type):
- r = self.typeToColor.get(type, '')
- return r
-
- def write(self, token, type=None):
- if token and token != '\r':
- c = self.color(type)
- if c:
- self.written.append(c)
- self.written.append(token)
- if c:
- self.written.append(self.normalColor)
-
- def __str__(self):
- s = ''.join(self.written)
- return s.strip('\n').splitlines()[-1]
-
-def lastColorizedLine(source):
- """Tokenize and colorize the given Python source.
-
- Returns a VT102-format colorized version of the last line of C{source}.
- """
- w = VT102Writer()
- p = TokenPrinter(w.write).printtoken
- s = StringIO.StringIO(source)
-
- tokenize.tokenize(s.readline, p)
-
- return str(w)
-
-class ColoredManhole(Manhole):
- """A REPL which syntax colors input as users type it.
- """
-
- def getSource(self):
- """Return a string containing the currently entered source.
-
- This is only the code which will be considered for execution
- next.
- """
- return ('\n'.join(self.interpreter.buffer) +
- '\n' +
- ''.join(self.lineBuffer))
-
-
- def characterReceived(self, ch, moreCharactersComing):
- if self.mode == 'insert':
- self.lineBuffer.insert(self.lineBufferIndex, ch)
- else:
- self.lineBuffer[self.lineBufferIndex:self.lineBufferIndex+1] = [ch]
- self.lineBufferIndex += 1
-
- if moreCharactersComing:
- # Skip it all, we'll get called with another character in
- # like 2 femtoseconds.
- return
-
- if ch == ' ':
- # Don't bother to try to color whitespace
- self.terminal.write(ch)
- return
-
- source = self.getSource()
-
- # Try to write some junk
- try:
- coloredLine = lastColorizedLine(source)
- except tokenize.TokenError:
- # We couldn't do it. Strange. Oh well, just add the character.
- self.terminal.write(ch)
- else:
- # Success! Clear the source on this line.
- self.terminal.eraseLine()
- self.terminal.cursorBackward(len(self.lineBuffer) + len(self.ps[self.pn]) - 1)
-
- # And write a new, colorized one.
- self.terminal.write(self.ps[self.pn] + coloredLine)
-
- # And move the cursor to where it belongs
- n = len(self.lineBuffer) - self.lineBufferIndex
- if n:
- self.terminal.cursorBackward(n)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/manhole_ssh.py b/Darwin/lib/python2.7/site-packages/twisted/conch/manhole_ssh.py
deleted file mode 100644
index a2297ef..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/manhole_ssh.py
+++ /dev/null
@@ -1,146 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_manhole -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-insults/SSH integration support.
-
-@author: Jp Calderone
-"""
-
-from zope.interface import implements
-
-from twisted.conch import avatar, interfaces as iconch, error as econch
-from twisted.conch.ssh import factory, keys, session
-from twisted.cred import credentials, checkers, portal
-from twisted.python import components
-
-from twisted.conch.insults import insults
-
-class _Glue:
- """A feeble class for making one attribute look like another.
-
- This should be replaced with a real class at some point, probably.
- Try not to write new code that uses it.
- """
- def __init__(self, **kw):
- self.__dict__.update(kw)
-
- def __getattr__(self, name):
- raise AttributeError(self.name, "has no attribute", name)
-
-class TerminalSessionTransport:
- def __init__(self, proto, chainedProtocol, avatar, width, height):
- self.proto = proto
- self.avatar = avatar
- self.chainedProtocol = chainedProtocol
-
- session = self.proto.session
-
- self.proto.makeConnection(
- _Glue(write=self.chainedProtocol.dataReceived,
- loseConnection=lambda: avatar.conn.sendClose(session),
- name="SSH Proto Transport"))
-
- def loseConnection():
- self.proto.loseConnection()
-
- self.chainedProtocol.makeConnection(
- _Glue(write=self.proto.write,
- loseConnection=loseConnection,
- name="Chained Proto Transport"))
-
- # XXX TODO
- # chainedProtocol is supposed to be an ITerminalTransport,
- # maybe. That means perhaps its terminalProtocol attribute is
- # an ITerminalProtocol, it could be. So calling terminalSize
- # on that should do the right thing But it'd be nice to clean
- # this bit up.
- self.chainedProtocol.terminalProtocol.terminalSize(width, height)
-
-class TerminalSession(components.Adapter):
- implements(iconch.ISession)
-
- transportFactory = TerminalSessionTransport
- chainedProtocolFactory = insults.ServerProtocol
-
- def getPty(self, term, windowSize, attrs):
- self.height, self.width = windowSize[:2]
-
- def openShell(self, proto):
- self.transportFactory(
- proto, self.chainedProtocolFactory(),
- iconch.IConchUser(self.original),
- self.width, self.height)
-
- def execCommand(self, proto, cmd):
- raise econch.ConchError("Cannot execute commands")
-
- def closed(self):
- pass
-
-class TerminalUser(avatar.ConchUser, components.Adapter):
- def __init__(self, original, avatarId):
- components.Adapter.__init__(self, original)
- avatar.ConchUser.__init__(self)
- self.channelLookup['session'] = session.SSHSession
-
-class TerminalRealm:
- userFactory = TerminalUser
- sessionFactory = TerminalSession
-
- transportFactory = TerminalSessionTransport
- chainedProtocolFactory = insults.ServerProtocol
-
- def _getAvatar(self, avatarId):
- comp = components.Componentized()
- user = self.userFactory(comp, avatarId)
- sess = self.sessionFactory(comp)
-
- sess.transportFactory = self.transportFactory
- sess.chainedProtocolFactory = self.chainedProtocolFactory
-
- comp.setComponent(iconch.IConchUser, user)
- comp.setComponent(iconch.ISession, sess)
-
- return user
-
- def __init__(self, transportFactory=None):
- if transportFactory is not None:
- self.transportFactory = transportFactory
-
- def requestAvatar(self, avatarId, mind, *interfaces):
- for i in interfaces:
- if i is iconch.IConchUser:
- return (iconch.IConchUser,
- self._getAvatar(avatarId),
- lambda: None)
- raise NotImplementedError()
-
-class ConchFactory(factory.SSHFactory):
- publicKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEArzJx8OYOnJmzf4tfBEvLi8DVPrJ3/c9k2I/Az64fxjHf9imyRJbixtQhlH9lfNjUIx+4LmrJH5QNRsFporcHDKOTwTTYLh5KmRpslkYHRivcJSkbh/C+BR3utDS555mV'
-
- publicKeys = {
- 'ssh-rsa' : keys.Key.fromString(publicKey)
- }
- del publicKey
-
- privateKey = """-----BEGIN RSA PRIVATE KEY-----
-MIIByAIBAAJhAK8ycfDmDpyZs3+LXwRLy4vA1T6yd/3PZNiPwM+uH8Yx3/YpskSW
-4sbUIZR/ZXzY1CMfuC5qyR+UDUbBaaK3Bwyjk8E02C4eSpkabJZGB0Yr3CUpG4fw
-vgUd7rQ0ueeZlQIBIwJgbh+1VZfr7WftK5lu7MHtqE1S1vPWZQYE3+VUn8yJADyb
-Z4fsZaCrzW9lkIqXkE3GIY+ojdhZhkO1gbG0118sIgphwSWKRxK0mvh6ERxKqIt1
-xJEJO74EykXZV4oNJ8sjAjEA3J9r2ZghVhGN6V8DnQrTk24Td0E8hU8AcP0FVP+8
-PQm/g/aXf2QQkQT+omdHVEJrAjEAy0pL0EBH6EVS98evDCBtQw22OZT52qXlAwZ2
-gyTriKFVoqjeEjt3SZKKqXHSApP/AjBLpF99zcJJZRq2abgYlf9lv1chkrWqDHUu
-DZttmYJeEfiFBBavVYIF1dOlZT0G8jMCMBc7sOSZodFnAiryP+Qg9otSBjJ3bQML
-pSTqy7c3a2AScC/YyOwkDaICHnnD3XyjMwIxALRzl0tQEKMXs6hH8ToUdlLROCrP
-EhQ0wahUTCk1gKA4uPD6TMTChavbh4K63OvbKg==
------END RSA PRIVATE KEY-----"""
- privateKeys = {
- 'ssh-rsa' : keys.Key.fromString(privateKey)
- }
- del privateKey
-
- def __init__(self, portal):
- self.portal = portal
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/manhole_tap.py b/Darwin/lib/python2.7/site-packages/twisted/conch/manhole_tap.py
deleted file mode 100644
index 4df7c83..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/manhole_tap.py
+++ /dev/null
@@ -1,124 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-TAP plugin for creating telnet- and ssh-accessible manhole servers.
-
-@author: Jp Calderone
-"""
-
-from zope.interface import implements
-
-from twisted.internet import protocol
-from twisted.application import service, strports
-from twisted.conch.ssh import session
-from twisted.conch import interfaces as iconch
-from twisted.cred import portal, checkers
-from twisted.python import usage
-
-from twisted.conch.insults import insults
-from twisted.conch import manhole, manhole_ssh, telnet
-
-class makeTelnetProtocol:
- def __init__(self, portal):
- self.portal = portal
-
- def __call__(self):
- auth = telnet.AuthenticatingTelnetProtocol
- args = (self.portal,)
- return telnet.TelnetTransport(auth, *args)
-
-class chainedProtocolFactory:
- def __init__(self, namespace):
- self.namespace = namespace
-
- def __call__(self):
- return insults.ServerProtocol(manhole.ColoredManhole, self.namespace)
-
-class _StupidRealm:
- implements(portal.IRealm)
-
- def __init__(self, proto, *a, **kw):
- self.protocolFactory = proto
- self.protocolArgs = a
- self.protocolKwArgs = kw
-
- def requestAvatar(self, avatarId, *interfaces):
- if telnet.ITelnetProtocol in interfaces:
- return (telnet.ITelnetProtocol,
- self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs),
- lambda: None)
- raise NotImplementedError()
-
-class Options(usage.Options):
- optParameters = [
- ["telnetPort", "t", None, "strports description of the address on which to listen for telnet connections"],
- ["sshPort", "s", None, "strports description of the address on which to listen for ssh connections"],
- ["passwd", "p", "/etc/passwd", "name of a passwd(5)-format username/password file"]]
-
- def __init__(self):
- usage.Options.__init__(self)
- self['namespace'] = None
-
- def postOptions(self):
- if self['telnetPort'] is None and self['sshPort'] is None:
- raise usage.UsageError("At least one of --telnetPort and --sshPort must be specified")
-
-def makeService(options):
- """Create a manhole server service.
-
- @type options: C{dict}
- @param options: A mapping describing the configuration of
- the desired service. Recognized key/value pairs are::
-
- "telnetPort": strports description of the address on which
- to listen for telnet connections. If None,
- no telnet service will be started.
-
- "sshPort": strports description of the address on which to
- listen for ssh connections. If None, no ssh
- service will be started.
-
- "namespace": dictionary containing desired initial locals
- for manhole connections. If None, an empty
- dictionary will be used.
-
- "passwd": Name of a passwd(5)-format username/password file.
-
- @rtype: L{twisted.application.service.IService}
- @return: A manhole service.
- """
-
- svc = service.MultiService()
-
- namespace = options['namespace']
- if namespace is None:
- namespace = {}
-
- checker = checkers.FilePasswordDB(options['passwd'])
-
- if options['telnetPort']:
- telnetRealm = _StupidRealm(telnet.TelnetBootstrapProtocol,
- insults.ServerProtocol,
- manhole.ColoredManhole,
- namespace)
-
- telnetPortal = portal.Portal(telnetRealm, [checker])
-
- telnetFactory = protocol.ServerFactory()
- telnetFactory.protocol = makeTelnetProtocol(telnetPortal)
- telnetService = strports.service(options['telnetPort'],
- telnetFactory)
- telnetService.setServiceParent(svc)
-
- if options['sshPort']:
- sshRealm = manhole_ssh.TerminalRealm()
- sshRealm.chainedProtocolFactory = chainedProtocolFactory(namespace)
-
- sshPortal = portal.Portal(sshRealm, [checker])
- sshFactory = manhole_ssh.ConchFactory(sshPortal)
- sshService = strports.service(options['sshPort'],
- sshFactory)
- sshService.setServiceParent(svc)
-
- return svc
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/mixin.py b/Darwin/lib/python2.7/site-packages/twisted/conch/mixin.py
deleted file mode 100644
index 581e2ff..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/mixin.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_mixin -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Experimental optimization
-
-This module provides a single mixin class which allows protocols to
-collapse numerous small writes into a single larger one.
-
-@author: Jp Calderone
-"""
-
-from twisted.internet import reactor
-
-class BufferingMixin:
- """Mixin which adds write buffering.
- """
- _delayedWriteCall = None
- bytes = None
-
- DELAY = 0.0
-
- def schedule(self):
- return reactor.callLater(self.DELAY, self.flush)
-
- def reschedule(self, token):
- token.reset(self.DELAY)
-
- def write(self, bytes):
- """Buffer some bytes to be written soon.
-
- Every call to this function delays the real write by C{self.DELAY}
- seconds. When the delay expires, all collected bytes are written
- to the underlying transport using L{ITransport.writeSequence}.
- """
- if self._delayedWriteCall is None:
- self.bytes = []
- self._delayedWriteCall = self.schedule()
- else:
- self.reschedule(self._delayedWriteCall)
- self.bytes.append(bytes)
-
- def flush(self):
- """Flush the buffer immediately.
- """
- self._delayedWriteCall = None
- self.transport.writeSequence(self.bytes)
- self.bytes = None
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/openssh_compat/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/conch/openssh_compat/__init__.py
deleted file mode 100644
index 69d5927..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/openssh_compat/__init__.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-"""
-Support for OpenSSH configuration files.
-
-Maintainer: Paul Swartz
-"""
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/openssh_compat/factory.py b/Darwin/lib/python2.7/site-packages/twisted/conch/openssh_compat/factory.py
deleted file mode 100644
index f0ad8f7..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/openssh_compat/factory.py
+++ /dev/null
@@ -1,73 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_openssh_compat -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Factory for reading openssh configuration files: public keys, private keys, and
-moduli file.
-"""
-
-import os, errno
-
-from twisted.python import log
-from twisted.python.util import runAsEffectiveUser
-
-from twisted.conch.ssh import keys, factory, common
-from twisted.conch.openssh_compat import primes
-
-
-
-class OpenSSHFactory(factory.SSHFactory):
- dataRoot = '/usr/local/etc'
- moduliRoot = '/usr/local/etc' # for openbsd which puts moduli in a different
- # directory from keys
-
-
- def getPublicKeys(self):
- """
- Return the server public keys.
- """
- ks = {}
- for filename in os.listdir(self.dataRoot):
- if filename[:9] == 'ssh_host_' and filename[-8:]=='_key.pub':
- try:
- k = keys.Key.fromFile(
- os.path.join(self.dataRoot, filename))
- t = common.getNS(k.blob())[0]
- ks[t] = k
- except Exception, e:
- log.msg('bad public key file %s: %s' % (filename, e))
- return ks
-
-
- def getPrivateKeys(self):
- """
- Return the server private keys.
- """
- privateKeys = {}
- for filename in os.listdir(self.dataRoot):
- if filename[:9] == 'ssh_host_' and filename[-4:]=='_key':
- fullPath = os.path.join(self.dataRoot, filename)
- try:
- key = keys.Key.fromFile(fullPath)
- except IOError, e:
- if e.errno == errno.EACCES:
- # Not allowed, let's switch to root
- key = runAsEffectiveUser(0, 0, keys.Key.fromFile, fullPath)
- keyType = keys.objectType(key.keyObject)
- privateKeys[keyType] = key
- else:
- raise
- except Exception, e:
- log.msg('bad private key file %s: %s' % (filename, e))
- else:
- keyType = keys.objectType(key.keyObject)
- privateKeys[keyType] = key
- return privateKeys
-
-
- def getPrimes(self):
- try:
- return primes.parseModuliFile(self.moduliRoot+'/moduli')
- except IOError:
- return None
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/openssh_compat/primes.py b/Darwin/lib/python2.7/site-packages/twisted/conch/openssh_compat/primes.py
deleted file mode 100644
index 5d939e6..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/openssh_compat/primes.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-"""
-Parsing for the moduli file, which contains Diffie-Hellman prime groups.
-
-Maintainer: Paul Swartz
-"""
-
-def parseModuliFile(filename):
- lines = open(filename).readlines()
- primes = {}
- for l in lines:
- l = l.strip()
- if not l or l[0]=='#':
- continue
- tim, typ, tst, tri, size, gen, mod = l.split()
- size = int(size) + 1
- gen = long(gen)
- mod = long(mod, 16)
- if not primes.has_key(size):
- primes[size] = []
- primes[size].append((gen, mod))
- return primes
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/recvline.py b/Darwin/lib/python2.7/site-packages/twisted/conch/recvline.py
deleted file mode 100644
index 6c8416a..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/recvline.py
+++ /dev/null
@@ -1,329 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_recvline -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Basic line editing support.
-
-@author: Jp Calderone
-"""
-
-import string
-
-from zope.interface import implements
-
-from twisted.conch.insults import insults, helper
-
-from twisted.python import log, reflect
-
-_counters = {}
-class Logging(object):
- """Wrapper which logs attribute lookups.
-
- This was useful in debugging something, I guess. I forget what.
- It can probably be deleted or moved somewhere more appropriate.
- Nothing special going on here, really.
- """
- def __init__(self, original):
- self.original = original
- key = reflect.qual(original.__class__)
- count = _counters.get(key, 0)
- _counters[key] = count + 1
- self._logFile = file(key + '-' + str(count), 'w')
-
- def __str__(self):
- return str(super(Logging, self).__getattribute__('original'))
-
- def __repr__(self):
- return repr(super(Logging, self).__getattribute__('original'))
-
- def __getattribute__(self, name):
- original = super(Logging, self).__getattribute__('original')
- logFile = super(Logging, self).__getattribute__('_logFile')
- logFile.write(name + '\n')
- return getattr(original, name)
-
-class TransportSequence(object):
- """An L{ITerminalTransport} implementation which forwards calls to
- one or more other L{ITerminalTransport}s.
-
- This is a cheap way for servers to keep track of the state they
- expect the client to see, since all terminal manipulations can be
- send to the real client and to a terminal emulator that lives in
- the server process.
- """
- implements(insults.ITerminalTransport)
-
- for keyID in ('UP_ARROW', 'DOWN_ARROW', 'RIGHT_ARROW', 'LEFT_ARROW',
- 'HOME', 'INSERT', 'DELETE', 'END', 'PGUP', 'PGDN',
- 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9',
- 'F10', 'F11', 'F12'):
- exec '%s = object()' % (keyID,)
-
- TAB = '\t'
- BACKSPACE = '\x7f'
-
- def __init__(self, *transports):
- assert transports, "Cannot construct a TransportSequence with no transports"
- self.transports = transports
-
- for method in insults.ITerminalTransport:
- exec """\
-def %s(self, *a, **kw):
- for tpt in self.transports:
- result = tpt.%s(*a, **kw)
- return result
-""" % (method, method)
-
-class LocalTerminalBufferMixin(object):
- """A mixin for RecvLine subclasses which records the state of the terminal.
-
- This is accomplished by performing all L{ITerminalTransport} operations on both
- the transport passed to makeConnection and an instance of helper.TerminalBuffer.
-
- @ivar terminalCopy: A L{helper.TerminalBuffer} instance which efforts
- will be made to keep up to date with the actual terminal
- associated with this protocol instance.
- """
-
- def makeConnection(self, transport):
- self.terminalCopy = helper.TerminalBuffer()
- self.terminalCopy.connectionMade()
- return super(LocalTerminalBufferMixin, self).makeConnection(
- TransportSequence(transport, self.terminalCopy))
-
- def __str__(self):
- return str(self.terminalCopy)
-
-class RecvLine(insults.TerminalProtocol):
- """L{TerminalProtocol} which adds line editing features.
-
- Clients will be prompted for lines of input with all the usual
- features: character echoing, left and right arrow support for
- moving the cursor to different areas of the line buffer, backspace
- and delete for removing characters, and insert for toggling
- between typeover and insert mode. Tabs will be expanded to enough
- spaces to move the cursor to the next tabstop (every four
- characters by default). Enter causes the line buffer to be
- cleared and the line to be passed to the lineReceived() method
- which, by default, does nothing. Subclasses are responsible for
- redrawing the input prompt (this will probably change).
- """
- width = 80
- height = 24
-
- TABSTOP = 4
-
- ps = ('>>> ', '... ')
- pn = 0
- _printableChars = set(string.printable)
-
- def connectionMade(self):
- # A list containing the characters making up the current line
- self.lineBuffer = []
-
- # A zero-based (wtf else?) index into self.lineBuffer.
- # Indicates the current cursor position.
- self.lineBufferIndex = 0
-
- t = self.terminal
- # A map of keyIDs to bound instance methods.
- self.keyHandlers = {
- t.LEFT_ARROW: self.handle_LEFT,
- t.RIGHT_ARROW: self.handle_RIGHT,
- t.TAB: self.handle_TAB,
-
- # Both of these should not be necessary, but figuring out
- # which is necessary is a huge hassle.
- '\r': self.handle_RETURN,
- '\n': self.handle_RETURN,
-
- t.BACKSPACE: self.handle_BACKSPACE,
- t.DELETE: self.handle_DELETE,
- t.INSERT: self.handle_INSERT,
- t.HOME: self.handle_HOME,
- t.END: self.handle_END}
-
- self.initializeScreen()
-
- def initializeScreen(self):
- # Hmm, state sucks. Oh well.
- # For now we will just take over the whole terminal.
- self.terminal.reset()
- self.terminal.write(self.ps[self.pn])
- # XXX Note: I would prefer to default to starting in insert
- # mode, however this does not seem to actually work! I do not
- # know why. This is probably of interest to implementors
- # subclassing RecvLine.
-
- # XXX XXX Note: But the unit tests all expect the initial mode
- # to be insert right now. Fuck, there needs to be a way to
- # query the current mode or something.
- # self.setTypeoverMode()
- self.setInsertMode()
-
- def currentLineBuffer(self):
- s = ''.join(self.lineBuffer)
- return s[:self.lineBufferIndex], s[self.lineBufferIndex:]
-
- def setInsertMode(self):
- self.mode = 'insert'
- self.terminal.setModes([insults.modes.IRM])
-
- def setTypeoverMode(self):
- self.mode = 'typeover'
- self.terminal.resetModes([insults.modes.IRM])
-
- def drawInputLine(self):
- """
- Write a line containing the current input prompt and the current line
- buffer at the current cursor position.
- """
- self.terminal.write(self.ps[self.pn] + ''.join(self.lineBuffer))
-
- def terminalSize(self, width, height):
- # XXX - Clear the previous input line, redraw it at the new
- # cursor position
- self.terminal.eraseDisplay()
- self.terminal.cursorHome()
- self.width = width
- self.height = height
- self.drawInputLine()
-
- def unhandledControlSequence(self, seq):
- pass
-
- def keystrokeReceived(self, keyID, modifier):
- m = self.keyHandlers.get(keyID)
- if m is not None:
- m()
- elif keyID in self._printableChars:
- self.characterReceived(keyID, False)
- else:
- log.msg("Received unhandled keyID: %r" % (keyID,))
-
- def characterReceived(self, ch, moreCharactersComing):
- if self.mode == 'insert':
- self.lineBuffer.insert(self.lineBufferIndex, ch)
- else:
- self.lineBuffer[self.lineBufferIndex:self.lineBufferIndex+1] = [ch]
- self.lineBufferIndex += 1
- self.terminal.write(ch)
-
- def handle_TAB(self):
- n = self.TABSTOP - (len(self.lineBuffer) % self.TABSTOP)
- self.terminal.cursorForward(n)
- self.lineBufferIndex += n
- self.lineBuffer.extend(' ' * n)
-
- def handle_LEFT(self):
- if self.lineBufferIndex > 0:
- self.lineBufferIndex -= 1
- self.terminal.cursorBackward()
-
- def handle_RIGHT(self):
- if self.lineBufferIndex < len(self.lineBuffer):
- self.lineBufferIndex += 1
- self.terminal.cursorForward()
-
- def handle_HOME(self):
- if self.lineBufferIndex:
- self.terminal.cursorBackward(self.lineBufferIndex)
- self.lineBufferIndex = 0
-
- def handle_END(self):
- offset = len(self.lineBuffer) - self.lineBufferIndex
- if offset:
- self.terminal.cursorForward(offset)
- self.lineBufferIndex = len(self.lineBuffer)
-
- def handle_BACKSPACE(self):
- if self.lineBufferIndex > 0:
- self.lineBufferIndex -= 1
- del self.lineBuffer[self.lineBufferIndex]
- self.terminal.cursorBackward()
- self.terminal.deleteCharacter()
-
- def handle_DELETE(self):
- if self.lineBufferIndex < len(self.lineBuffer):
- del self.lineBuffer[self.lineBufferIndex]
- self.terminal.deleteCharacter()
-
- def handle_RETURN(self):
- line = ''.join(self.lineBuffer)
- self.lineBuffer = []
- self.lineBufferIndex = 0
- self.terminal.nextLine()
- self.lineReceived(line)
-
- def handle_INSERT(self):
- assert self.mode in ('typeover', 'insert')
- if self.mode == 'typeover':
- self.setInsertMode()
- else:
- self.setTypeoverMode()
-
- def lineReceived(self, line):
- pass
-
-class HistoricRecvLine(RecvLine):
- """L{TerminalProtocol} which adds both basic line-editing features and input history.
-
- Everything supported by L{RecvLine} is also supported by this class. In addition, the
- up and down arrows traverse the input history. Each received line is automatically
- added to the end of the input history.
- """
- def connectionMade(self):
- RecvLine.connectionMade(self)
-
- self.historyLines = []
- self.historyPosition = 0
-
- t = self.terminal
- self.keyHandlers.update({t.UP_ARROW: self.handle_UP,
- t.DOWN_ARROW: self.handle_DOWN})
-
- def currentHistoryBuffer(self):
- b = tuple(self.historyLines)
- return b[:self.historyPosition], b[self.historyPosition:]
-
- def _deliverBuffer(self, buf):
- if buf:
- for ch in buf[:-1]:
- self.characterReceived(ch, True)
- self.characterReceived(buf[-1], False)
-
- def handle_UP(self):
- if self.lineBuffer and self.historyPosition == len(self.historyLines):
- self.historyLines.append(self.lineBuffer)
- if self.historyPosition > 0:
- self.handle_HOME()
- self.terminal.eraseToLineEnd()
-
- self.historyPosition -= 1
- self.lineBuffer = []
-
- self._deliverBuffer(self.historyLines[self.historyPosition])
-
- def handle_DOWN(self):
- if self.historyPosition < len(self.historyLines) - 1:
- self.handle_HOME()
- self.terminal.eraseToLineEnd()
-
- self.historyPosition += 1
- self.lineBuffer = []
-
- self._deliverBuffer(self.historyLines[self.historyPosition])
- else:
- self.handle_HOME()
- self.terminal.eraseToLineEnd()
-
- self.historyPosition = len(self.historyLines)
- self.lineBuffer = []
- self.lineBufferIndex = 0
-
- def handle_RETURN(self):
- if self.lineBuffer:
- self.historyLines.append(''.join(self.lineBuffer))
- self.historyPosition = len(self.historyLines)
- return RecvLine.handle_RETURN(self)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/__init__.py
deleted file mode 100644
index 63fdb3d..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-'conch scripts'
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/cftp.py b/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/cftp.py
deleted file mode 100644
index f7a5a64..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/cftp.py
+++ /dev/null
@@ -1,832 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_cftp -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Implementation module for the I{cftp} command.
-"""
-
-import os, sys, getpass, struct, tty, fcntl, stat
-import fnmatch, pwd, glob
-
-from twisted.conch.client import connect, default, options
-from twisted.conch.ssh import connection, common
-from twisted.conch.ssh import channel, filetransfer
-from twisted.protocols import basic
-from twisted.internet import reactor, stdio, defer, utils
-from twisted.python import log, usage, failure
-
-class ClientOptions(options.ConchOptions):
-
- synopsis = """Usage: cftp [options] [user@]host
- cftp [options] [user@]host[:dir[/]]
- cftp [options] [user@]host[:file [localfile]]
-"""
- longdesc = ("cftp is a client for logging into a remote machine and "
- "executing commands to send and receive file information")
-
- optParameters = [
- ['buffersize', 'B', 32768, 'Size of the buffer to use for sending/receiving.'],
- ['batchfile', 'b', None, 'File to read commands from, or \'-\' for stdin.'],
- ['requests', 'R', 5, 'Number of requests to make before waiting for a reply.'],
- ['subsystem', 's', 'sftp', 'Subsystem/server program to connect to.']]
-
- compData = usage.Completions(
- descriptions={
- "buffersize": "Size of send/receive buffer (default: 32768)"},
- extraActions=[usage.CompleteUserAtHost(),
- usage.CompleteFiles(descr="local file")])
-
- def parseArgs(self, host, localPath=None):
- self['remotePath'] = ''
- if ':' in host:
- host, self['remotePath'] = host.split(':', 1)
- self['remotePath'].rstrip('/')
- self['host'] = host
- self['localPath'] = localPath
-
-def run():
-# import hotshot
-# prof = hotshot.Profile('cftp.prof')
-# prof.start()
- args = sys.argv[1:]
- if '-l' in args: # cvs is an idiot
- i = args.index('-l')
- args = args[i:i+2]+args
- del args[i+2:i+4]
- options = ClientOptions()
- try:
- options.parseOptions(args)
- except usage.UsageError, u:
- print 'ERROR: %s' % u
- sys.exit(1)
- if options['log']:
- realout = sys.stdout
- log.startLogging(sys.stderr)
- sys.stdout = realout
- else:
- log.discardLogs()
- doConnect(options)
- reactor.run()
-# prof.stop()
-# prof.close()
-
-def handleError():
- global exitStatus
- exitStatus = 2
- try:
- reactor.stop()
- except: pass
- log.err(failure.Failure())
- raise
-
-def doConnect(options):
-# log.deferr = handleError # HACK
- if '@' in options['host']:
- options['user'], options['host'] = options['host'].split('@',1)
- host = options['host']
- if not options['user']:
- options['user'] = getpass.getuser()
- if not options['port']:
- options['port'] = 22
- else:
- options['port'] = int(options['port'])
- host = options['host']
- port = options['port']
- conn = SSHConnection()
- conn.options = options
- vhk = default.verifyHostKey
- uao = default.SSHUserAuthClient(options['user'], options, conn)
- connect.connect(host, port, options, vhk, uao).addErrback(_ebExit)
-
-def _ebExit(f):
- #global exitStatus
- if hasattr(f.value, 'value'):
- s = f.value.value
- else:
- s = str(f)
- print s
- #exitStatus = "conch: exiting with error %s" % f
- try:
- reactor.stop()
- except: pass
-
-def _ignore(*args): pass
-
-class FileWrapper:
-
- def __init__(self, f):
- self.f = f
- self.total = 0.0
- f.seek(0, 2) # seek to the end
- self.size = f.tell()
-
- def __getattr__(self, attr):
- return getattr(self.f, attr)
-
-class StdioClient(basic.LineReceiver):
-
- _pwd = pwd
-
- ps = 'cftp> '
- delimiter = '\n'
-
- reactor = reactor
-
- def __init__(self, client, f = None):
- self.client = client
- self.currentDirectory = ''
- self.file = f
- self.useProgressBar = (not f and 1) or 0
-
- def connectionMade(self):
- self.client.realPath('').addCallback(self._cbSetCurDir)
-
- def _cbSetCurDir(self, path):
- self.currentDirectory = path
- self._newLine()
-
- def lineReceived(self, line):
- if self.client.transport.localClosed:
- return
- log.msg('got line %s' % repr(line))
- line = line.lstrip()
- if not line:
- self._newLine()
- return
- if self.file and line.startswith('-'):
- self.ignoreErrors = 1
- line = line[1:]
- else:
- self.ignoreErrors = 0
- d = self._dispatchCommand(line)
- if d is not None:
- d.addCallback(self._cbCommand)
- d.addErrback(self._ebCommand)
-
-
- def _dispatchCommand(self, line):
- if ' ' in line:
- command, rest = line.split(' ', 1)
- rest = rest.lstrip()
- else:
- command, rest = line, ''
- if command.startswith('!'): # command
- f = self.cmd_EXEC
- rest = (command[1:] + ' ' + rest).strip()
- else:
- command = command.upper()
- log.msg('looking up cmd %s' % command)
- f = getattr(self, 'cmd_%s' % command, None)
- if f is not None:
- return defer.maybeDeferred(f, rest)
- else:
- self._ebCommand(failure.Failure(NotImplementedError(
- "No command called `%s'" % command)))
- self._newLine()
-
- def _printFailure(self, f):
- log.msg(f)
- e = f.trap(NotImplementedError, filetransfer.SFTPError, OSError, IOError)
- if e == NotImplementedError:
- self.transport.write(self.cmd_HELP(''))
- elif e == filetransfer.SFTPError:
- self.transport.write("remote error %i: %s\n" %
- (f.value.code, f.value.message))
- elif e in (OSError, IOError):
- self.transport.write("local error %i: %s\n" %
- (f.value.errno, f.value.strerror))
-
- def _newLine(self):
- if self.client.transport.localClosed:
- return
- self.transport.write(self.ps)
- self.ignoreErrors = 0
- if self.file:
- l = self.file.readline()
- if not l:
- self.client.transport.loseConnection()
- else:
- self.transport.write(l)
- self.lineReceived(l.strip())
-
- def _cbCommand(self, result):
- if result is not None:
- self.transport.write(result)
- if not result.endswith('\n'):
- self.transport.write('\n')
- self._newLine()
-
- def _ebCommand(self, f):
- self._printFailure(f)
- if self.file and not self.ignoreErrors:
- self.client.transport.loseConnection()
- self._newLine()
-
- def cmd_CD(self, path):
- path, rest = self._getFilename(path)
- if not path.endswith('/'):
- path += '/'
- newPath = path and os.path.join(self.currentDirectory, path) or ''
- d = self.client.openDirectory(newPath)
- d.addCallback(self._cbCd)
- d.addErrback(self._ebCommand)
- return d
-
- def _cbCd(self, directory):
- directory.close()
- d = self.client.realPath(directory.name)
- d.addCallback(self._cbCurDir)
- return d
-
- def _cbCurDir(self, path):
- self.currentDirectory = path
-
- def cmd_CHGRP(self, rest):
- grp, rest = rest.split(None, 1)
- path, rest = self._getFilename(rest)
- grp = int(grp)
- d = self.client.getAttrs(path)
- d.addCallback(self._cbSetUsrGrp, path, grp=grp)
- return d
-
- def cmd_CHMOD(self, rest):
- mod, rest = rest.split(None, 1)
- path, rest = self._getFilename(rest)
- mod = int(mod, 8)
- d = self.client.setAttrs(path, {'permissions':mod})
- d.addCallback(_ignore)
- return d
-
- def cmd_CHOWN(self, rest):
- usr, rest = rest.split(None, 1)
- path, rest = self._getFilename(rest)
- usr = int(usr)
- d = self.client.getAttrs(path)
- d.addCallback(self._cbSetUsrGrp, path, usr=usr)
- return d
-
- def _cbSetUsrGrp(self, attrs, path, usr=None, grp=None):
- new = {}
- new['uid'] = (usr is not None) and usr or attrs['uid']
- new['gid'] = (grp is not None) and grp or attrs['gid']
- d = self.client.setAttrs(path, new)
- d.addCallback(_ignore)
- return d
-
- def cmd_GET(self, rest):
- remote, rest = self._getFilename(rest)
- if '*' in remote or '?' in remote: # wildcard
- if rest:
- local, rest = self._getFilename(rest)
- if not os.path.isdir(local):
- return "Wildcard get with non-directory target."
- else:
- local = ''
- d = self._remoteGlob(remote)
- d.addCallback(self._cbGetMultiple, local)
- return d
- if rest:
- local, rest = self._getFilename(rest)
- else:
- local = os.path.split(remote)[1]
- log.msg((remote, local))
- lf = file(local, 'w', 0)
- path = os.path.join(self.currentDirectory, remote)
- d = self.client.openFile(path, filetransfer.FXF_READ, {})
- d.addCallback(self._cbGetOpenFile, lf)
- d.addErrback(self._ebCloseLf, lf)
- return d
-
- def _cbGetMultiple(self, files, local):
- #if self._useProgressBar: # one at a time
- # XXX this can be optimized for times w/o progress bar
- return self._cbGetMultipleNext(None, files, local)
-
- def _cbGetMultipleNext(self, res, files, local):
- if isinstance(res, failure.Failure):
- self._printFailure(res)
- elif res:
- self.transport.write(res)
- if not res.endswith('\n'):
- self.transport.write('\n')
- if not files:
- return
- f = files.pop(0)[0]
- lf = file(os.path.join(local, os.path.split(f)[1]), 'w', 0)
- path = os.path.join(self.currentDirectory, f)
- d = self.client.openFile(path, filetransfer.FXF_READ, {})
- d.addCallback(self._cbGetOpenFile, lf)
- d.addErrback(self._ebCloseLf, lf)
- d.addBoth(self._cbGetMultipleNext, files, local)
- return d
-
- def _ebCloseLf(self, f, lf):
- lf.close()
- return f
-
- def _cbGetOpenFile(self, rf, lf):
- return rf.getAttrs().addCallback(self._cbGetFileSize, rf, lf)
-
- def _cbGetFileSize(self, attrs, rf, lf):
- if not stat.S_ISREG(attrs['permissions']):
- rf.close()
- lf.close()
- return "Can't get non-regular file: %s" % rf.name
- rf.size = attrs['size']
- bufferSize = self.client.transport.conn.options['buffersize']
- numRequests = self.client.transport.conn.options['requests']
- rf.total = 0.0
- dList = []
- chunks = []
- startTime = self.reactor.seconds()
- for i in range(numRequests):
- d = self._cbGetRead('', rf, lf, chunks, 0, bufferSize, startTime)
- dList.append(d)
- dl = defer.DeferredList(dList, fireOnOneErrback=1)
- dl.addCallback(self._cbGetDone, rf, lf)
- return dl
-
- def _getNextChunk(self, chunks):
- end = 0
- for chunk in chunks:
- if end == 'eof':
- return # nothing more to get
- if end != chunk[0]:
- i = chunks.index(chunk)
- chunks.insert(i, (end, chunk[0]))
- return (end, chunk[0] - end)
- end = chunk[1]
- bufSize = int(self.client.transport.conn.options['buffersize'])
- chunks.append((end, end + bufSize))
- return (end, bufSize)
-
- def _cbGetRead(self, data, rf, lf, chunks, start, size, startTime):
- if data and isinstance(data, failure.Failure):
- log.msg('get read err: %s' % data)
- reason = data
- reason.trap(EOFError)
- i = chunks.index((start, start + size))
- del chunks[i]
- chunks.insert(i, (start, 'eof'))
- elif data:
- log.msg('get read data: %i' % len(data))
- lf.seek(start)
- lf.write(data)
- if len(data) != size:
- log.msg('got less than we asked for: %i < %i' %
- (len(data), size))
- i = chunks.index((start, start + size))
- del chunks[i]
- chunks.insert(i, (start, start + len(data)))
- rf.total += len(data)
- if self.useProgressBar:
- self._printProgressBar(rf, startTime)
- chunk = self._getNextChunk(chunks)
- if not chunk:
- return
- else:
- start, length = chunk
- log.msg('asking for %i -> %i' % (start, start+length))
- d = rf.readChunk(start, length)
- d.addBoth(self._cbGetRead, rf, lf, chunks, start, length, startTime)
- return d
-
- def _cbGetDone(self, ignored, rf, lf):
- log.msg('get done')
- rf.close()
- lf.close()
- if self.useProgressBar:
- self.transport.write('\n')
- return "Transferred %s to %s" % (rf.name, lf.name)
-
- def cmd_PUT(self, rest):
- local, rest = self._getFilename(rest)
- if '*' in local or '?' in local: # wildcard
- if rest:
- remote, rest = self._getFilename(rest)
- path = os.path.join(self.currentDirectory, remote)
- d = self.client.getAttrs(path)
- d.addCallback(self._cbPutTargetAttrs, remote, local)
- return d
- else:
- remote = ''
- files = glob.glob(local)
- return self._cbPutMultipleNext(None, files, remote)
- if rest:
- remote, rest = self._getFilename(rest)
- else:
- remote = os.path.split(local)[1]
- lf = file(local, 'r')
- path = os.path.join(self.currentDirectory, remote)
- flags = filetransfer.FXF_WRITE|filetransfer.FXF_CREAT|filetransfer.FXF_TRUNC
- d = self.client.openFile(path, flags, {})
- d.addCallback(self._cbPutOpenFile, lf)
- d.addErrback(self._ebCloseLf, lf)
- return d
-
- def _cbPutTargetAttrs(self, attrs, path, local):
- if not stat.S_ISDIR(attrs['permissions']):
- return "Wildcard put with non-directory target."
- return self._cbPutMultipleNext(None, files, path)
-
- def _cbPutMultipleNext(self, res, files, path):
- if isinstance(res, failure.Failure):
- self._printFailure(res)
- elif res:
- self.transport.write(res)
- if not res.endswith('\n'):
- self.transport.write('\n')
- f = None
- while files and not f:
- try:
- f = files.pop(0)
- lf = file(f, 'r')
- except:
- self._printFailure(failure.Failure())
- f = None
- if not f:
- return
- name = os.path.split(f)[1]
- remote = os.path.join(self.currentDirectory, path, name)
- log.msg((name, remote, path))
- flags = filetransfer.FXF_WRITE|filetransfer.FXF_CREAT|filetransfer.FXF_TRUNC
- d = self.client.openFile(remote, flags, {})
- d.addCallback(self._cbPutOpenFile, lf)
- d.addErrback(self._ebCloseLf, lf)
- d.addBoth(self._cbPutMultipleNext, files, path)
- return d
-
- def _cbPutOpenFile(self, rf, lf):
- numRequests = self.client.transport.conn.options['requests']
- if self.useProgressBar:
- lf = FileWrapper(lf)
- dList = []
- chunks = []
- startTime = self.reactor.seconds()
- for i in range(numRequests):
- d = self._cbPutWrite(None, rf, lf, chunks, startTime)
- if d:
- dList.append(d)
- dl = defer.DeferredList(dList, fireOnOneErrback=1)
- dl.addCallback(self._cbPutDone, rf, lf)
- return dl
-
- def _cbPutWrite(self, ignored, rf, lf, chunks, startTime):
- chunk = self._getNextChunk(chunks)
- start, size = chunk
- lf.seek(start)
- data = lf.read(size)
- if self.useProgressBar:
- lf.total += len(data)
- self._printProgressBar(lf, startTime)
- if data:
- d = rf.writeChunk(start, data)
- d.addCallback(self._cbPutWrite, rf, lf, chunks, startTime)
- return d
- else:
- return
-
- def _cbPutDone(self, ignored, rf, lf):
- lf.close()
- rf.close()
- if self.useProgressBar:
- self.transport.write('\n')
- return 'Transferred %s to %s' % (lf.name, rf.name)
-
- def cmd_LCD(self, path):
- os.chdir(path)
-
- def cmd_LN(self, rest):
- linkpath, rest = self._getFilename(rest)
- targetpath, rest = self._getFilename(rest)
- linkpath, targetpath = map(
- lambda x: os.path.join(self.currentDirectory, x),
- (linkpath, targetpath))
- return self.client.makeLink(linkpath, targetpath).addCallback(_ignore)
-
- def cmd_LS(self, rest):
- # possible lines:
- # ls current directory
- # ls name_of_file that file
- # ls name_of_directory that directory
- # ls some_glob_string current directory, globbed for that string
- options = []
- rest = rest.split()
- while rest and rest[0] and rest[0][0] == '-':
- opts = rest.pop(0)[1:]
- for o in opts:
- if o == 'l':
- options.append('verbose')
- elif o == 'a':
- options.append('all')
- rest = ' '.join(rest)
- path, rest = self._getFilename(rest)
- if not path:
- fullPath = self.currentDirectory + '/'
- else:
- fullPath = os.path.join(self.currentDirectory, path)
- d = self._remoteGlob(fullPath)
- d.addCallback(self._cbDisplayFiles, options)
- return d
-
- def _cbDisplayFiles(self, files, options):
- files.sort()
- if 'all' not in options:
- files = [f for f in files if not f[0].startswith('.')]
- if 'verbose' in options:
- lines = [f[1] for f in files]
- else:
- lines = [f[0] for f in files]
- if not lines:
- return None
- else:
- return '\n'.join(lines)
-
- def cmd_MKDIR(self, path):
- path, rest = self._getFilename(path)
- path = os.path.join(self.currentDirectory, path)
- return self.client.makeDirectory(path, {}).addCallback(_ignore)
-
- def cmd_RMDIR(self, path):
- path, rest = self._getFilename(path)
- path = os.path.join(self.currentDirectory, path)
- return self.client.removeDirectory(path).addCallback(_ignore)
-
- def cmd_LMKDIR(self, path):
- os.system("mkdir %s" % path)
-
- def cmd_RM(self, path):
- path, rest = self._getFilename(path)
- path = os.path.join(self.currentDirectory, path)
- return self.client.removeFile(path).addCallback(_ignore)
-
- def cmd_LLS(self, rest):
- os.system("ls %s" % rest)
-
- def cmd_RENAME(self, rest):
- oldpath, rest = self._getFilename(rest)
- newpath, rest = self._getFilename(rest)
- oldpath, newpath = map (
- lambda x: os.path.join(self.currentDirectory, x),
- (oldpath, newpath))
- return self.client.renameFile(oldpath, newpath).addCallback(_ignore)
-
- def cmd_EXIT(self, ignored):
- self.client.transport.loseConnection()
-
- cmd_QUIT = cmd_EXIT
-
- def cmd_VERSION(self, ignored):
- return "SFTP version %i" % self.client.version
-
- def cmd_HELP(self, ignored):
- return """Available commands:
-cd path Change remote directory to 'path'.
-chgrp gid path Change gid of 'path' to 'gid'.
-chmod mode path Change mode of 'path' to 'mode'.
-chown uid path Change uid of 'path' to 'uid'.
-exit Disconnect from the server.
-get remote-path [local-path] Get remote file.
-help Get a list of available commands.
-lcd path Change local directory to 'path'.
-lls [ls-options] [path] Display local directory listing.
-lmkdir path Create local directory.
-ln linkpath targetpath Symlink remote file.
-lpwd Print the local working directory.
-ls [-l] [path] Display remote directory listing.
-mkdir path Create remote directory.
-progress Toggle progress bar.
-put local-path [remote-path] Put local file.
-pwd Print the remote working directory.
-quit Disconnect from the server.
-rename oldpath newpath Rename remote file.
-rmdir path Remove remote directory.
-rm path Remove remote file.
-version Print the SFTP version.
-? Synonym for 'help'.
-"""
-
- def cmd_PWD(self, ignored):
- return self.currentDirectory
-
- def cmd_LPWD(self, ignored):
- return os.getcwd()
-
- def cmd_PROGRESS(self, ignored):
- self.useProgressBar = not self.useProgressBar
- return "%ssing progess bar." % (self.useProgressBar and "U" or "Not u")
-
- def cmd_EXEC(self, rest):
- """
- Run C{rest} using the user's shell (or /bin/sh if they do not have
- one).
- """
- shell = self._pwd.getpwnam(getpass.getuser())[6]
- if not shell:
- shell = '/bin/sh'
- if rest:
- cmds = ['-c', rest]
- return utils.getProcessOutput(shell, cmds, errortoo=1)
- else:
- os.system(shell)
-
- # accessory functions
-
- def _remoteGlob(self, fullPath):
- log.msg('looking up %s' % fullPath)
- head, tail = os.path.split(fullPath)
- if '*' in tail or '?' in tail:
- glob = 1
- else:
- glob = 0
- if tail and not glob: # could be file or directory
- # try directory first
- d = self.client.openDirectory(fullPath)
- d.addCallback(self._cbOpenList, '')
- d.addErrback(self._ebNotADirectory, head, tail)
- else:
- d = self.client.openDirectory(head)
- d.addCallback(self._cbOpenList, tail)
- return d
-
- def _cbOpenList(self, directory, glob):
- files = []
- d = directory.read()
- d.addBoth(self._cbReadFile, files, directory, glob)
- return d
-
- def _ebNotADirectory(self, reason, path, glob):
- d = self.client.openDirectory(path)
- d.addCallback(self._cbOpenList, glob)
- return d
-
- def _cbReadFile(self, files, l, directory, glob):
- if not isinstance(files, failure.Failure):
- if glob:
- l.extend([f for f in files if fnmatch.fnmatch(f[0], glob)])
- else:
- l.extend(files)
- d = directory.read()
- d.addBoth(self._cbReadFile, l, directory, glob)
- return d
- else:
- reason = files
- reason.trap(EOFError)
- directory.close()
- return l
-
- def _abbrevSize(self, size):
- # from http://mail.python.org/pipermail/python-list/1999-December/018395.html
- _abbrevs = [
- (1<<50L, 'PB'),
- (1<<40L, 'TB'),
- (1<<30L, 'GB'),
- (1<<20L, 'MB'),
- (1<<10L, 'kB'),
- (1, 'B')
- ]
-
- for factor, suffix in _abbrevs:
- if size > factor:
- break
- return '%.1f' % (size/factor) + suffix
-
- def _abbrevTime(self, t):
- if t > 3600: # 1 hour
- hours = int(t / 3600)
- t -= (3600 * hours)
- mins = int(t / 60)
- t -= (60 * mins)
- return "%i:%02i:%02i" % (hours, mins, t)
- else:
- mins = int(t/60)
- t -= (60 * mins)
- return "%02i:%02i" % (mins, t)
-
-
- def _printProgressBar(self, f, startTime):
- """
- Update a console progress bar on this L{StdioClient}'s transport, based
- on the difference between the start time of the operation and the
- current time according to the reactor, and appropriate to the size of
- the console window.
-
- @param f: a wrapper around the file which is being written or read
- @type f: L{FileWrapper}
-
- @param startTime: The time at which the operation being tracked began.
- @type startTime: C{float}
- """
- diff = self.reactor.seconds() - startTime
- total = f.total
- try:
- winSize = struct.unpack('4H',
- fcntl.ioctl(0, tty.TIOCGWINSZ, '12345679'))
- except IOError:
- winSize = [None, 80]
- if diff == 0.0:
- speed = 0.0
- else:
- speed = total / diff
- if speed:
- timeLeft = (f.size - total) / speed
- else:
- timeLeft = 0
- front = f.name
- back = '%3i%% %s %sps %s ' % ((total / f.size) * 100,
- self._abbrevSize(total),
- self._abbrevSize(speed),
- self._abbrevTime(timeLeft))
- spaces = (winSize[1] - (len(front) + len(back) + 1)) * ' '
- self.transport.write('\r%s%s%s' % (front, spaces, back))
-
-
- def _getFilename(self, line):
- line.lstrip()
- if not line:
- return None, ''
- if line[0] in '\'"':
- ret = []
- line = list(line)
- try:
- for i in range(1,len(line)):
- c = line[i]
- if c == line[0]:
- return ''.join(ret), ''.join(line[i+1:]).lstrip()
- elif c == '\\': # quoted character
- del line[i]
- if line[i] not in '\'"\\':
- raise IndexError, "bad quote: \\%s" % line[i]
- ret.append(line[i])
- else:
- ret.append(line[i])
- except IndexError:
- raise IndexError, "unterminated quote"
- ret = line.split(None, 1)
- if len(ret) == 1:
- return ret[0], ''
- else:
- return ret
-
-StdioClient.__dict__['cmd_?'] = StdioClient.cmd_HELP
-
-class SSHConnection(connection.SSHConnection):
- def serviceStarted(self):
- self.openChannel(SSHSession())
-
-class SSHSession(channel.SSHChannel):
-
- name = 'session'
-
- def channelOpen(self, foo):
- log.msg('session %s open' % self.id)
- if self.conn.options['subsystem'].startswith('/'):
- request = 'exec'
- else:
- request = 'subsystem'
- d = self.conn.sendRequest(self, request, \
- common.NS(self.conn.options['subsystem']), wantReply=1)
- d.addCallback(self._cbSubsystem)
- d.addErrback(_ebExit)
-
- def _cbSubsystem(self, result):
- self.client = filetransfer.FileTransferClient()
- self.client.makeConnection(self)
- self.dataReceived = self.client.dataReceived
- f = None
- if self.conn.options['batchfile']:
- fn = self.conn.options['batchfile']
- if fn != '-':
- f = file(fn)
- self.stdio = stdio.StandardIO(StdioClient(self.client, f))
-
- def extReceived(self, t, data):
- if t==connection.EXTENDED_DATA_STDERR:
- log.msg('got %s stderr data' % len(data))
- sys.stderr.write(data)
- sys.stderr.flush()
-
- def eofReceived(self):
- log.msg('got eof')
- self.stdio.loseWriteConnection()
-
- def closeReceived(self):
- log.msg('remote side closed %s' % self)
- self.conn.sendClose(self)
-
- def closed(self):
- try:
- reactor.stop()
- except:
- pass
-
- def stopWriting(self):
- self.stdio.pauseProducing()
-
- def startWriting(self):
- self.stdio.resumeProducing()
-
-if __name__ == '__main__':
- run()
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/ckeygen.py b/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/ckeygen.py
deleted file mode 100644
index 113f362..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/ckeygen.py
+++ /dev/null
@@ -1,226 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_ckeygen -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Implementation module for the `ckeygen` command.
-"""
-
-import sys, os, getpass, socket
-if getpass.getpass == getpass.unix_getpass:
- try:
- import termios # hack around broken termios
- termios.tcgetattr, termios.tcsetattr
- except (ImportError, AttributeError):
- sys.modules['termios'] = None
- reload(getpass)
-
-from twisted.conch.ssh import keys
-from twisted.python import filepath, log, usage, randbytes
-
-
-
-class GeneralOptions(usage.Options):
- synopsis = """Usage: ckeygen [options]
- """
-
- longdesc = "ckeygen manipulates public/private keys in various ways."
-
- optParameters = [['bits', 'b', 1024, 'Number of bits in the key to create.'],
- ['filename', 'f', None, 'Filename of the key file.'],
- ['type', 't', None, 'Specify type of key to create.'],
- ['comment', 'C', None, 'Provide new comment.'],
- ['newpass', 'N', None, 'Provide new passphrase.'],
- ['pass', 'P', None, 'Provide old passphrase.']]
-
- optFlags = [['fingerprint', 'l', 'Show fingerprint of key file.'],
- ['changepass', 'p', 'Change passphrase of private key file.'],
- ['quiet', 'q', 'Quiet.'],
- ['no-passphrase', None, "Create the key with no passphrase."],
- ['showpub', 'y', 'Read private key file and print public key.']]
-
- compData = usage.Completions(
- optActions={"type": usage.CompleteList(["rsa", "dsa"])})
-
-
-
-def run():
- options = GeneralOptions()
- try:
- options.parseOptions(sys.argv[1:])
- except usage.UsageError, u:
- print 'ERROR: %s' % u
- options.opt_help()
- sys.exit(1)
- log.discardLogs()
- log.deferr = handleError # HACK
- if options['type']:
- if options['type'] == 'rsa':
- generateRSAkey(options)
- elif options['type'] == 'dsa':
- generateDSAkey(options)
- else:
- sys.exit('Key type was %s, must be one of: rsa, dsa' % options['type'])
- elif options['fingerprint']:
- printFingerprint(options)
- elif options['changepass']:
- changePassPhrase(options)
- elif options['showpub']:
- displayPublicKey(options)
- else:
- options.opt_help()
- sys.exit(1)
-
-
-
-def handleError():
- from twisted.python import failure
- global exitStatus
- exitStatus = 2
- log.err(failure.Failure())
- reactor.stop()
- raise
-
-
-
-def generateRSAkey(options):
- from Crypto.PublicKey import RSA
- print 'Generating public/private rsa key pair.'
- key = RSA.generate(int(options['bits']), randbytes.secureRandom)
- _saveKey(key, options)
-
-
-
-def generateDSAkey(options):
- from Crypto.PublicKey import DSA
- print 'Generating public/private dsa key pair.'
- key = DSA.generate(int(options['bits']), randbytes.secureRandom)
- _saveKey(key, options)
-
-
-
-def printFingerprint(options):
- if not options['filename']:
- filename = os.path.expanduser('~/.ssh/id_rsa')
- options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
- if os.path.exists(options['filename']+'.pub'):
- options['filename'] += '.pub'
- try:
- key = keys.Key.fromFile(options['filename'])
- obj = key.keyObject
- string = key.blob()
- print '%s %s %s' % (
- obj.size() + 1,
- key.fingerprint(),
- os.path.basename(options['filename']))
- except:
- sys.exit('bad key')
-
-
-
-def changePassPhrase(options):
- if not options['filename']:
- filename = os.path.expanduser('~/.ssh/id_rsa')
- options['filename'] = raw_input(
- 'Enter file in which the key is (%s): ' % filename)
- try:
- key = keys.Key.fromFile(options['filename']).keyObject
- except keys.EncryptedKeyError as e:
- # Raised if password not supplied for an encrypted key
- if not options.get('pass'):
- options['pass'] = getpass.getpass('Enter old passphrase: ')
- try:
- key = keys.Key.fromFile(
- options['filename'], passphrase=options['pass']).keyObject
- except keys.BadKeyError:
- sys.exit('Could not change passphrase: old passphrase error')
- except keys.EncryptedKeyError as e:
- sys.exit('Could not change passphrase: %s' % (e,))
- except keys.BadKeyError as e:
- sys.exit('Could not change passphrase: %s' % (e,))
-
- if not options.get('newpass'):
- while 1:
- p1 = getpass.getpass(
- 'Enter new passphrase (empty for no passphrase): ')
- p2 = getpass.getpass('Enter same passphrase again: ')
- if p1 == p2:
- break
- print 'Passphrases do not match. Try again.'
- options['newpass'] = p1
-
- try:
- newkeydata = keys.Key(key).toString('openssh',
- extra=options['newpass'])
- except Exception as e:
- sys.exit('Could not change passphrase: %s' % (e,))
-
- try:
- keys.Key.fromString(newkeydata, passphrase=options['newpass'])
- except (keys.EncryptedKeyError, keys.BadKeyError) as e:
- sys.exit('Could not change passphrase: %s' % (e,))
-
- fd = open(options['filename'], 'w')
- fd.write(newkeydata)
- fd.close()
-
- print 'Your identification has been saved with the new passphrase.'
-
-
-
-def displayPublicKey(options):
- if not options['filename']:
- filename = os.path.expanduser('~/.ssh/id_rsa')
- options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
- try:
- key = keys.Key.fromFile(options['filename']).keyObject
- except keys.EncryptedKeyError:
- if not options.get('pass'):
- options['pass'] = getpass.getpass('Enter passphrase: ')
- key = keys.Key.fromFile(
- options['filename'], passphrase = options['pass']).keyObject
- print keys.Key(key).public().toString('openssh')
-
-
-
-def _saveKey(key, options):
- if not options['filename']:
- kind = keys.objectType(key)
- kind = {'ssh-rsa':'rsa','ssh-dss':'dsa'}[kind]
- filename = os.path.expanduser('~/.ssh/id_%s'%kind)
- options['filename'] = raw_input('Enter file in which to save the key (%s): '%filename).strip() or filename
- if os.path.exists(options['filename']):
- print '%s already exists.' % options['filename']
- yn = raw_input('Overwrite (y/n)? ')
- if yn[0].lower() != 'y':
- sys.exit()
- if options.get('no-passphrase'):
- options['pass'] = b''
- elif not options['pass']:
- while 1:
- p1 = getpass.getpass('Enter passphrase (empty for no passphrase): ')
- p2 = getpass.getpass('Enter same passphrase again: ')
- if p1 == p2:
- break
- print 'Passphrases do not match. Try again.'
- options['pass'] = p1
-
- keyObj = keys.Key(key)
- comment = '%s@%s' % (getpass.getuser(), socket.gethostname())
-
- filepath.FilePath(options['filename']).setContent(
- keyObj.toString('openssh', options['pass']))
- os.chmod(options['filename'], 33152)
-
- filepath.FilePath(options['filename'] + '.pub').setContent(
- keyObj.public().toString('openssh', comment))
-
- print 'Your identification has been saved in %s' % options['filename']
- print 'Your public key has been saved in %s.pub' % options['filename']
- print 'The key fingerprint is:'
- print keyObj.fingerprint()
-
-
-
-if __name__ == '__main__':
- run()
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/conch.py b/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/conch.py
deleted file mode 100644
index 8c49544..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/conch.py
+++ /dev/null
@@ -1,512 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_conch -*-
-#
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-# $Id: conch.py,v 1.65 2004/03/11 00:29:14 z3p Exp $
-
-#""" Implementation module for the `conch` command.
-#"""
-from twisted.conch.client import connect, default, options
-from twisted.conch.error import ConchError
-from twisted.conch.ssh import connection, common
-from twisted.conch.ssh import session, forwarding, channel
-from twisted.internet import reactor, stdio, task
-from twisted.python import log, usage
-
-import os, sys, getpass, struct, tty, fcntl, signal
-
-class ClientOptions(options.ConchOptions):
-
- synopsis = """Usage: conch [options] host [command]
-"""
- longdesc = ("conch is a SSHv2 client that allows logging into a remote "
- "machine and executing commands.")
-
- optParameters = [['escape', 'e', '~'],
- ['localforward', 'L', None, 'listen-port:host:port Forward local port to remote address'],
- ['remoteforward', 'R', None, 'listen-port:host:port Forward remote port to local address'],
- ]
-
- optFlags = [['null', 'n', 'Redirect input from /dev/null.'],
- ['fork', 'f', 'Fork to background after authentication.'],
- ['tty', 't', 'Tty; allocate a tty even if command is given.'],
- ['notty', 'T', 'Do not allocate a tty.'],
- ['noshell', 'N', 'Do not execute a shell or command.'],
- ['subsystem', 's', 'Invoke command (mandatory) as SSH2 subsystem.'],
- ]
-
- compData = usage.Completions(
- mutuallyExclusive=[("tty", "notty")],
- optActions={
- "localforward": usage.Completer(descr="listen-port:host:port"),
- "remoteforward": usage.Completer(descr="listen-port:host:port")},
- extraActions=[usage.CompleteUserAtHost(),
- usage.Completer(descr="command"),
- usage.Completer(descr="argument", repeat=True)]
- )
-
- localForwards = []
- remoteForwards = []
-
- def opt_escape(self, esc):
- "Set escape character; ``none'' = disable"
- if esc == 'none':
- self['escape'] = None
- elif esc[0] == '^' and len(esc) == 2:
- self['escape'] = chr(ord(esc[1])-64)
- elif len(esc) == 1:
- self['escape'] = esc
- else:
- sys.exit("Bad escape character '%s'." % esc)
-
- def opt_localforward(self, f):
- "Forward local port to remote address (lport:host:port)"
- localPort, remoteHost, remotePort = f.split(':') # doesn't do v6 yet
- localPort = int(localPort)
- remotePort = int(remotePort)
- self.localForwards.append((localPort, (remoteHost, remotePort)))
-
- def opt_remoteforward(self, f):
- """Forward remote port to local address (rport:host:port)"""
- remotePort, connHost, connPort = f.split(':') # doesn't do v6 yet
- remotePort = int(remotePort)
- connPort = int(connPort)
- self.remoteForwards.append((remotePort, (connHost, connPort)))
-
- def parseArgs(self, host, *command):
- self['host'] = host
- self['command'] = ' '.join(command)
-
-# Rest of code in "run"
-options = None
-conn = None
-exitStatus = 0
-old = None
-_inRawMode = 0
-_savedRawMode = None
-
-def run():
- global options, old
- args = sys.argv[1:]
- if '-l' in args: # cvs is an idiot
- i = args.index('-l')
- args = args[i:i+2]+args
- del args[i+2:i+4]
- for arg in args[:]:
- try:
- i = args.index(arg)
- if arg[:2] == '-o' and args[i+1][0]!='-':
- args[i:i+2] = [] # suck on it scp
- except ValueError:
- pass
- options = ClientOptions()
- try:
- options.parseOptions(args)
- except usage.UsageError, u:
- print 'ERROR: %s' % u
- options.opt_help()
- sys.exit(1)
- if options['log']:
- if options['logfile']:
- if options['logfile'] == '-':
- f = sys.stdout
- else:
- f = file(options['logfile'], 'a+')
- else:
- f = sys.stderr
- realout = sys.stdout
- log.startLogging(f)
- sys.stdout = realout
- else:
- log.discardLogs()
- doConnect()
- fd = sys.stdin.fileno()
- try:
- old = tty.tcgetattr(fd)
- except:
- old = None
- try:
- oldUSR1 = signal.signal(signal.SIGUSR1, lambda *a: reactor.callLater(0, reConnect))
- except:
- oldUSR1 = None
- try:
- reactor.run()
- finally:
- if old:
- tty.tcsetattr(fd, tty.TCSANOW, old)
- if oldUSR1:
- signal.signal(signal.SIGUSR1, oldUSR1)
- if (options['command'] and options['tty']) or not options['notty']:
- signal.signal(signal.SIGWINCH, signal.SIG_DFL)
- if sys.stdout.isatty() and not options['command']:
- print 'Connection to %s closed.' % options['host']
- sys.exit(exitStatus)
-
-def handleError():
- from twisted.python import failure
- global exitStatus
- exitStatus = 2
- reactor.callLater(0.01, _stopReactor)
- log.err(failure.Failure())
- raise
-
-def _stopReactor():
- try:
- reactor.stop()
- except: pass
-
-def doConnect():
-# log.deferr = handleError # HACK
- if '@' in options['host']:
- options['user'], options['host'] = options['host'].split('@',1)
- if not options.identitys:
- options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa']
- host = options['host']
- if not options['user']:
- options['user'] = getpass.getuser()
- if not options['port']:
- options['port'] = 22
- else:
- options['port'] = int(options['port'])
- host = options['host']
- port = options['port']
- vhk = default.verifyHostKey
- uao = default.SSHUserAuthClient(options['user'], options, SSHConnection())
- connect.connect(host, port, options, vhk, uao).addErrback(_ebExit)
-
-def _ebExit(f):
- global exitStatus
- if hasattr(f.value, 'value'):
- s = f.value.value
- else:
- s = str(f)
- exitStatus = "conch: exiting with error %s" % f
- reactor.callLater(0.1, _stopReactor)
-
-def onConnect():
-# if keyAgent and options['agent']:
-# cc = protocol.ClientCreator(reactor, SSHAgentForwardingLocal, conn)
-# cc.connectUNIX(os.environ['SSH_AUTH_SOCK'])
- if hasattr(conn.transport, 'sendIgnore'):
- _KeepAlive(conn)
- if options.localForwards:
- for localPort, hostport in options.localForwards:
- s = reactor.listenTCP(localPort,
- forwarding.SSHListenForwardingFactory(conn,
- hostport,
- SSHListenClientForwardingChannel))
- conn.localForwards.append(s)
- if options.remoteForwards:
- for remotePort, hostport in options.remoteForwards:
- log.msg('asking for remote forwarding for %s:%s' %
- (remotePort, hostport))
- conn.requestRemoteForwarding(remotePort, hostport)
- reactor.addSystemEventTrigger('before', 'shutdown', beforeShutdown)
- if not options['noshell'] or options['agent']:
- conn.openChannel(SSHSession())
- if options['fork']:
- if os.fork():
- os._exit(0)
- os.setsid()
- for i in range(3):
- try:
- os.close(i)
- except OSError, e:
- import errno
- if e.errno != errno.EBADF:
- raise
-
-def reConnect():
- beforeShutdown()
- conn.transport.transport.loseConnection()
-
-def beforeShutdown():
- remoteForwards = options.remoteForwards
- for remotePort, hostport in remoteForwards:
- log.msg('cancelling %s:%s' % (remotePort, hostport))
- conn.cancelRemoteForwarding(remotePort)
-
-def stopConnection():
- if not options['reconnect']:
- reactor.callLater(0.1, _stopReactor)
-
-class _KeepAlive:
-
- def __init__(self, conn):
- self.conn = conn
- self.globalTimeout = None
- self.lc = task.LoopingCall(self.sendGlobal)
- self.lc.start(300)
-
- def sendGlobal(self):
- d = self.conn.sendGlobalRequest("conch-keep-alive@twistedmatrix.com",
- "", wantReply = 1)
- d.addBoth(self._cbGlobal)
- self.globalTimeout = reactor.callLater(30, self._ebGlobal)
-
- def _cbGlobal(self, res):
- if self.globalTimeout:
- self.globalTimeout.cancel()
- self.globalTimeout = None
-
- def _ebGlobal(self):
- if self.globalTimeout:
- self.globalTimeout = None
- self.conn.transport.loseConnection()
-
-class SSHConnection(connection.SSHConnection):
- def serviceStarted(self):
- global conn
- conn = self
- self.localForwards = []
- self.remoteForwards = {}
- if not isinstance(self, connection.SSHConnection):
- # make these fall through
- del self.__class__.requestRemoteForwarding
- del self.__class__.cancelRemoteForwarding
- onConnect()
-
- def serviceStopped(self):
- lf = self.localForwards
- self.localForwards = []
- for s in lf:
- s.loseConnection()
- stopConnection()
-
- def requestRemoteForwarding(self, remotePort, hostport):
- data = forwarding.packGlobal_tcpip_forward(('0.0.0.0', remotePort))
- d = self.sendGlobalRequest('tcpip-forward', data,
- wantReply=1)
- log.msg('requesting remote forwarding %s:%s' %(remotePort, hostport))
- d.addCallback(self._cbRemoteForwarding, remotePort, hostport)
- d.addErrback(self._ebRemoteForwarding, remotePort, hostport)
-
- def _cbRemoteForwarding(self, result, remotePort, hostport):
- log.msg('accepted remote forwarding %s:%s' % (remotePort, hostport))
- self.remoteForwards[remotePort] = hostport
- log.msg(repr(self.remoteForwards))
-
- def _ebRemoteForwarding(self, f, remotePort, hostport):
- log.msg('remote forwarding %s:%s failed' % (remotePort, hostport))
- log.msg(f)
-
- def cancelRemoteForwarding(self, remotePort):
- data = forwarding.packGlobal_tcpip_forward(('0.0.0.0', remotePort))
- self.sendGlobalRequest('cancel-tcpip-forward', data)
- log.msg('cancelling remote forwarding %s' % remotePort)
- try:
- del self.remoteForwards[remotePort]
- except:
- pass
- log.msg(repr(self.remoteForwards))
-
- def channel_forwarded_tcpip(self, windowSize, maxPacket, data):
- log.msg('%s %s' % ('FTCP', repr(data)))
- remoteHP, origHP = forwarding.unpackOpen_forwarded_tcpip(data)
- log.msg(self.remoteForwards)
- log.msg(remoteHP)
- if self.remoteForwards.has_key(remoteHP[1]):
- connectHP = self.remoteForwards[remoteHP[1]]
- log.msg('connect forwarding %s' % (connectHP,))
- return SSHConnectForwardingChannel(connectHP,
- remoteWindow = windowSize,
- remoteMaxPacket = maxPacket,
- conn = self)
- else:
- raise ConchError(connection.OPEN_CONNECT_FAILED, "don't know about that port")
-
-# def channel_auth_agent_openssh_com(self, windowSize, maxPacket, data):
-# if options['agent'] and keyAgent:
-# return agent.SSHAgentForwardingChannel(remoteWindow = windowSize,
-# remoteMaxPacket = maxPacket,
-# conn = self)
-# else:
-# return connection.OPEN_CONNECT_FAILED, "don't have an agent"
-
- def channelClosed(self, channel):
- log.msg('connection closing %s' % channel)
- log.msg(self.channels)
- if len(self.channels) == 1: # just us left
- log.msg('stopping connection')
- stopConnection()
- else:
- # because of the unix thing
- self.__class__.__bases__[0].channelClosed(self, channel)
-
-class SSHSession(channel.SSHChannel):
-
- name = 'session'
-
- def channelOpen(self, foo):
- log.msg('session %s open' % self.id)
- if options['agent']:
- d = self.conn.sendRequest(self, 'auth-agent-req@openssh.com', '', wantReply=1)
- d.addBoth(lambda x:log.msg(x))
- if options['noshell']: return
- if (options['command'] and options['tty']) or not options['notty']:
- _enterRawMode()
- c = session.SSHSessionClient()
- if options['escape'] and not options['notty']:
- self.escapeMode = 1
- c.dataReceived = self.handleInput
- else:
- c.dataReceived = self.write
- c.connectionLost = lambda x=None,s=self:s.sendEOF()
- self.stdio = stdio.StandardIO(c)
- fd = 0
- if options['subsystem']:
- self.conn.sendRequest(self, 'subsystem', \
- common.NS(options['command']))
- elif options['command']:
- if options['tty']:
- term = os.environ['TERM']
- winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
- winSize = struct.unpack('4H', winsz)
- ptyReqData = session.packRequest_pty_req(term, winSize, '')
- self.conn.sendRequest(self, 'pty-req', ptyReqData)
- signal.signal(signal.SIGWINCH, self._windowResized)
- self.conn.sendRequest(self, 'exec', \
- common.NS(options['command']))
- else:
- if not options['notty']:
- term = os.environ['TERM']
- winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
- winSize = struct.unpack('4H', winsz)
- ptyReqData = session.packRequest_pty_req(term, winSize, '')
- self.conn.sendRequest(self, 'pty-req', ptyReqData)
- signal.signal(signal.SIGWINCH, self._windowResized)
- self.conn.sendRequest(self, 'shell', '')
- #if hasattr(conn.transport, 'transport'):
- # conn.transport.transport.setTcpNoDelay(1)
-
- def handleInput(self, char):
- #log.msg('handling %s' % repr(char))
- if char in ('\n', '\r'):
- self.escapeMode = 1
- self.write(char)
- elif self.escapeMode == 1 and char == options['escape']:
- self.escapeMode = 2
- elif self.escapeMode == 2:
- self.escapeMode = 1 # so we can chain escapes together
- if char == '.': # disconnect
- log.msg('disconnecting from escape')
- stopConnection()
- return
- elif char == '\x1a': # ^Z, suspend
- def _():
- _leaveRawMode()
- sys.stdout.flush()
- sys.stdin.flush()
- os.kill(os.getpid(), signal.SIGTSTP)
- _enterRawMode()
- reactor.callLater(0, _)
- return
- elif char == 'R': # rekey connection
- log.msg('rekeying connection')
- self.conn.transport.sendKexInit()
- return
- elif char == '#': # display connections
- self.stdio.write('\r\nThe following connections are open:\r\n')
- channels = self.conn.channels.keys()
- channels.sort()
- for channelId in channels:
- self.stdio.write(' #%i %s\r\n' % (channelId, str(self.conn.channels[channelId])))
- return
- self.write('~' + char)
- else:
- self.escapeMode = 0
- self.write(char)
-
- def dataReceived(self, data):
- self.stdio.write(data)
-
- def extReceived(self, t, data):
- if t==connection.EXTENDED_DATA_STDERR:
- log.msg('got %s stderr data' % len(data))
- sys.stderr.write(data)
-
- def eofReceived(self):
- log.msg('got eof')
- self.stdio.loseWriteConnection()
-
- def closeReceived(self):
- log.msg('remote side closed %s' % self)
- self.conn.sendClose(self)
-
- def closed(self):
- global old
- log.msg('closed %s' % self)
- log.msg(repr(self.conn.channels))
-
- def request_exit_status(self, data):
- global exitStatus
- exitStatus = int(struct.unpack('>L', data)[0])
- log.msg('exit status: %s' % exitStatus)
-
- def sendEOF(self):
- self.conn.sendEOF(self)
-
- def stopWriting(self):
- self.stdio.pauseProducing()
-
- def startWriting(self):
- self.stdio.resumeProducing()
-
- def _windowResized(self, *args):
- winsz = fcntl.ioctl(0, tty.TIOCGWINSZ, '12345678')
- winSize = struct.unpack('4H', winsz)
- newSize = winSize[1], winSize[0], winSize[2], winSize[3]
- self.conn.sendRequest(self, 'window-change', struct.pack('!4L', *newSize))
-
-
-class SSHListenClientForwardingChannel(forwarding.SSHListenClientForwardingChannel): pass
-class SSHConnectForwardingChannel(forwarding.SSHConnectForwardingChannel): pass
-
-def _leaveRawMode():
- global _inRawMode
- if not _inRawMode:
- return
- fd = sys.stdin.fileno()
- tty.tcsetattr(fd, tty.TCSANOW, _savedMode)
- _inRawMode = 0
-
-def _enterRawMode():
- global _inRawMode, _savedMode
- if _inRawMode:
- return
- fd = sys.stdin.fileno()
- try:
- old = tty.tcgetattr(fd)
- new = old[:]
- except:
- log.msg('not a typewriter!')
- else:
- # iflage
- new[0] = new[0] | tty.IGNPAR
- new[0] = new[0] & ~(tty.ISTRIP | tty.INLCR | tty.IGNCR | tty.ICRNL |
- tty.IXON | tty.IXANY | tty.IXOFF)
- if hasattr(tty, 'IUCLC'):
- new[0] = new[0] & ~tty.IUCLC
-
- # lflag
- new[3] = new[3] & ~(tty.ISIG | tty.ICANON | tty.ECHO | tty.ECHO |
- tty.ECHOE | tty.ECHOK | tty.ECHONL)
- if hasattr(tty, 'IEXTEN'):
- new[3] = new[3] & ~tty.IEXTEN
-
- #oflag
- new[1] = new[1] & ~tty.OPOST
-
- new[6][tty.VMIN] = 1
- new[6][tty.VTIME] = 0
-
- _savedMode = old
- tty.tcsetattr(fd, tty.TCSANOW, new)
- #tty.setraw(fd)
- _inRawMode = 1
-
-if __name__ == '__main__':
- run()
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/tkconch.py b/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/tkconch.py
deleted file mode 100644
index eb00186..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/scripts/tkconch.py
+++ /dev/null
@@ -1,572 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_scripts -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Implementation module for the `tkconch` command.
-"""
-
-import Tkinter, tkFileDialog, tkFont, tkMessageBox, string
-from twisted.conch.ui import tkvt100
-from twisted.conch.ssh import transport, userauth, connection, common, keys
-from twisted.conch.ssh import session, forwarding, channel
-from twisted.conch.client.default import isInKnownHosts
-from twisted.internet import reactor, defer, protocol, tksupport
-from twisted.python import usage, log
-
-import os, sys, getpass, struct, base64, signal
-
-class TkConchMenu(Tkinter.Frame):
- def __init__(self, *args, **params):
- ## Standard heading: initialization
- apply(Tkinter.Frame.__init__, (self,) + args, params)
-
- self.master.title('TkConch')
- self.localRemoteVar = Tkinter.StringVar()
- self.localRemoteVar.set('local')
-
- Tkinter.Label(self, anchor='w', justify='left', text='Hostname').grid(column=1, row=1, sticky='w')
- self.host = Tkinter.Entry(self)
- self.host.grid(column=2, columnspan=2, row=1, sticky='nesw')
-
- Tkinter.Label(self, anchor='w', justify='left', text='Port').grid(column=1, row=2, sticky='w')
- self.port = Tkinter.Entry(self)
- self.port.grid(column=2, columnspan=2, row=2, sticky='nesw')
-
- Tkinter.Label(self, anchor='w', justify='left', text='Username').grid(column=1, row=3, sticky='w')
- self.user = Tkinter.Entry(self)
- self.user.grid(column=2, columnspan=2, row=3, sticky='nesw')
-
- Tkinter.Label(self, anchor='w', justify='left', text='Command').grid(column=1, row=4, sticky='w')
- self.command = Tkinter.Entry(self)
- self.command.grid(column=2, columnspan=2, row=4, sticky='nesw')
-
- Tkinter.Label(self, anchor='w', justify='left', text='Identity').grid(column=1, row=5, sticky='w')
- self.identity = Tkinter.Entry(self)
- self.identity.grid(column=2, row=5, sticky='nesw')
- Tkinter.Button(self, command=self.getIdentityFile, text='Browse').grid(column=3, row=5, sticky='nesw')
-
- Tkinter.Label(self, text='Port Forwarding').grid(column=1, row=6, sticky='w')
- self.forwards = Tkinter.Listbox(self, height=0, width=0)
- self.forwards.grid(column=2, columnspan=2, row=6, sticky='nesw')
- Tkinter.Button(self, text='Add', command=self.addForward).grid(column=1, row=7)
- Tkinter.Button(self, text='Remove', command=self.removeForward).grid(column=1, row=8)
- self.forwardPort = Tkinter.Entry(self)
- self.forwardPort.grid(column=2, row=7, sticky='nesw')
- Tkinter.Label(self, text='Port').grid(column=3, row=7, sticky='nesw')
- self.forwardHost = Tkinter.Entry(self)
- self.forwardHost.grid(column=2, row=8, sticky='nesw')
- Tkinter.Label(self, text='Host').grid(column=3, row=8, sticky='nesw')
- self.localForward = Tkinter.Radiobutton(self, text='Local', variable=self.localRemoteVar, value='local')
- self.localForward.grid(column=2, row=9)
- self.remoteForward = Tkinter.Radiobutton(self, text='Remote', variable=self.localRemoteVar, value='remote')
- self.remoteForward.grid(column=3, row=9)
-
- Tkinter.Label(self, text='Advanced Options').grid(column=1, columnspan=3, row=10, sticky='nesw')
-
- Tkinter.Label(self, anchor='w', justify='left', text='Cipher').grid(column=1, row=11, sticky='w')
- self.cipher = Tkinter.Entry(self, name='cipher')
- self.cipher.grid(column=2, columnspan=2, row=11, sticky='nesw')
-
- Tkinter.Label(self, anchor='w', justify='left', text='MAC').grid(column=1, row=12, sticky='w')
- self.mac = Tkinter.Entry(self, name='mac')
- self.mac.grid(column=2, columnspan=2, row=12, sticky='nesw')
-
- Tkinter.Label(self, anchor='w', justify='left', text='Escape Char').grid(column=1, row=13, sticky='w')
- self.escape = Tkinter.Entry(self, name='escape')
- self.escape.grid(column=2, columnspan=2, row=13, sticky='nesw')
- Tkinter.Button(self, text='Connect!', command=self.doConnect).grid(column=1, columnspan=3, row=14, sticky='nesw')
-
- # Resize behavior(s)
- self.grid_rowconfigure(6, weight=1, minsize=64)
- self.grid_columnconfigure(2, weight=1, minsize=2)
-
- self.master.protocol("WM_DELETE_WINDOW", sys.exit)
-
-
- def getIdentityFile(self):
- r = tkFileDialog.askopenfilename()
- if r:
- self.identity.delete(0, Tkinter.END)
- self.identity.insert(Tkinter.END, r)
-
- def addForward(self):
- port = self.forwardPort.get()
- self.forwardPort.delete(0, Tkinter.END)
- host = self.forwardHost.get()
- self.forwardHost.delete(0, Tkinter.END)
- if self.localRemoteVar.get() == 'local':
- self.forwards.insert(Tkinter.END, 'L:%s:%s' % (port, host))
- else:
- self.forwards.insert(Tkinter.END, 'R:%s:%s' % (port, host))
-
- def removeForward(self):
- cur = self.forwards.curselection()
- if cur:
- self.forwards.remove(cur[0])
-
- def doConnect(self):
- finished = 1
- options['host'] = self.host.get()
- options['port'] = self.port.get()
- options['user'] = self.user.get()
- options['command'] = self.command.get()
- cipher = self.cipher.get()
- mac = self.mac.get()
- escape = self.escape.get()
- if cipher:
- if cipher in SSHClientTransport.supportedCiphers:
- SSHClientTransport.supportedCiphers = [cipher]
- else:
- tkMessageBox.showerror('TkConch', 'Bad cipher.')
- finished = 0
-
- if mac:
- if mac in SSHClientTransport.supportedMACs:
- SSHClientTransport.supportedMACs = [mac]
- elif finished:
- tkMessageBox.showerror('TkConch', 'Bad MAC.')
- finished = 0
-
- if escape:
- if escape == 'none':
- options['escape'] = None
- elif escape[0] == '^' and len(escape) == 2:
- options['escape'] = chr(ord(escape[1])-64)
- elif len(escape) == 1:
- options['escape'] = escape
- elif finished:
- tkMessageBox.showerror('TkConch', "Bad escape character '%s'." % escape)
- finished = 0
-
- if self.identity.get():
- options.identitys.append(self.identity.get())
-
- for line in self.forwards.get(0,Tkinter.END):
- if line[0]=='L':
- options.opt_localforward(line[2:])
- else:
- options.opt_remoteforward(line[2:])
-
- if '@' in options['host']:
- options['user'], options['host'] = options['host'].split('@',1)
-
- if (not options['host'] or not options['user']) and finished:
- tkMessageBox.showerror('TkConch', 'Missing host or username.')
- finished = 0
- if finished:
- self.master.quit()
- self.master.destroy()
- if options['log']:
- realout = sys.stdout
- log.startLogging(sys.stderr)
- sys.stdout = realout
- else:
- log.discardLogs()
- log.deferr = handleError # HACK
- if not options.identitys:
- options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa']
- host = options['host']
- port = int(options['port'] or 22)
- log.msg((host,port))
- reactor.connectTCP(host, port, SSHClientFactory())
- frame.master.deiconify()
- frame.master.title('%s@%s - TkConch' % (options['user'], options['host']))
- else:
- self.focus()
-
-class GeneralOptions(usage.Options):
- synopsis = """Usage: tkconch [options] host [command]
- """
-
- optParameters = [['user', 'l', None, 'Log in using this user name.'],
- ['identity', 'i', '~/.ssh/identity', 'Identity for public key authentication'],
- ['escape', 'e', '~', "Set escape character; ``none'' = disable"],
- ['cipher', 'c', None, 'Select encryption algorithm.'],
- ['macs', 'm', None, 'Specify MAC algorithms for protocol version 2.'],
- ['port', 'p', None, 'Connect to this port. Server must be on the same port.'],
- ['localforward', 'L', None, 'listen-port:host:port Forward local port to remote address'],
- ['remoteforward', 'R', None, 'listen-port:host:port Forward remote port to local address'],
- ]
-
- optFlags = [['tty', 't', 'Tty; allocate a tty even if command is given.'],
- ['notty', 'T', 'Do not allocate a tty.'],
- ['version', 'V', 'Display version number only.'],
- ['compress', 'C', 'Enable compression.'],
- ['noshell', 'N', 'Do not execute a shell or command.'],
- ['subsystem', 's', 'Invoke command (mandatory) as SSH2 subsystem.'],
- ['log', 'v', 'Log to stderr'],
- ['ansilog', 'a', 'Print the receieved data to stdout']]
-
- _ciphers = transport.SSHClientTransport.supportedCiphers
- _macs = transport.SSHClientTransport.supportedMACs
-
- compData = usage.Completions(
- mutuallyExclusive=[("tty", "notty")],
- optActions={
- "cipher": usage.CompleteList(_ciphers),
- "macs": usage.CompleteList(_macs),
- "localforward": usage.Completer(descr="listen-port:host:port"),
- "remoteforward": usage.Completer(descr="listen-port:host:port")},
- extraActions=[usage.CompleteUserAtHost(),
- usage.Completer(descr="command"),
- usage.Completer(descr="argument", repeat=True)]
- )
-
- identitys = []
- localForwards = []
- remoteForwards = []
-
- def opt_identity(self, i):
- self.identitys.append(i)
-
- def opt_localforward(self, f):
- localPort, remoteHost, remotePort = f.split(':') # doesn't do v6 yet
- localPort = int(localPort)
- remotePort = int(remotePort)
- self.localForwards.append((localPort, (remoteHost, remotePort)))
-
- def opt_remoteforward(self, f):
- remotePort, connHost, connPort = f.split(':') # doesn't do v6 yet
- remotePort = int(remotePort)
- connPort = int(connPort)
- self.remoteForwards.append((remotePort, (connHost, connPort)))
-
- def opt_compress(self):
- SSHClientTransport.supportedCompressions[0:1] = ['zlib']
-
- def parseArgs(self, *args):
- if args:
- self['host'] = args[0]
- self['command'] = ' '.join(args[1:])
- else:
- self['host'] = ''
- self['command'] = ''
-
-# Rest of code in "run"
-options = None
-menu = None
-exitStatus = 0
-frame = None
-
-def deferredAskFrame(question, echo):
- if frame.callback:
- raise ValueError("can't ask 2 questions at once!")
- d = defer.Deferred()
- resp = []
- def gotChar(ch, resp=resp):
- if not ch: return
- if ch=='\x03': # C-c
- reactor.stop()
- if ch=='\r':
- frame.write('\r\n')
- stresp = ''.join(resp)
- del resp
- frame.callback = None
- d.callback(stresp)
- return
- elif 32 <= ord(ch) < 127:
- resp.append(ch)
- if echo:
- frame.write(ch)
- elif ord(ch) == 8 and resp: # BS
- if echo: frame.write('\x08 \x08')
- resp.pop()
- frame.callback = gotChar
- frame.write(question)
- frame.canvas.focus_force()
- return d
-
-def run():
- global menu, options, frame
- args = sys.argv[1:]
- if '-l' in args: # cvs is an idiot
- i = args.index('-l')
- args = args[i:i+2]+args
- del args[i+2:i+4]
- for arg in args[:]:
- try:
- i = args.index(arg)
- if arg[:2] == '-o' and args[i+1][0]!='-':
- args[i:i+2] = [] # suck on it scp
- except ValueError:
- pass
- root = Tkinter.Tk()
- root.withdraw()
- top = Tkinter.Toplevel()
- menu = TkConchMenu(top)
- menu.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
- options = GeneralOptions()
- try:
- options.parseOptions(args)
- except usage.UsageError, u:
- print 'ERROR: %s' % u
- options.opt_help()
- sys.exit(1)
- for k,v in options.items():
- if v and hasattr(menu, k):
- getattr(menu,k).insert(Tkinter.END, v)
- for (p, (rh, rp)) in options.localForwards:
- menu.forwards.insert(Tkinter.END, 'L:%s:%s:%s' % (p, rh, rp))
- options.localForwards = []
- for (p, (rh, rp)) in options.remoteForwards:
- menu.forwards.insert(Tkinter.END, 'R:%s:%s:%s' % (p, rh, rp))
- options.remoteForwards = []
- frame = tkvt100.VT100Frame(root, callback=None)
- root.geometry('%dx%d'%(tkvt100.fontWidth*frame.width+3, tkvt100.fontHeight*frame.height+3))
- frame.pack(side = Tkinter.TOP)
- tksupport.install(root)
- root.withdraw()
- if (options['host'] and options['user']) or '@' in options['host']:
- menu.doConnect()
- else:
- top.mainloop()
- reactor.run()
- sys.exit(exitStatus)
-
-def handleError():
- from twisted.python import failure
- global exitStatus
- exitStatus = 2
- log.err(failure.Failure())
- reactor.stop()
- raise
-
-class SSHClientFactory(protocol.ClientFactory):
- noisy = 1
-
- def stopFactory(self):
- reactor.stop()
-
- def buildProtocol(self, addr):
- return SSHClientTransport()
-
- def clientConnectionFailed(self, connector, reason):
- tkMessageBox.showwarning('TkConch','Connection Failed, Reason:\n %s: %s' % (reason.type, reason.value))
-
-class SSHClientTransport(transport.SSHClientTransport):
-
- def receiveError(self, code, desc):
- global exitStatus
- exitStatus = 'conch:\tRemote side disconnected with error code %i\nconch:\treason: %s' % (code, desc)
-
- def sendDisconnect(self, code, reason):
- global exitStatus
- exitStatus = 'conch:\tSending disconnect with error code %i\nconch:\treason: %s' % (code, reason)
- transport.SSHClientTransport.sendDisconnect(self, code, reason)
-
- def receiveDebug(self, alwaysDisplay, message, lang):
- global options
- if alwaysDisplay or options['log']:
- log.msg('Received Debug Message: %s' % message)
-
- def verifyHostKey(self, pubKey, fingerprint):
- #d = defer.Deferred()
- #d.addCallback(lambda x:defer.succeed(1))
- #d.callback(2)
- #return d
- goodKey = isInKnownHosts(options['host'], pubKey, {'known-hosts': None})
- if goodKey == 1: # good key
- return defer.succeed(1)
- elif goodKey == 2: # AAHHHHH changed
- return defer.fail(error.ConchError('bad host key'))
- else:
- if options['host'] == self.transport.getPeer()[1]:
- host = options['host']
- khHost = options['host']
- else:
- host = '%s (%s)' % (options['host'],
- self.transport.getPeer()[1])
- khHost = '%s,%s' % (options['host'],
- self.transport.getPeer()[1])
- keyType = common.getNS(pubKey)[0]
- ques = """The authenticity of host '%s' can't be established.\r
-%s key fingerprint is %s.""" % (host,
- {'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType],
- fingerprint)
- ques+='\r\nAre you sure you want to continue connecting (yes/no)? '
- return deferredAskFrame(ques, 1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)
-
- def _cbVerifyHostKey(self, ans, pubKey, khHost, keyType):
- if ans.lower() not in ('yes', 'no'):
- return deferredAskFrame("Please type 'yes' or 'no': ",1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType)
- if ans.lower() == 'no':
- frame.write('Host key verification failed.\r\n')
- raise error.ConchError('bad host key')
- try:
- frame.write("Warning: Permanently added '%s' (%s) to the list of known hosts.\r\n" % (khHost, {'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType]))
- known_hosts = open(os.path.expanduser('~/.ssh/known_hosts'), 'a')
- encodedKey = base64.encodestring(pubKey).replace('\n', '')
- known_hosts.write('\n%s %s %s' % (khHost, keyType, encodedKey))
- known_hosts.close()
- except:
- log.deferr()
- raise error.ConchError
-
- def connectionSecure(self):
- if options['user']:
- user = options['user']
- else:
- user = getpass.getuser()
- self.requestService(SSHUserAuthClient(user, SSHConnection()))
-
-class SSHUserAuthClient(userauth.SSHUserAuthClient):
- usedFiles = []
-
- def getPassword(self, prompt = None):
- if not prompt:
- prompt = "%s@%s's password: " % (self.user, options['host'])
- return deferredAskFrame(prompt,0)
-
- def getPublicKey(self):
- files = [x for x in options.identitys if x not in self.usedFiles]
- if not files:
- return None
- file = files[0]
- log.msg(file)
- self.usedFiles.append(file)
- file = os.path.expanduser(file)
- file += '.pub'
- if not os.path.exists(file):
- return
- try:
- return keys.Key.fromFile(file).blob()
- except:
- return self.getPublicKey() # try again
-
- def getPrivateKey(self):
- file = os.path.expanduser(self.usedFiles[-1])
- if not os.path.exists(file):
- return None
- try:
- return defer.succeed(keys.Key.fromFile(file).keyObject)
- except keys.BadKeyError, e:
- if e.args[0] == 'encrypted key with no password':
- prompt = "Enter passphrase for key '%s': " % \
- self.usedFiles[-1]
- return deferredAskFrame(prompt, 0).addCallback(self._cbGetPrivateKey, 0)
- def _cbGetPrivateKey(self, ans, count):
- file = os.path.expanduser(self.usedFiles[-1])
- try:
- return keys.Key.fromFile(file, password = ans).keyObject
- except keys.BadKeyError:
- if count == 2:
- raise
- prompt = "Enter passphrase for key '%s': " % \
- self.usedFiles[-1]
- return deferredAskFrame(prompt, 0).addCallback(self._cbGetPrivateKey, count+1)
-
-class SSHConnection(connection.SSHConnection):
- def serviceStarted(self):
- if not options['noshell']:
- self.openChannel(SSHSession())
- if options.localForwards:
- for localPort, hostport in options.localForwards:
- reactor.listenTCP(localPort,
- forwarding.SSHListenForwardingFactory(self,
- hostport,
- forwarding.SSHListenClientForwardingChannel))
- if options.remoteForwards:
- for remotePort, hostport in options.remoteForwards:
- log.msg('asking for remote forwarding for %s:%s' %
- (remotePort, hostport))
- data = forwarding.packGlobal_tcpip_forward(
- ('0.0.0.0', remotePort))
- d = self.sendGlobalRequest('tcpip-forward', data)
- self.remoteForwards[remotePort] = hostport
-
-class SSHSession(channel.SSHChannel):
-
- name = 'session'
-
- def channelOpen(self, foo):
- #global globalSession
- #globalSession = self
- # turn off local echo
- self.escapeMode = 1
- c = session.SSHSessionClient()
- if options['escape']:
- c.dataReceived = self.handleInput
- else:
- c.dataReceived = self.write
- c.connectionLost = self.sendEOF
- frame.callback = c.dataReceived
- frame.canvas.focus_force()
- if options['subsystem']:
- self.conn.sendRequest(self, 'subsystem', \
- common.NS(options['command']))
- elif options['command']:
- if options['tty']:
- term = os.environ.get('TERM', 'xterm')
- #winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
- winSize = (25,80,0,0) #struct.unpack('4H', winsz)
- ptyReqData = session.packRequest_pty_req(term, winSize, '')
- self.conn.sendRequest(self, 'pty-req', ptyReqData)
- self.conn.sendRequest(self, 'exec', \
- common.NS(options['command']))
- else:
- if not options['notty']:
- term = os.environ.get('TERM', 'xterm')
- #winsz = fcntl.ioctl(fd, tty.TIOCGWINSZ, '12345678')
- winSize = (25,80,0,0) #struct.unpack('4H', winsz)
- ptyReqData = session.packRequest_pty_req(term, winSize, '')
- self.conn.sendRequest(self, 'pty-req', ptyReqData)
- self.conn.sendRequest(self, 'shell', '')
- self.conn.transport.transport.setTcpNoDelay(1)
-
- def handleInput(self, char):
- #log.msg('handling %s' % repr(char))
- if char in ('\n', '\r'):
- self.escapeMode = 1
- self.write(char)
- elif self.escapeMode == 1 and char == options['escape']:
- self.escapeMode = 2
- elif self.escapeMode == 2:
- self.escapeMode = 1 # so we can chain escapes together
- if char == '.': # disconnect
- log.msg('disconnecting from escape')
- reactor.stop()
- return
- elif char == '\x1a': # ^Z, suspend
- # following line courtesy of Erwin@freenode
- os.kill(os.getpid(), signal.SIGSTOP)
- return
- elif char == 'R': # rekey connection
- log.msg('rekeying connection')
- self.conn.transport.sendKexInit()
- return
- self.write('~' + char)
- else:
- self.escapeMode = 0
- self.write(char)
-
- def dataReceived(self, data):
- if options['ansilog']:
- print repr(data)
- frame.write(data)
-
- def extReceived(self, t, data):
- if t==connection.EXTENDED_DATA_STDERR:
- log.msg('got %s stderr data' % len(data))
- sys.stderr.write(data)
- sys.stderr.flush()
-
- def eofReceived(self):
- log.msg('got eof')
- sys.stdin.close()
-
- def closed(self):
- log.msg('closed %s' % self)
- if len(self.conn.channels) == 1: # just us left
- reactor.stop()
-
- def request_exit_status(self, data):
- global exitStatus
- exitStatus = int(struct.unpack('>L', data)[0])
- log.msg('exit status: %s' % exitStatus)
-
- def sendEOF(self):
- self.conn.sendEOF(self)
-
-if __name__=="__main__":
- run()
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/__init__.py
deleted file mode 100644
index 4b7f024..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/__init__.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-"""
-An SSHv2 implementation for Twisted. Part of the Twisted.Conch package.
-
-Maintainer: Paul Swartz
-"""
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/address.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/address.py
deleted file mode 100644
index c06f2bf..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/address.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_address -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Address object for SSH network connections.
-
-Maintainer: Paul Swartz
-
-@since: 12.1
-"""
-from zope.interface import implements
-from twisted.internet.interfaces import IAddress
-from twisted.python import util
-
-
-
-class SSHTransportAddress(object, util.FancyEqMixin):
- """
- Object representing an SSH Transport endpoint.
-
- @ivar address: A instance of an object which implements I{IAddress} to
- which this transport address is connected.
- """
-
- implements(IAddress)
-
- compareAttributes = ('address',)
-
- def __init__(self, address):
- self.address = address
-
- def __repr__(self):
- return 'SSHTransportAddress(%r)' % (self.address,)
-
- def __hash__(self):
- return hash(('SSH', self.address))
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/agent.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/agent.py
deleted file mode 100644
index c1bf1a0..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/agent.py
+++ /dev/null
@@ -1,294 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Implements the SSH v2 key agent protocol. This protocol is documented in the
-SSH source code, in the file
-U{PROTOCOL.agent}.
-
-Maintainer: Paul Swartz
-"""
-
-import struct
-
-from twisted.conch.ssh.common import NS, getNS, getMP
-from twisted.conch.error import ConchError, MissingKeyStoreError
-from twisted.conch.ssh import keys
-from twisted.internet import defer, protocol
-
-
-
-class SSHAgentClient(protocol.Protocol):
- """
- The client side of the SSH agent protocol. This is equivalent to
- ssh-add(1) and can be used with either ssh-agent(1) or the SSHAgentServer
- protocol, also in this package.
- """
-
- def __init__(self):
- self.buf = ''
- self.deferreds = []
-
-
- def dataReceived(self, data):
- self.buf += data
- while 1:
- if len(self.buf) <= 4:
- return
- packLen = struct.unpack('!L', self.buf[:4])[0]
- if len(self.buf) < 4 + packLen:
- return
- packet, self.buf = self.buf[4:4 + packLen], self.buf[4 + packLen:]
- reqType = ord(packet[0])
- d = self.deferreds.pop(0)
- if reqType == AGENT_FAILURE:
- d.errback(ConchError('agent failure'))
- elif reqType == AGENT_SUCCESS:
- d.callback('')
- else:
- d.callback(packet)
-
-
- def sendRequest(self, reqType, data):
- pack = struct.pack('!LB',len(data) + 1, reqType) + data
- self.transport.write(pack)
- d = defer.Deferred()
- self.deferreds.append(d)
- return d
-
-
- def requestIdentities(self):
- """
- @return: A L{Deferred} which will fire with a list of all keys found in
- the SSH agent. The list of keys is comprised of (public key blob,
- comment) tuples.
- """
- d = self.sendRequest(AGENTC_REQUEST_IDENTITIES, '')
- d.addCallback(self._cbRequestIdentities)
- return d
-
-
- def _cbRequestIdentities(self, data):
- """
- Unpack a collection of identities into a list of tuples comprised of
- public key blobs and comments.
- """
- if ord(data[0]) != AGENT_IDENTITIES_ANSWER:
- raise ConchError('unexpected response: %i' % ord(data[0]))
- numKeys = struct.unpack('!L', data[1:5])[0]
- keys = []
- data = data[5:]
- for i in range(numKeys):
- blob, data = getNS(data)
- comment, data = getNS(data)
- keys.append((blob, comment))
- return keys
-
-
- def addIdentity(self, blob, comment = ''):
- """
- Add a private key blob to the agent's collection of keys.
- """
- req = blob
- req += NS(comment)
- return self.sendRequest(AGENTC_ADD_IDENTITY, req)
-
-
- def signData(self, blob, data):
- """
- Request that the agent sign the given C{data} with the private key
- which corresponds to the public key given by C{blob}. The private
- key should have been added to the agent already.
-
- @type blob: C{str}
- @type data: C{str}
- @return: A L{Deferred} which fires with a signature for given data
- created with the given key.
- """
- req = NS(blob)
- req += NS(data)
- req += '\000\000\000\000' # flags
- return self.sendRequest(AGENTC_SIGN_REQUEST, req).addCallback(self._cbSignData)
-
-
- def _cbSignData(self, data):
- if ord(data[0]) != AGENT_SIGN_RESPONSE:
- raise ConchError('unexpected data: %i' % ord(data[0]))
- signature = getNS(data[1:])[0]
- return signature
-
-
- def removeIdentity(self, blob):
- """
- Remove the private key corresponding to the public key in blob from the
- running agent.
- """
- req = NS(blob)
- return self.sendRequest(AGENTC_REMOVE_IDENTITY, req)
-
-
- def removeAllIdentities(self):
- """
- Remove all keys from the running agent.
- """
- return self.sendRequest(AGENTC_REMOVE_ALL_IDENTITIES, '')
-
-
-
-class SSHAgentServer(protocol.Protocol):
- """
- The server side of the SSH agent protocol. This is equivalent to
- ssh-agent(1) and can be used with either ssh-add(1) or the SSHAgentClient
- protocol, also in this package.
- """
-
- def __init__(self):
- self.buf = ''
-
-
- def dataReceived(self, data):
- self.buf += data
- while 1:
- if len(self.buf) <= 4:
- return
- packLen = struct.unpack('!L', self.buf[:4])[0]
- if len(self.buf) < 4 + packLen:
- return
- packet, self.buf = self.buf[4:4 + packLen], self.buf[4 + packLen:]
- reqType = ord(packet[0])
- reqName = messages.get(reqType, None)
- if not reqName:
- self.sendResponse(AGENT_FAILURE, '')
- else:
- f = getattr(self, 'agentc_%s' % reqName)
- if getattr(self.factory, 'keys', None) is None:
- self.sendResponse(AGENT_FAILURE, '')
- raise MissingKeyStoreError()
- f(packet[1:])
-
-
- def sendResponse(self, reqType, data):
- pack = struct.pack('!LB', len(data) + 1, reqType) + data
- self.transport.write(pack)
-
-
- def agentc_REQUEST_IDENTITIES(self, data):
- """
- Return all of the identities that have been added to the server
- """
- assert data == ''
- numKeys = len(self.factory.keys)
- resp = []
-
- resp.append(struct.pack('!L', numKeys))
- for key, comment in self.factory.keys.itervalues():
- resp.append(NS(key.blob())) # yes, wrapped in an NS
- resp.append(NS(comment))
- self.sendResponse(AGENT_IDENTITIES_ANSWER, ''.join(resp))
-
-
- def agentc_SIGN_REQUEST(self, data):
- """
- Data is a structure with a reference to an already added key object and
- some data that the clients wants signed with that key. If the key
- object wasn't loaded, return AGENT_FAILURE, else return the signature.
- """
- blob, data = getNS(data)
- if blob not in self.factory.keys:
- return self.sendResponse(AGENT_FAILURE, '')
- signData, data = getNS(data)
- assert data == '\000\000\000\000'
- self.sendResponse(AGENT_SIGN_RESPONSE, NS(self.factory.keys[blob][0].sign(signData)))
-
-
- def agentc_ADD_IDENTITY(self, data):
- """
- Adds a private key to the agent's collection of identities. On
- subsequent interactions, the private key can be accessed using only the
- corresponding public key.
- """
-
- # need to pre-read the key data so we can get past it to the comment string
- keyType, rest = getNS(data)
- if keyType == 'ssh-rsa':
- nmp = 6
- elif keyType == 'ssh-dss':
- nmp = 5
- else:
- raise keys.BadKeyError('unknown blob type: %s' % keyType)
-
- rest = getMP(rest, nmp)[-1] # ignore the key data for now, we just want the comment
- comment, rest = getNS(rest) # the comment, tacked onto the end of the key blob
-
- k = keys.Key.fromString(data, type='private_blob') # not wrapped in NS here
- self.factory.keys[k.blob()] = (k, comment)
- self.sendResponse(AGENT_SUCCESS, '')
-
-
- def agentc_REMOVE_IDENTITY(self, data):
- """
- Remove a specific key from the agent's collection of identities.
- """
- blob, _ = getNS(data)
- k = keys.Key.fromString(blob, type='blob')
- del self.factory.keys[k.blob()]
- self.sendResponse(AGENT_SUCCESS, '')
-
-
- def agentc_REMOVE_ALL_IDENTITIES(self, data):
- """
- Remove all keys from the agent's collection of identities.
- """
- assert data == ''
- self.factory.keys = {}
- self.sendResponse(AGENT_SUCCESS, '')
-
- # v1 messages that we ignore because we don't keep v1 keys
- # open-ssh sends both v1 and v2 commands, so we have to
- # do no-ops for v1 commands or we'll get "bad request" errors
-
- def agentc_REQUEST_RSA_IDENTITIES(self, data):
- """
- v1 message for listing RSA1 keys; superseded by
- agentc_REQUEST_IDENTITIES, which handles different key types.
- """
- self.sendResponse(AGENT_RSA_IDENTITIES_ANSWER, struct.pack('!L', 0))
-
-
- def agentc_REMOVE_RSA_IDENTITY(self, data):
- """
- v1 message for removing RSA1 keys; superseded by
- agentc_REMOVE_IDENTITY, which handles different key types.
- """
- self.sendResponse(AGENT_SUCCESS, '')
-
-
- def agentc_REMOVE_ALL_RSA_IDENTITIES(self, data):
- """
- v1 message for removing all RSA1 keys; superseded by
- agentc_REMOVE_ALL_IDENTITIES, which handles different key types.
- """
- self.sendResponse(AGENT_SUCCESS, '')
-
-
-AGENTC_REQUEST_RSA_IDENTITIES = 1
-AGENT_RSA_IDENTITIES_ANSWER = 2
-AGENT_FAILURE = 5
-AGENT_SUCCESS = 6
-
-AGENTC_REMOVE_RSA_IDENTITY = 8
-AGENTC_REMOVE_ALL_RSA_IDENTITIES = 9
-
-AGENTC_REQUEST_IDENTITIES = 11
-AGENT_IDENTITIES_ANSWER = 12
-AGENTC_SIGN_REQUEST = 13
-AGENT_SIGN_RESPONSE = 14
-AGENTC_ADD_IDENTITY = 17
-AGENTC_REMOVE_IDENTITY = 18
-AGENTC_REMOVE_ALL_IDENTITIES = 19
-
-messages = {}
-for name, value in locals().copy().items():
- if name[:7] == 'AGENTC_':
- messages[value] = name[7:] # doesn't handle doubles
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/channel.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/channel.py
deleted file mode 100644
index f498aec..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/channel.py
+++ /dev/null
@@ -1,281 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_channel -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-"""
-The parent class for all the SSH Channels. Currently implemented channels
-are session. direct-tcp, and forwarded-tcp.
-
-Maintainer: Paul Swartz
-"""
-
-from twisted.python import log
-from twisted.internet import interfaces
-from zope.interface import implements
-
-
-class SSHChannel(log.Logger):
- """
- A class that represents a multiplexed channel over an SSH connection.
- The channel has a local window which is the maximum amount of data it will
- receive, and a remote which is the maximum amount of data the remote side
- will accept. There is also a maximum packet size for any individual data
- packet going each way.
-
- @ivar name: the name of the channel.
- @type name: C{str}
- @ivar localWindowSize: the maximum size of the local window in bytes.
- @type localWindowSize: C{int}
- @ivar localWindowLeft: how many bytes are left in the local window.
- @type localWindowLeft: C{int}
- @ivar localMaxPacket: the maximum size of packet we will accept in bytes.
- @type localMaxPacket: C{int}
- @ivar remoteWindowLeft: how many bytes are left in the remote window.
- @type remoteWindowLeft: C{int}
- @ivar remoteMaxPacket: the maximum size of a packet the remote side will
- accept in bytes.
- @type remoteMaxPacket: C{int}
- @ivar conn: the connection this channel is multiplexed through.
- @type conn: L{SSHConnection}
- @ivar data: any data to send to the other size when the channel is
- requested.
- @type data: C{str}
- @ivar avatar: an avatar for the logged-in user (if a server channel)
- @ivar localClosed: True if we aren't accepting more data.
- @type localClosed: C{bool}
- @ivar remoteClosed: True if the other size isn't accepting more data.
- @type remoteClosed: C{bool}
- """
-
- implements(interfaces.ITransport)
-
- name = None # only needed for client channels
-
- def __init__(self, localWindow = 0, localMaxPacket = 0,
- remoteWindow = 0, remoteMaxPacket = 0,
- conn = None, data=None, avatar = None):
- self.localWindowSize = localWindow or 131072
- self.localWindowLeft = self.localWindowSize
- self.localMaxPacket = localMaxPacket or 32768
- self.remoteWindowLeft = remoteWindow
- self.remoteMaxPacket = remoteMaxPacket
- self.areWriting = 1
- self.conn = conn
- self.data = data
- self.avatar = avatar
- self.specificData = ''
- self.buf = ''
- self.extBuf = []
- self.closing = 0
- self.localClosed = 0
- self.remoteClosed = 0
- self.id = None # gets set later by SSHConnection
-
- def __str__(self):
- return '' % (self.name,
- self.localWindowLeft, self.remoteWindowLeft)
-
- def logPrefix(self):
- id = (self.id is not None and str(self.id)) or "unknown"
- return "SSHChannel %s (%s) on %s" % (self.name, id,
- self.conn.logPrefix())
-
- def channelOpen(self, specificData):
- """
- Called when the channel is opened. specificData is any data that the
- other side sent us when opening the channel.
-
- @type specificData: C{str}
- """
- log.msg('channel open')
-
- def openFailed(self, reason):
- """
- Called when the the open failed for some reason.
- reason.desc is a string descrption, reason.code the the SSH error code.
-
- @type reason: L{error.ConchError}
- """
- log.msg('other side refused open\nreason: %s'% reason)
-
- def addWindowBytes(self, bytes):
- """
- Called when bytes are added to the remote window. By default it clears
- the data buffers.
-
- @type bytes: C{int}
- """
- self.remoteWindowLeft = self.remoteWindowLeft+bytes
- if not self.areWriting and not self.closing:
- self.areWriting = True
- self.startWriting()
- if self.buf:
- b = self.buf
- self.buf = ''
- self.write(b)
- if self.extBuf:
- b = self.extBuf
- self.extBuf = []
- for (type, data) in b:
- self.writeExtended(type, data)
-
- def requestReceived(self, requestType, data):
- """
- Called when a request is sent to this channel. By default it delegates
- to self.request_.
- If this function returns true, the request succeeded, otherwise it
- failed.
-
- @type requestType: C{str}
- @type data: C{str}
- @rtype: C{bool}
- """
- foo = requestType.replace('-', '_')
- f = getattr(self, 'request_%s'%foo, None)
- if f:
- return f(data)
- log.msg('unhandled request for %s'%requestType)
- return 0
-
- def dataReceived(self, data):
- """
- Called when we receive data.
-
- @type data: C{str}
- """
- log.msg('got data %s'%repr(data))
-
- def extReceived(self, dataType, data):
- """
- Called when we receive extended data (usually standard error).
-
- @type dataType: C{int}
- @type data: C{str}
- """
- log.msg('got extended data %s %s'%(dataType, repr(data)))
-
- def eofReceived(self):
- """
- Called when the other side will send no more data.
- """
- log.msg('remote eof')
-
- def closeReceived(self):
- """
- Called when the other side has closed the channel.
- """
- log.msg('remote close')
- self.loseConnection()
-
- def closed(self):
- """
- Called when the channel is closed. This means that both our side and
- the remote side have closed the channel.
- """
- log.msg('closed')
-
- # transport stuff
- def write(self, data):
- """
- Write some data to the channel. If there is not enough remote window
- available, buffer until it is. Otherwise, split the data into
- packets of length remoteMaxPacket and send them.
-
- @type data: C{str}
- """
- if self.buf:
- self.buf += data
- return
- top = len(data)
- if top > self.remoteWindowLeft:
- data, self.buf = (data[:self.remoteWindowLeft],
- data[self.remoteWindowLeft:])
- self.areWriting = 0
- self.stopWriting()
- top = self.remoteWindowLeft
- rmp = self.remoteMaxPacket
- write = self.conn.sendData
- r = range(0, top, rmp)
- for offset in r:
- write(self, data[offset: offset+rmp])
- self.remoteWindowLeft -= top
- if self.closing and not self.buf:
- self.loseConnection() # try again
-
- def writeExtended(self, dataType, data):
- """
- Send extended data to this channel. If there is not enough remote
- window available, buffer until there is. Otherwise, split the data
- into packets of length remoteMaxPacket and send them.
-
- @type dataType: C{int}
- @type data: C{str}
- """
- if self.extBuf:
- if self.extBuf[-1][0] == dataType:
- self.extBuf[-1][1] += data
- else:
- self.extBuf.append([dataType, data])
- return
- if len(data) > self.remoteWindowLeft:
- data, self.extBuf = (data[:self.remoteWindowLeft],
- [[dataType, data[self.remoteWindowLeft:]]])
- self.areWriting = 0
- self.stopWriting()
- while len(data) > self.remoteMaxPacket:
- self.conn.sendExtendedData(self, dataType,
- data[:self.remoteMaxPacket])
- data = data[self.remoteMaxPacket:]
- self.remoteWindowLeft -= self.remoteMaxPacket
- if data:
- self.conn.sendExtendedData(self, dataType, data)
- self.remoteWindowLeft -= len(data)
- if self.closing:
- self.loseConnection() # try again
-
- def writeSequence(self, data):
- """
- Part of the Transport interface. Write a list of strings to the
- channel.
-
- @type data: C{list} of C{str}
- """
- self.write(''.join(data))
-
- def loseConnection(self):
- """
- Close the channel if there is no buferred data. Otherwise, note the
- request and return.
- """
- self.closing = 1
- if not self.buf and not self.extBuf:
- self.conn.sendClose(self)
-
- def getPeer(self):
- """
- Return a tuple describing the other side of the connection.
-
- @rtype: C{tuple}
- """
- return('SSH', )+self.conn.transport.getPeer()
-
- def getHost(self):
- """
- Return a tuple describing our side of the connection.
-
- @rtype: C{tuple}
- """
- return('SSH', )+self.conn.transport.getHost()
-
- def stopWriting(self):
- """
- Called when the remote buffer is full, as a hint to stop writing.
- This can be ignored, but it can be helpful.
- """
-
- def startWriting(self):
- """
- Called when the remote buffer has more room, as a hint to continue
- writing.
- """
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/common.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/common.py
deleted file mode 100644
index 3afa341..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/common.py
+++ /dev/null
@@ -1,117 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_ssh -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Common functions for the SSH classes.
-
-Maintainer: Paul Swartz
-"""
-
-import struct, warnings, __builtin__
-
-try:
- from Crypto import Util
-except ImportError:
- warnings.warn("PyCrypto not installed, but continuing anyways!",
- RuntimeWarning)
-
-from twisted.python import randbytes
-
-
-def NS(t):
- """
- net string
- """
- return struct.pack('!L',len(t)) + t
-
-def getNS(s, count=1):
- """
- get net string
- """
- ns = []
- c = 0
- for i in range(count):
- l, = struct.unpack('!L',s[c:c+4])
- ns.append(s[c+4:4+l+c])
- c += 4 + l
- return tuple(ns) + (s[c:],)
-
-def MP(number):
- if number==0: return '\000'*4
- assert number>0
- bn = Util.number.long_to_bytes(number)
- if ord(bn[0])&128:
- bn = '\000' + bn
- return struct.pack('>L',len(bn)) + bn
-
-def getMP(data, count=1):
- """
- Get multiple precision integer out of the string. A multiple precision
- integer is stored as a 4-byte length followed by length bytes of the
- integer. If count is specified, get count integers out of the string.
- The return value is a tuple of count integers followed by the rest of
- the data.
- """
- mp = []
- c = 0
- for i in range(count):
- length, = struct.unpack('>L',data[c:c+4])
- mp.append(Util.number.bytes_to_long(data[c+4:c+4+length]))
- c += 4 + length
- return tuple(mp) + (data[c:],)
-
-def _MPpow(x, y, z):
- """return the MP version of (x**y)%z
- """
- return MP(pow(x,y,z))
-
-def ffs(c, s):
- """
- first from second
- goes through the first list, looking for items in the second, returns the first one
- """
- for i in c:
- if i in s: return i
-
-getMP_py = getMP
-MP_py = MP
-_MPpow_py = _MPpow
-pyPow = pow
-
-def _fastgetMP(data, count=1):
- mp = []
- c = 0
- for i in range(count):
- length = struct.unpack('!L', data[c:c+4])[0]
- mp.append(long(gmpy.mpz(data[c + 4:c + 4 + length][::-1] + '\x00', 256)))
- c += length + 4
- return tuple(mp) + (data[c:],)
-
-def _fastMP(i):
- i2 = gmpy.mpz(i).binary()[::-1]
- return struct.pack('!L', len(i2)) + i2
-
-def _fastMPpow(x, y, z=None):
- r = pyPow(gmpy.mpz(x),y,z).binary()[::-1]
- return struct.pack('!L', len(r)) + r
-
-def install():
- global getMP, MP, _MPpow
- getMP = _fastgetMP
- MP = _fastMP
- _MPpow = _fastMPpow
- # XXX: We override builtin pow so that PyCrypto can benefit from gmpy too.
- def _fastpow(x, y, z=None, mpz=gmpy.mpz):
- if type(x) in (long, int):
- x = mpz(x)
- return pyPow(x, y, z)
- __builtin__.pow = _fastpow # evil evil
-
-try:
- import gmpy
- install()
-except ImportError:
- pass
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/connection.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/connection.py
deleted file mode 100644
index badd6cd..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/connection.py
+++ /dev/null
@@ -1,636 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_connection -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-This module contains the implementation of the ssh-connection service, which
-allows access to the shell and port-forwarding.
-
-Maintainer: Paul Swartz
-"""
-
-import struct
-
-from twisted.conch.ssh import service, common
-from twisted.conch import error
-from twisted.internet import defer
-from twisted.python import log
-
-class SSHConnection(service.SSHService):
- """
- An implementation of the 'ssh-connection' service. It is used to
- multiplex multiple channels over the single SSH connection.
-
- @ivar localChannelID: the next number to use as a local channel ID.
- @type localChannelID: C{int}
- @ivar channels: a C{dict} mapping a local channel ID to C{SSHChannel}
- subclasses.
- @type channels: C{dict}
- @ivar localToRemoteChannel: a C{dict} mapping a local channel ID to a
- remote channel ID.
- @type localToRemoteChannel: C{dict}
- @ivar channelsToRemoteChannel: a C{dict} mapping a C{SSHChannel} subclass
- to remote channel ID.
- @type channelsToRemoteChannel: C{dict}
- @ivar deferreds: a C{dict} mapping a local channel ID to a C{list} of
- C{Deferreds} for outstanding channel requests. Also, the 'global'
- key stores the C{list} of pending global request C{Deferred}s.
- """
- name = 'ssh-connection'
-
- def __init__(self):
- self.localChannelID = 0 # this is the current # to use for channel ID
- self.localToRemoteChannel = {} # local channel ID -> remote channel ID
- self.channels = {} # local channel ID -> subclass of SSHChannel
- self.channelsToRemoteChannel = {} # subclass of SSHChannel ->
- # remote channel ID
- self.deferreds = {"global": []} # local channel -> list of deferreds
- # for pending requests or 'global' -> list of
- # deferreds for global requests
- self.transport = None # gets set later
-
-
- def serviceStarted(self):
- if hasattr(self.transport, 'avatar'):
- self.transport.avatar.conn = self
-
-
- def serviceStopped(self):
- """
- Called when the connection is stopped.
- """
- map(self.channelClosed, self.channels.values())
- self._cleanupGlobalDeferreds()
-
-
- def _cleanupGlobalDeferreds(self):
- """
- All pending requests that have returned a deferred must be errbacked
- when this service is stopped, otherwise they might be left uncalled and
- uncallable.
- """
- for d in self.deferreds["global"]:
- d.errback(error.ConchError("Connection stopped."))
- del self.deferreds["global"][:]
-
-
- # packet methods
- def ssh_GLOBAL_REQUEST(self, packet):
- """
- The other side has made a global request. Payload::
- string request type
- bool want reply
-
-
- This dispatches to self.gotGlobalRequest.
- """
- requestType, rest = common.getNS(packet)
- wantReply, rest = ord(rest[0]), rest[1:]
- ret = self.gotGlobalRequest(requestType, rest)
- if wantReply:
- reply = MSG_REQUEST_FAILURE
- data = ''
- if ret:
- reply = MSG_REQUEST_SUCCESS
- if isinstance(ret, (tuple, list)):
- data = ret[1]
- self.transport.sendPacket(reply, data)
-
- def ssh_REQUEST_SUCCESS(self, packet):
- """
- Our global request succeeded. Get the appropriate Deferred and call
- it back with the packet we received.
- """
- log.msg('RS')
- self.deferreds['global'].pop(0).callback(packet)
-
- def ssh_REQUEST_FAILURE(self, packet):
- """
- Our global request failed. Get the appropriate Deferred and errback
- it with the packet we received.
- """
- log.msg('RF')
- self.deferreds['global'].pop(0).errback(
- error.ConchError('global request failed', packet))
-
- def ssh_CHANNEL_OPEN(self, packet):
- """
- The other side wants to get a channel. Payload::
- string channel name
- uint32 remote channel number
- uint32 remote window size
- uint32 remote maximum packet size
-
-
- We get a channel from self.getChannel(), give it a local channel number
- and notify the other side. Then notify the channel by calling its
- channelOpen method.
- """
- channelType, rest = common.getNS(packet)
- senderChannel, windowSize, maxPacket = struct.unpack('>3L', rest[:12])
- packet = rest[12:]
- try:
- channel = self.getChannel(channelType, windowSize, maxPacket,
- packet)
- localChannel = self.localChannelID
- self.localChannelID += 1
- channel.id = localChannel
- self.channels[localChannel] = channel
- self.channelsToRemoteChannel[channel] = senderChannel
- self.localToRemoteChannel[localChannel] = senderChannel
- self.transport.sendPacket(MSG_CHANNEL_OPEN_CONFIRMATION,
- struct.pack('>4L', senderChannel, localChannel,
- channel.localWindowSize,
- channel.localMaxPacket)+channel.specificData)
- log.callWithLogger(channel, channel.channelOpen, packet)
- except Exception, e:
- log.err(e, 'channel open failed')
- if isinstance(e, error.ConchError):
- textualInfo, reason = e.args
- if isinstance(textualInfo, (int, long)):
- # See #3657 and #3071
- textualInfo, reason = reason, textualInfo
- else:
- reason = OPEN_CONNECT_FAILED
- textualInfo = "unknown failure"
- self.transport.sendPacket(
- MSG_CHANNEL_OPEN_FAILURE,
- struct.pack('>2L', senderChannel, reason) +
- common.NS(textualInfo) + common.NS(''))
-
- def ssh_CHANNEL_OPEN_CONFIRMATION(self, packet):
- """
- The other side accepted our MSG_CHANNEL_OPEN request. Payload::
- uint32 local channel number
- uint32 remote channel number
- uint32 remote window size
- uint32 remote maximum packet size
-
-
- Find the channel using the local channel number and notify its
- channelOpen method.
- """
- (localChannel, remoteChannel, windowSize,
- maxPacket) = struct.unpack('>4L', packet[: 16])
- specificData = packet[16:]
- channel = self.channels[localChannel]
- channel.conn = self
- self.localToRemoteChannel[localChannel] = remoteChannel
- self.channelsToRemoteChannel[channel] = remoteChannel
- channel.remoteWindowLeft = windowSize
- channel.remoteMaxPacket = maxPacket
- log.callWithLogger(channel, channel.channelOpen, specificData)
-
- def ssh_CHANNEL_OPEN_FAILURE(self, packet):
- """
- The other side did not accept our MSG_CHANNEL_OPEN request. Payload::
- uint32 local channel number
- uint32 reason code
- string reason description
-
- Find the channel using the local channel number and notify it by
- calling its openFailed() method.
- """
- localChannel, reasonCode = struct.unpack('>2L', packet[:8])
- reasonDesc = common.getNS(packet[8:])[0]
- channel = self.channels[localChannel]
- del self.channels[localChannel]
- channel.conn = self
- reason = error.ConchError(reasonDesc, reasonCode)
- log.callWithLogger(channel, channel.openFailed, reason)
-
- def ssh_CHANNEL_WINDOW_ADJUST(self, packet):
- """
- The other side is adding bytes to its window. Payload::
- uint32 local channel number
- uint32 bytes to add
-
- Call the channel's addWindowBytes() method to add new bytes to the
- remote window.
- """
- localChannel, bytesToAdd = struct.unpack('>2L', packet[:8])
- channel = self.channels[localChannel]
- log.callWithLogger(channel, channel.addWindowBytes, bytesToAdd)
-
- def ssh_CHANNEL_DATA(self, packet):
- """
- The other side is sending us data. Payload::
- uint32 local channel number
- string data
-
- Check to make sure the other side hasn't sent too much data (more
- than what's in the window, or more than the maximum packet size). If
- they have, close the channel. Otherwise, decrease the available
- window and pass the data to the channel's dataReceived().
- """
- localChannel, dataLength = struct.unpack('>2L', packet[:8])
- channel = self.channels[localChannel]
- # XXX should this move to dataReceived to put client in charge?
- if (dataLength > channel.localWindowLeft or
- dataLength > channel.localMaxPacket): # more data than we want
- log.callWithLogger(channel, log.msg, 'too much data')
- self.sendClose(channel)
- return
- #packet = packet[:channel.localWindowLeft+4]
- data = common.getNS(packet[4:])[0]
- channel.localWindowLeft -= dataLength
- if channel.localWindowLeft < channel.localWindowSize // 2:
- self.adjustWindow(channel, channel.localWindowSize - \
- channel.localWindowLeft)
- #log.msg('local window left: %s/%s' % (channel.localWindowLeft,
- # channel.localWindowSize))
- log.callWithLogger(channel, channel.dataReceived, data)
-
- def ssh_CHANNEL_EXTENDED_DATA(self, packet):
- """
- The other side is sending us exteneded data. Payload::
- uint32 local channel number
- uint32 type code
- string data
-
- Check to make sure the other side hasn't sent too much data (more
- than what's in the window, or or than the maximum packet size). If
- they have, close the channel. Otherwise, decrease the available
- window and pass the data and type code to the channel's
- extReceived().
- """
- localChannel, typeCode, dataLength = struct.unpack('>3L', packet[:12])
- channel = self.channels[localChannel]
- if (dataLength > channel.localWindowLeft or
- dataLength > channel.localMaxPacket):
- log.callWithLogger(channel, log.msg, 'too much extdata')
- self.sendClose(channel)
- return
- data = common.getNS(packet[8:])[0]
- channel.localWindowLeft -= dataLength
- if channel.localWindowLeft < channel.localWindowSize // 2:
- self.adjustWindow(channel, channel.localWindowSize -
- channel.localWindowLeft)
- log.callWithLogger(channel, channel.extReceived, typeCode, data)
-
- def ssh_CHANNEL_EOF(self, packet):
- """
- The other side is not sending any more data. Payload::
- uint32 local channel number
-
- Notify the channel by calling its eofReceived() method.
- """
- localChannel = struct.unpack('>L', packet[:4])[0]
- channel = self.channels[localChannel]
- log.callWithLogger(channel, channel.eofReceived)
-
- def ssh_CHANNEL_CLOSE(self, packet):
- """
- The other side is closing its end; it does not want to receive any
- more data. Payload::
- uint32 local channel number
-
- Notify the channnel by calling its closeReceived() method. If
- the channel has also sent a close message, call self.channelClosed().
- """
- localChannel = struct.unpack('>L', packet[:4])[0]
- channel = self.channels[localChannel]
- log.callWithLogger(channel, channel.closeReceived)
- channel.remoteClosed = True
- if channel.localClosed and channel.remoteClosed:
- self.channelClosed(channel)
-
- def ssh_CHANNEL_REQUEST(self, packet):
- """
- The other side is sending a request to a channel. Payload::
- uint32 local channel number
- string request name
- bool want reply
-
-
- Pass the message to the channel's requestReceived method. If the
- other side wants a reply, add callbacks which will send the
- reply.
- """
- localChannel = struct.unpack('>L', packet[:4])[0]
- requestType, rest = common.getNS(packet[4:])
- wantReply = ord(rest[0])
- channel = self.channels[localChannel]
- d = defer.maybeDeferred(log.callWithLogger, channel,
- channel.requestReceived, requestType, rest[1:])
- if wantReply:
- d.addCallback(self._cbChannelRequest, localChannel)
- d.addErrback(self._ebChannelRequest, localChannel)
- return d
-
- def _cbChannelRequest(self, result, localChannel):
- """
- Called back if the other side wanted a reply to a channel request. If
- the result is true, send a MSG_CHANNEL_SUCCESS. Otherwise, raise
- a C{error.ConchError}
-
- @param result: the value returned from the channel's requestReceived()
- method. If it's False, the request failed.
- @type result: C{bool}
- @param localChannel: the local channel ID of the channel to which the
- request was made.
- @type localChannel: C{int}
- @raises ConchError: if the result is False.
- """
- if not result:
- raise error.ConchError('failed request')
- self.transport.sendPacket(MSG_CHANNEL_SUCCESS, struct.pack('>L',
- self.localToRemoteChannel[localChannel]))
-
- def _ebChannelRequest(self, result, localChannel):
- """
- Called if the other wisde wanted a reply to the channel requeset and
- the channel request failed.
-
- @param result: a Failure, but it's not used.
- @param localChannel: the local channel ID of the channel to which the
- request was made.
- @type localChannel: C{int}
- """
- self.transport.sendPacket(MSG_CHANNEL_FAILURE, struct.pack('>L',
- self.localToRemoteChannel[localChannel]))
-
- def ssh_CHANNEL_SUCCESS(self, packet):
- """
- Our channel request to the other other side succeeded. Payload::
- uint32 local channel number
-
- Get the C{Deferred} out of self.deferreds and call it back.
- """
- localChannel = struct.unpack('>L', packet[:4])[0]
- if self.deferreds.get(localChannel):
- d = self.deferreds[localChannel].pop(0)
- log.callWithLogger(self.channels[localChannel],
- d.callback, '')
-
- def ssh_CHANNEL_FAILURE(self, packet):
- """
- Our channel request to the other side failed. Payload::
- uint32 local channel number
-
- Get the C{Deferred} out of self.deferreds and errback it with a
- C{error.ConchError}.
- """
- localChannel = struct.unpack('>L', packet[:4])[0]
- if self.deferreds.get(localChannel):
- d = self.deferreds[localChannel].pop(0)
- log.callWithLogger(self.channels[localChannel],
- d.errback,
- error.ConchError('channel request failed'))
-
- # methods for users of the connection to call
-
- def sendGlobalRequest(self, request, data, wantReply=0):
- """
- Send a global request for this connection. Current this is only used
- for remote->local TCP forwarding.
-
- @type request: C{str}
- @type data: C{str}
- @type wantReply: C{bool}
- @rtype C{Deferred}/C{None}
- """
- self.transport.sendPacket(MSG_GLOBAL_REQUEST,
- common.NS(request)
- + (wantReply and '\xff' or '\x00')
- + data)
- if wantReply:
- d = defer.Deferred()
- self.deferreds['global'].append(d)
- return d
-
- def openChannel(self, channel, extra=''):
- """
- Open a new channel on this connection.
-
- @type channel: subclass of C{SSHChannel}
- @type extra: C{str}
- """
- log.msg('opening channel %s with %s %s'%(self.localChannelID,
- channel.localWindowSize, channel.localMaxPacket))
- self.transport.sendPacket(MSG_CHANNEL_OPEN, common.NS(channel.name)
- + struct.pack('>3L', self.localChannelID,
- channel.localWindowSize, channel.localMaxPacket)
- + extra)
- channel.id = self.localChannelID
- self.channels[self.localChannelID] = channel
- self.localChannelID += 1
-
- def sendRequest(self, channel, requestType, data, wantReply=0):
- """
- Send a request to a channel.
-
- @type channel: subclass of C{SSHChannel}
- @type requestType: C{str}
- @type data: C{str}
- @type wantReply: C{bool}
- @rtype C{Deferred}/C{None}
- """
- if channel.localClosed:
- return
- log.msg('sending request %s' % requestType)
- self.transport.sendPacket(MSG_CHANNEL_REQUEST, struct.pack('>L',
- self.channelsToRemoteChannel[channel])
- + common.NS(requestType)+chr(wantReply)
- + data)
- if wantReply:
- d = defer.Deferred()
- self.deferreds.setdefault(channel.id, []).append(d)
- return d
-
- def adjustWindow(self, channel, bytesToAdd):
- """
- Tell the other side that we will receive more data. This should not
- normally need to be called as it is managed automatically.
-
- @type channel: subclass of L{SSHChannel}
- @type bytesToAdd: C{int}
- """
- if channel.localClosed:
- return # we're already closed
- self.transport.sendPacket(MSG_CHANNEL_WINDOW_ADJUST, struct.pack('>2L',
- self.channelsToRemoteChannel[channel],
- bytesToAdd))
- log.msg('adding %i to %i in channel %i' % (bytesToAdd,
- channel.localWindowLeft, channel.id))
- channel.localWindowLeft += bytesToAdd
-
- def sendData(self, channel, data):
- """
- Send data to a channel. This should not normally be used: instead use
- channel.write(data) as it manages the window automatically.
-
- @type channel: subclass of L{SSHChannel}
- @type data: C{str}
- """
- if channel.localClosed:
- return # we're already closed
- self.transport.sendPacket(MSG_CHANNEL_DATA, struct.pack('>L',
- self.channelsToRemoteChannel[channel]) +
- common.NS(data))
-
- def sendExtendedData(self, channel, dataType, data):
- """
- Send extended data to a channel. This should not normally be used:
- instead use channel.writeExtendedData(data, dataType) as it manages
- the window automatically.
-
- @type channel: subclass of L{SSHChannel}
- @type dataType: C{int}
- @type data: C{str}
- """
- if channel.localClosed:
- return # we're already closed
- self.transport.sendPacket(MSG_CHANNEL_EXTENDED_DATA, struct.pack('>2L',
- self.channelsToRemoteChannel[channel],dataType) \
- + common.NS(data))
-
- def sendEOF(self, channel):
- """
- Send an EOF (End of File) for a channel.
-
- @type channel: subclass of L{SSHChannel}
- """
- if channel.localClosed:
- return # we're already closed
- log.msg('sending eof')
- self.transport.sendPacket(MSG_CHANNEL_EOF, struct.pack('>L',
- self.channelsToRemoteChannel[channel]))
-
- def sendClose(self, channel):
- """
- Close a channel.
-
- @type channel: subclass of L{SSHChannel}
- """
- if channel.localClosed:
- return # we're already closed
- log.msg('sending close %i' % channel.id)
- self.transport.sendPacket(MSG_CHANNEL_CLOSE, struct.pack('>L',
- self.channelsToRemoteChannel[channel]))
- channel.localClosed = True
- if channel.localClosed and channel.remoteClosed:
- self.channelClosed(channel)
-
- # methods to override
- def getChannel(self, channelType, windowSize, maxPacket, data):
- """
- The other side requested a channel of some sort.
- channelType is the type of channel being requested,
- windowSize is the initial size of the remote window,
- maxPacket is the largest packet we should send,
- data is any other packet data (often nothing).
-
- We return a subclass of L{SSHChannel}.
-
- By default, this dispatches to a method 'channel_channelType' with any
- non-alphanumerics in the channelType replace with _'s. If it cannot
- find a suitable method, it returns an OPEN_UNKNOWN_CHANNEL_TYPE error.
- The method is called with arguments of windowSize, maxPacket, data.
-
- @type channelType: C{str}
- @type windowSize: C{int}
- @type maxPacket: C{int}
- @type data: C{str}
- @rtype: subclass of L{SSHChannel}/C{tuple}
- """
- log.msg('got channel %s request' % channelType)
- if hasattr(self.transport, "avatar"): # this is a server!
- chan = self.transport.avatar.lookupChannel(channelType,
- windowSize,
- maxPacket,
- data)
- else:
- channelType = channelType.translate(TRANSLATE_TABLE)
- f = getattr(self, 'channel_%s' % channelType, None)
- if f is not None:
- chan = f(windowSize, maxPacket, data)
- else:
- chan = None
- if chan is None:
- raise error.ConchError('unknown channel',
- OPEN_UNKNOWN_CHANNEL_TYPE)
- else:
- chan.conn = self
- return chan
-
- def gotGlobalRequest(self, requestType, data):
- """
- We got a global request. pretty much, this is just used by the client
- to request that we forward a port from the server to the client.
- Returns either:
- - 1: request accepted
- - 1, : request accepted with request specific data
- - 0: request denied
-
- By default, this dispatches to a method 'global_requestType' with
- -'s in requestType replaced with _'s. The found method is passed data.
- If this method cannot be found, this method returns 0. Otherwise, it
- returns the return value of that method.
-
- @type requestType: C{str}
- @type data: C{str}
- @rtype: C{int}/C{tuple}
- """
- log.msg('got global %s request' % requestType)
- if hasattr(self.transport, 'avatar'): # this is a server!
- return self.transport.avatar.gotGlobalRequest(requestType, data)
-
- requestType = requestType.replace('-','_')
- f = getattr(self, 'global_%s' % requestType, None)
- if not f:
- return 0
- return f(data)
-
- def channelClosed(self, channel):
- """
- Called when a channel is closed.
- It clears the local state related to the channel, and calls
- channel.closed().
- MAKE SURE YOU CALL THIS METHOD, even if you subclass L{SSHConnection}.
- If you don't, things will break mysteriously.
-
- @type channel: L{SSHChannel}
- """
- if channel in self.channelsToRemoteChannel: # actually open
- channel.localClosed = channel.remoteClosed = True
- del self.localToRemoteChannel[channel.id]
- del self.channels[channel.id]
- del self.channelsToRemoteChannel[channel]
- for d in self.deferreds.setdefault(channel.id, []):
- d.errback(error.ConchError("Channel closed."))
- del self.deferreds[channel.id][:]
- log.callWithLogger(channel, channel.closed)
-
-MSG_GLOBAL_REQUEST = 80
-MSG_REQUEST_SUCCESS = 81
-MSG_REQUEST_FAILURE = 82
-MSG_CHANNEL_OPEN = 90
-MSG_CHANNEL_OPEN_CONFIRMATION = 91
-MSG_CHANNEL_OPEN_FAILURE = 92
-MSG_CHANNEL_WINDOW_ADJUST = 93
-MSG_CHANNEL_DATA = 94
-MSG_CHANNEL_EXTENDED_DATA = 95
-MSG_CHANNEL_EOF = 96
-MSG_CHANNEL_CLOSE = 97
-MSG_CHANNEL_REQUEST = 98
-MSG_CHANNEL_SUCCESS = 99
-MSG_CHANNEL_FAILURE = 100
-
-OPEN_ADMINISTRATIVELY_PROHIBITED = 1
-OPEN_CONNECT_FAILED = 2
-OPEN_UNKNOWN_CHANNEL_TYPE = 3
-OPEN_RESOURCE_SHORTAGE = 4
-
-EXTENDED_DATA_STDERR = 1
-
-messages = {}
-for name, value in locals().copy().items():
- if name[:4] == 'MSG_':
- messages[value] = name # doesn't handle doubles
-
-import string
-alphanums = string.letters + string.digits
-TRANSLATE_TABLE = ''.join([chr(i) in alphanums and chr(i) or '_'
- for i in range(256)])
-SSHConnection.protocolMessages = messages
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/factory.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/factory.py
deleted file mode 100644
index d020bc5..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/factory.py
+++ /dev/null
@@ -1,120 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-A Factory for SSH servers, along with an OpenSSHFactory to use the same
-data sources as OpenSSH.
-
-Maintainer: Paul Swartz
-"""
-
-from twisted.internet import protocol
-from twisted.python import log
-
-from twisted.conch import error
-import transport, userauth, connection
-
-import random
-
-
-class SSHFactory(protocol.Factory):
- """
- A Factory for SSH servers.
- """
- protocol = transport.SSHServerTransport
-
- services = {
- 'ssh-userauth':userauth.SSHUserAuthServer,
- 'ssh-connection':connection.SSHConnection
- }
- def startFactory(self):
- """
- Check for public and private keys.
- """
- if not hasattr(self,'publicKeys'):
- self.publicKeys = self.getPublicKeys()
- if not hasattr(self,'privateKeys'):
- self.privateKeys = self.getPrivateKeys()
- if not self.publicKeys or not self.privateKeys:
- raise error.ConchError('no host keys, failing')
- if not hasattr(self,'primes'):
- self.primes = self.getPrimes()
-
-
- def buildProtocol(self, addr):
- """
- Create an instance of the server side of the SSH protocol.
-
- @type addr: L{twisted.internet.interfaces.IAddress} provider
- @param addr: The address at which the server will listen.
-
- @rtype: L{twisted.conch.ssh.SSHServerTransport}
- @return: The built transport.
- """
- t = protocol.Factory.buildProtocol(self, addr)
- t.supportedPublicKeys = self.privateKeys.keys()
- if not self.primes:
- log.msg('disabling diffie-hellman-group-exchange because we '
- 'cannot find moduli file')
- ske = t.supportedKeyExchanges[:]
- ske.remove('diffie-hellman-group-exchange-sha1')
- t.supportedKeyExchanges = ske
- return t
-
-
- def getPublicKeys(self):
- """
- Called when the factory is started to get the public portions of the
- servers host keys. Returns a dictionary mapping SSH key types to
- public key strings.
-
- @rtype: C{dict}
- """
- raise NotImplementedError('getPublicKeys unimplemented')
-
-
- def getPrivateKeys(self):
- """
- Called when the factory is started to get the private portions of the
- servers host keys. Returns a dictionary mapping SSH key types to
- C{Crypto.PublicKey.pubkey.pubkey} objects.
-
- @rtype: C{dict}
- """
- raise NotImplementedError('getPrivateKeys unimplemented')
-
-
- def getPrimes(self):
- """
- Called when the factory is started to get Diffie-Hellman generators and
- primes to use. Returns a dictionary mapping number of bits to lists
- of tuple of (generator, prime).
-
- @rtype: C{dict}
- """
-
-
- def getDHPrime(self, bits):
- """
- Return a tuple of (g, p) for a Diffe-Hellman process, with p being as
- close to bits bits as possible.
-
- @type bits: C{int}
- @rtype: C{tuple}
- """
- primesKeys = self.primes.keys()
- primesKeys.sort(lambda x, y: cmp(abs(x - bits), abs(y - bits)))
- realBits = primesKeys[0]
- return random.choice(self.primes[realBits])
-
-
- def getService(self, transport, service):
- """
- Return a class to use as a service for the given transport.
-
- @type transport: L{transport.SSHServerTransport}
- @type service: C{str}
- @rtype: subclass of L{service.SSHService}
- """
- if service == 'ssh-userauth' or hasattr(transport, 'avatar'):
- return self.services[service]
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/filetransfer.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/filetransfer.py
deleted file mode 100644
index 9b11db0..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/filetransfer.py
+++ /dev/null
@@ -1,934 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_filetransfer -*-
-#
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-import struct, errno
-
-from twisted.internet import defer, protocol
-from twisted.python import failure, log
-
-from common import NS, getNS
-from twisted.conch.interfaces import ISFTPServer, ISFTPFile
-
-from zope import interface
-
-
-
-class FileTransferBase(protocol.Protocol):
-
- versions = (3, )
-
- packetTypes = {}
-
- def __init__(self):
- self.buf = ''
- self.otherVersion = None # this gets set
-
- def sendPacket(self, kind, data):
- self.transport.write(struct.pack('!LB', len(data)+1, kind) + data)
-
- def dataReceived(self, data):
- self.buf += data
- while len(self.buf) > 5:
- length, kind = struct.unpack('!LB', self.buf[:5])
- if len(self.buf) < 4 + length:
- return
- data, self.buf = self.buf[5:4+length], self.buf[4+length:]
- packetType = self.packetTypes.get(kind, None)
- if not packetType:
- log.msg('no packet type for', kind)
- continue
- f = getattr(self, 'packet_%s' % packetType, None)
- if not f:
- log.msg('not implemented: %s' % packetType)
- log.msg(repr(data[4:]))
- reqId, = struct.unpack('!L', data[:4])
- self._sendStatus(reqId, FX_OP_UNSUPPORTED,
- "don't understand %s" % packetType)
- #XXX not implemented
- continue
- try:
- f(data)
- except:
- log.err()
- continue
- reqId ,= struct.unpack('!L', data[:4])
- self._ebStatus(failure.Failure(e), reqId)
-
- def _parseAttributes(self, data):
- flags ,= struct.unpack('!L', data[:4])
- attrs = {}
- data = data[4:]
- if flags & FILEXFER_ATTR_SIZE == FILEXFER_ATTR_SIZE:
- size ,= struct.unpack('!Q', data[:8])
- attrs['size'] = size
- data = data[8:]
- if flags & FILEXFER_ATTR_OWNERGROUP == FILEXFER_ATTR_OWNERGROUP:
- uid, gid = struct.unpack('!2L', data[:8])
- attrs['uid'] = uid
- attrs['gid'] = gid
- data = data[8:]
- if flags & FILEXFER_ATTR_PERMISSIONS == FILEXFER_ATTR_PERMISSIONS:
- perms ,= struct.unpack('!L', data[:4])
- attrs['permissions'] = perms
- data = data[4:]
- if flags & FILEXFER_ATTR_ACMODTIME == FILEXFER_ATTR_ACMODTIME:
- atime, mtime = struct.unpack('!2L', data[:8])
- attrs['atime'] = atime
- attrs['mtime'] = mtime
- data = data[8:]
- if flags & FILEXFER_ATTR_EXTENDED == FILEXFER_ATTR_EXTENDED:
- extended_count ,= struct.unpack('!L', data[:4])
- data = data[4:]
- for i in xrange(extended_count):
- extended_type, data = getNS(data)
- extended_data, data = getNS(data)
- attrs['ext_%s' % extended_type] = extended_data
- return attrs, data
-
- def _packAttributes(self, attrs):
- flags = 0
- data = ''
- if 'size' in attrs:
- data += struct.pack('!Q', attrs['size'])
- flags |= FILEXFER_ATTR_SIZE
- if 'uid' in attrs and 'gid' in attrs:
- data += struct.pack('!2L', attrs['uid'], attrs['gid'])
- flags |= FILEXFER_ATTR_OWNERGROUP
- if 'permissions' in attrs:
- data += struct.pack('!L', attrs['permissions'])
- flags |= FILEXFER_ATTR_PERMISSIONS
- if 'atime' in attrs and 'mtime' in attrs:
- data += struct.pack('!2L', attrs['atime'], attrs['mtime'])
- flags |= FILEXFER_ATTR_ACMODTIME
- extended = []
- for k in attrs:
- if k.startswith('ext_'):
- ext_type = NS(k[4:])
- ext_data = NS(attrs[k])
- extended.append(ext_type+ext_data)
- if extended:
- data += struct.pack('!L', len(extended))
- data += ''.join(extended)
- flags |= FILEXFER_ATTR_EXTENDED
- return struct.pack('!L', flags) + data
-
-class FileTransferServer(FileTransferBase):
-
- def __init__(self, data=None, avatar=None):
- FileTransferBase.__init__(self)
- self.client = ISFTPServer(avatar) # yay interfaces
- self.openFiles = {}
- self.openDirs = {}
-
- def packet_INIT(self, data):
- version ,= struct.unpack('!L', data[:4])
- self.version = min(list(self.versions) + [version])
- data = data[4:]
- ext = {}
- while data:
- ext_name, data = getNS(data)
- ext_data, data = getNS(data)
- ext[ext_name] = ext_data
- our_ext = self.client.gotVersion(version, ext)
- our_ext_data = ""
- for (k,v) in our_ext.items():
- our_ext_data += NS(k) + NS(v)
- self.sendPacket(FXP_VERSION, struct.pack('!L', self.version) + \
- our_ext_data)
-
- def packet_OPEN(self, data):
- requestId = data[:4]
- data = data[4:]
- filename, data = getNS(data)
- flags ,= struct.unpack('!L', data[:4])
- data = data[4:]
- attrs, data = self._parseAttributes(data)
- assert data == '', 'still have data in OPEN: %s' % repr(data)
- d = defer.maybeDeferred(self.client.openFile, filename, flags, attrs)
- d.addCallback(self._cbOpenFile, requestId)
- d.addErrback(self._ebStatus, requestId, "open failed")
-
- def _cbOpenFile(self, fileObj, requestId):
- fileId = str(hash(fileObj))
- if fileId in self.openFiles:
- raise KeyError, 'id already open'
- self.openFiles[fileId] = fileObj
- self.sendPacket(FXP_HANDLE, requestId + NS(fileId))
-
- def packet_CLOSE(self, data):
- requestId = data[:4]
- data = data[4:]
- handle, data = getNS(data)
- assert data == '', 'still have data in CLOSE: %s' % repr(data)
- if handle in self.openFiles:
- fileObj = self.openFiles[handle]
- d = defer.maybeDeferred(fileObj.close)
- d.addCallback(self._cbClose, handle, requestId)
- d.addErrback(self._ebStatus, requestId, "close failed")
- elif handle in self.openDirs:
- dirObj = self.openDirs[handle][0]
- d = defer.maybeDeferred(dirObj.close)
- d.addCallback(self._cbClose, handle, requestId, 1)
- d.addErrback(self._ebStatus, requestId, "close failed")
- else:
- self._ebClose(failure.Failure(KeyError()), requestId)
-
- def _cbClose(self, result, handle, requestId, isDir = 0):
- if isDir:
- del self.openDirs[handle]
- else:
- del self.openFiles[handle]
- self._sendStatus(requestId, FX_OK, 'file closed')
-
- def packet_READ(self, data):
- requestId = data[:4]
- data = data[4:]
- handle, data = getNS(data)
- (offset, length), data = struct.unpack('!QL', data[:12]), data[12:]
- assert data == '', 'still have data in READ: %s' % repr(data)
- if handle not in self.openFiles:
- self._ebRead(failure.Failure(KeyError()), requestId)
- else:
- fileObj = self.openFiles[handle]
- d = defer.maybeDeferred(fileObj.readChunk, offset, length)
- d.addCallback(self._cbRead, requestId)
- d.addErrback(self._ebStatus, requestId, "read failed")
-
- def _cbRead(self, result, requestId):
- if result == '': # python's read will return this for EOF
- raise EOFError()
- self.sendPacket(FXP_DATA, requestId + NS(result))
-
- def packet_WRITE(self, data):
- requestId = data[:4]
- data = data[4:]
- handle, data = getNS(data)
- offset, = struct.unpack('!Q', data[:8])
- data = data[8:]
- writeData, data = getNS(data)
- assert data == '', 'still have data in WRITE: %s' % repr(data)
- if handle not in self.openFiles:
- self._ebWrite(failure.Failure(KeyError()), requestId)
- else:
- fileObj = self.openFiles[handle]
- d = defer.maybeDeferred(fileObj.writeChunk, offset, writeData)
- d.addCallback(self._cbStatus, requestId, "write succeeded")
- d.addErrback(self._ebStatus, requestId, "write failed")
-
- def packet_REMOVE(self, data):
- requestId = data[:4]
- data = data[4:]
- filename, data = getNS(data)
- assert data == '', 'still have data in REMOVE: %s' % repr(data)
- d = defer.maybeDeferred(self.client.removeFile, filename)
- d.addCallback(self._cbStatus, requestId, "remove succeeded")
- d.addErrback(self._ebStatus, requestId, "remove failed")
-
- def packet_RENAME(self, data):
- requestId = data[:4]
- data = data[4:]
- oldPath, data = getNS(data)
- newPath, data = getNS(data)
- assert data == '', 'still have data in RENAME: %s' % repr(data)
- d = defer.maybeDeferred(self.client.renameFile, oldPath, newPath)
- d.addCallback(self._cbStatus, requestId, "rename succeeded")
- d.addErrback(self._ebStatus, requestId, "rename failed")
-
- def packet_MKDIR(self, data):
- requestId = data[:4]
- data = data[4:]
- path, data = getNS(data)
- attrs, data = self._parseAttributes(data)
- assert data == '', 'still have data in MKDIR: %s' % repr(data)
- d = defer.maybeDeferred(self.client.makeDirectory, path, attrs)
- d.addCallback(self._cbStatus, requestId, "mkdir succeeded")
- d.addErrback(self._ebStatus, requestId, "mkdir failed")
-
- def packet_RMDIR(self, data):
- requestId = data[:4]
- data = data[4:]
- path, data = getNS(data)
- assert data == '', 'still have data in RMDIR: %s' % repr(data)
- d = defer.maybeDeferred(self.client.removeDirectory, path)
- d.addCallback(self._cbStatus, requestId, "rmdir succeeded")
- d.addErrback(self._ebStatus, requestId, "rmdir failed")
-
- def packet_OPENDIR(self, data):
- requestId = data[:4]
- data = data[4:]
- path, data = getNS(data)
- assert data == '', 'still have data in OPENDIR: %s' % repr(data)
- d = defer.maybeDeferred(self.client.openDirectory, path)
- d.addCallback(self._cbOpenDirectory, requestId)
- d.addErrback(self._ebStatus, requestId, "opendir failed")
-
- def _cbOpenDirectory(self, dirObj, requestId):
- handle = str(hash(dirObj))
- if handle in self.openDirs:
- raise KeyError, "already opened this directory"
- self.openDirs[handle] = [dirObj, iter(dirObj)]
- self.sendPacket(FXP_HANDLE, requestId + NS(handle))
-
- def packet_READDIR(self, data):
- requestId = data[:4]
- data = data[4:]
- handle, data = getNS(data)
- assert data == '', 'still have data in READDIR: %s' % repr(data)
- if handle not in self.openDirs:
- self._ebStatus(failure.Failure(KeyError()), requestId)
- else:
- dirObj, dirIter = self.openDirs[handle]
- d = defer.maybeDeferred(self._scanDirectory, dirIter, [])
- d.addCallback(self._cbSendDirectory, requestId)
- d.addErrback(self._ebStatus, requestId, "scan directory failed")
-
- def _scanDirectory(self, dirIter, f):
- while len(f) < 250:
- try:
- info = dirIter.next()
- except StopIteration:
- if not f:
- raise EOFError
- return f
- if isinstance(info, defer.Deferred):
- info.addCallback(self._cbScanDirectory, dirIter, f)
- return
- else:
- f.append(info)
- return f
-
- def _cbScanDirectory(self, result, dirIter, f):
- f.append(result)
- return self._scanDirectory(dirIter, f)
-
- def _cbSendDirectory(self, result, requestId):
- data = ''
- for (filename, longname, attrs) in result:
- data += NS(filename)
- data += NS(longname)
- data += self._packAttributes(attrs)
- self.sendPacket(FXP_NAME, requestId +
- struct.pack('!L', len(result))+data)
-
- def packet_STAT(self, data, followLinks = 1):
- requestId = data[:4]
- data = data[4:]
- path, data = getNS(data)
- assert data == '', 'still have data in STAT/LSTAT: %s' % repr(data)
- d = defer.maybeDeferred(self.client.getAttrs, path, followLinks)
- d.addCallback(self._cbStat, requestId)
- d.addErrback(self._ebStatus, requestId, 'stat/lstat failed')
-
- def packet_LSTAT(self, data):
- self.packet_STAT(data, 0)
-
- def packet_FSTAT(self, data):
- requestId = data[:4]
- data = data[4:]
- handle, data = getNS(data)
- assert data == '', 'still have data in FSTAT: %s' % repr(data)
- if handle not in self.openFiles:
- self._ebStatus(failure.Failure(KeyError('%s not in self.openFiles'
- % handle)), requestId)
- else:
- fileObj = self.openFiles[handle]
- d = defer.maybeDeferred(fileObj.getAttrs)
- d.addCallback(self._cbStat, requestId)
- d.addErrback(self._ebStatus, requestId, 'fstat failed')
-
- def _cbStat(self, result, requestId):
- data = requestId + self._packAttributes(result)
- self.sendPacket(FXP_ATTRS, data)
-
- def packet_SETSTAT(self, data):
- requestId = data[:4]
- data = data[4:]
- path, data = getNS(data)
- attrs, data = self._parseAttributes(data)
- if data != '':
- log.msg('WARN: still have data in SETSTAT: %s' % repr(data))
- d = defer.maybeDeferred(self.client.setAttrs, path, attrs)
- d.addCallback(self._cbStatus, requestId, 'setstat succeeded')
- d.addErrback(self._ebStatus, requestId, 'setstat failed')
-
- def packet_FSETSTAT(self, data):
- requestId = data[:4]
- data = data[4:]
- handle, data = getNS(data)
- attrs, data = self._parseAttributes(data)
- assert data == '', 'still have data in FSETSTAT: %s' % repr(data)
- if handle not in self.openFiles:
- self._ebStatus(failure.Failure(KeyError()), requestId)
- else:
- fileObj = self.openFiles[handle]
- d = defer.maybeDeferred(fileObj.setAttrs, attrs)
- d.addCallback(self._cbStatus, requestId, 'fsetstat succeeded')
- d.addErrback(self._ebStatus, requestId, 'fsetstat failed')
-
- def packet_READLINK(self, data):
- requestId = data[:4]
- data = data[4:]
- path, data = getNS(data)
- assert data == '', 'still have data in READLINK: %s' % repr(data)
- d = defer.maybeDeferred(self.client.readLink, path)
- d.addCallback(self._cbReadLink, requestId)
- d.addErrback(self._ebStatus, requestId, 'readlink failed')
-
- def _cbReadLink(self, result, requestId):
- self._cbSendDirectory([(result, '', {})], requestId)
-
- def packet_SYMLINK(self, data):
- requestId = data[:4]
- data = data[4:]
- linkPath, data = getNS(data)
- targetPath, data = getNS(data)
- d = defer.maybeDeferred(self.client.makeLink, linkPath, targetPath)
- d.addCallback(self._cbStatus, requestId, 'symlink succeeded')
- d.addErrback(self._ebStatus, requestId, 'symlink failed')
-
- def packet_REALPATH(self, data):
- requestId = data[:4]
- data = data[4:]
- path, data = getNS(data)
- assert data == '', 'still have data in REALPATH: %s' % repr(data)
- d = defer.maybeDeferred(self.client.realPath, path)
- d.addCallback(self._cbReadLink, requestId) # same return format
- d.addErrback(self._ebStatus, requestId, 'realpath failed')
-
- def packet_EXTENDED(self, data):
- requestId = data[:4]
- data = data[4:]
- extName, extData = getNS(data)
- d = defer.maybeDeferred(self.client.extendedRequest, extName, extData)
- d.addCallback(self._cbExtended, requestId)
- d.addErrback(self._ebStatus, requestId, 'extended %s failed' % extName)
-
- def _cbExtended(self, data, requestId):
- self.sendPacket(FXP_EXTENDED_REPLY, requestId + data)
-
- def _cbStatus(self, result, requestId, msg = "request succeeded"):
- self._sendStatus(requestId, FX_OK, msg)
-
- def _ebStatus(self, reason, requestId, msg = "request failed"):
- code = FX_FAILURE
- message = msg
- if reason.type in (IOError, OSError):
- if reason.value.errno == errno.ENOENT: # no such file
- code = FX_NO_SUCH_FILE
- message = reason.value.strerror
- elif reason.value.errno == errno.EACCES: # permission denied
- code = FX_PERMISSION_DENIED
- message = reason.value.strerror
- elif reason.value.errno == errno.EEXIST:
- code = FX_FILE_ALREADY_EXISTS
- else:
- log.err(reason)
- elif reason.type == EOFError: # EOF
- code = FX_EOF
- if reason.value.args:
- message = reason.value.args[0]
- elif reason.type == NotImplementedError:
- code = FX_OP_UNSUPPORTED
- if reason.value.args:
- message = reason.value.args[0]
- elif reason.type == SFTPError:
- code = reason.value.code
- message = reason.value.message
- else:
- log.err(reason)
- self._sendStatus(requestId, code, message)
-
- def _sendStatus(self, requestId, code, message, lang = ''):
- """
- Helper method to send a FXP_STATUS message.
- """
- data = requestId + struct.pack('!L', code)
- data += NS(message)
- data += NS(lang)
- self.sendPacket(FXP_STATUS, data)
-
-
- def connectionLost(self, reason):
- """
- Clean all opened files and directories.
- """
- for fileObj in self.openFiles.values():
- fileObj.close()
- self.openFiles = {}
- for (dirObj, dirIter) in self.openDirs.values():
- dirObj.close()
- self.openDirs = {}
-
-
-
-class FileTransferClient(FileTransferBase):
-
- def __init__(self, extData = {}):
- """
- @param extData: a dict of extended_name : extended_data items
- to be sent to the server.
- """
- FileTransferBase.__init__(self)
- self.extData = {}
- self.counter = 0
- self.openRequests = {} # id -> Deferred
- self.wasAFile = {} # Deferred -> 1 TERRIBLE HACK
-
- def connectionMade(self):
- data = struct.pack('!L', max(self.versions))
- for k,v in self.extData.itervalues():
- data += NS(k) + NS(v)
- self.sendPacket(FXP_INIT, data)
-
- def _sendRequest(self, msg, data):
- data = struct.pack('!L', self.counter) + data
- d = defer.Deferred()
- self.openRequests[self.counter] = d
- self.counter += 1
- self.sendPacket(msg, data)
- return d
-
- def _parseRequest(self, data):
- (id,) = struct.unpack('!L', data[:4])
- d = self.openRequests[id]
- del self.openRequests[id]
- return d, data[4:]
-
- def openFile(self, filename, flags, attrs):
- """
- Open a file.
-
- This method returns a L{Deferred} that is called back with an object
- that provides the L{ISFTPFile} interface.
-
- @param filename: a string representing the file to open.
-
- @param flags: a integer of the flags to open the file with, ORed together.
- The flags and their values are listed at the bottom of this file.
-
- @param attrs: a list of attributes to open the file with. It is a
- dictionary, consisting of 0 or more keys. The possible keys are::
-
- size: the size of the file in bytes
- uid: the user ID of the file as an integer
- gid: the group ID of the file as an integer
- permissions: the permissions of the file with as an integer.
- the bit representation of this field is defined by POSIX.
- atime: the access time of the file as seconds since the epoch.
- mtime: the modification time of the file as seconds since the epoch.
- ext_*: extended attributes. The server is not required to
- understand this, but it may.
-
- NOTE: there is no way to indicate text or binary files. it is up
- to the SFTP client to deal with this.
- """
- data = NS(filename) + struct.pack('!L', flags) + self._packAttributes(attrs)
- d = self._sendRequest(FXP_OPEN, data)
- self.wasAFile[d] = (1, filename) # HACK
- return d
-
- def removeFile(self, filename):
- """
- Remove the given file.
-
- This method returns a Deferred that is called back when it succeeds.
-
- @param filename: the name of the file as a string.
- """
- return self._sendRequest(FXP_REMOVE, NS(filename))
-
- def renameFile(self, oldpath, newpath):
- """
- Rename the given file.
-
- This method returns a Deferred that is called back when it succeeds.
-
- @param oldpath: the current location of the file.
- @param newpath: the new file name.
- """
- return self._sendRequest(FXP_RENAME, NS(oldpath)+NS(newpath))
-
- def makeDirectory(self, path, attrs):
- """
- Make a directory.
-
- This method returns a Deferred that is called back when it is
- created.
-
- @param path: the name of the directory to create as a string.
-
- @param attrs: a dictionary of attributes to create the directory
- with. Its meaning is the same as the attrs in the openFile method.
- """
- return self._sendRequest(FXP_MKDIR, NS(path)+self._packAttributes(attrs))
-
- def removeDirectory(self, path):
- """
- Remove a directory (non-recursively)
-
- It is an error to remove a directory that has files or directories in
- it.
-
- This method returns a Deferred that is called back when it is removed.
-
- @param path: the directory to remove.
- """
- return self._sendRequest(FXP_RMDIR, NS(path))
-
- def openDirectory(self, path):
- """
- Open a directory for scanning.
-
- This method returns a Deferred that is called back with an iterable
- object that has a close() method.
-
- The close() method is called when the client is finished reading
- from the directory. At this point, the iterable will no longer
- be used.
-
- The iterable returns triples of the form (filename, longname, attrs)
- or a Deferred that returns the same. The sequence must support
- __getitem__, but otherwise may be any 'sequence-like' object.
-
- filename is the name of the file relative to the directory.
- logname is an expanded format of the filename. The recommended format
- is:
- -rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer
- 1234567890 123 12345678 12345678 12345678 123456789012
-
- The first line is sample output, the second is the length of the field.
- The fields are: permissions, link count, user owner, group owner,
- size in bytes, modification time.
-
- attrs is a dictionary in the format of the attrs argument to openFile.
-
- @param path: the directory to open.
- """
- d = self._sendRequest(FXP_OPENDIR, NS(path))
- self.wasAFile[d] = (0, path)
- return d
-
- def getAttrs(self, path, followLinks=0):
- """
- Return the attributes for the given path.
-
- This method returns a dictionary in the same format as the attrs
- argument to openFile or a Deferred that is called back with same.
-
- @param path: the path to return attributes for as a string.
- @param followLinks: a boolean. if it is True, follow symbolic links
- and return attributes for the real path at the base. if it is False,
- return attributes for the specified path.
- """
- if followLinks: m = FXP_STAT
- else: m = FXP_LSTAT
- return self._sendRequest(m, NS(path))
-
- def setAttrs(self, path, attrs):
- """
- Set the attributes for the path.
-
- This method returns when the attributes are set or a Deferred that is
- called back when they are.
-
- @param path: the path to set attributes for as a string.
- @param attrs: a dictionary in the same format as the attrs argument to
- openFile.
- """
- data = NS(path) + self._packAttributes(attrs)
- return self._sendRequest(FXP_SETSTAT, data)
-
- def readLink(self, path):
- """
- Find the root of a set of symbolic links.
-
- This method returns the target of the link, or a Deferred that
- returns the same.
-
- @param path: the path of the symlink to read.
- """
- d = self._sendRequest(FXP_READLINK, NS(path))
- return d.addCallback(self._cbRealPath)
-
- def makeLink(self, linkPath, targetPath):
- """
- Create a symbolic link.
-
- This method returns when the link is made, or a Deferred that
- returns the same.
-
- @param linkPath: the pathname of the symlink as a string
- @param targetPath: the path of the target of the link as a string.
- """
- return self._sendRequest(FXP_SYMLINK, NS(linkPath)+NS(targetPath))
-
- def realPath(self, path):
- """
- Convert any path to an absolute path.
-
- This method returns the absolute path as a string, or a Deferred
- that returns the same.
-
- @param path: the path to convert as a string.
- """
- d = self._sendRequest(FXP_REALPATH, NS(path))
- return d.addCallback(self._cbRealPath)
-
- def _cbRealPath(self, result):
- name, longname, attrs = result[0]
- return name
-
- def extendedRequest(self, request, data):
- """
- Make an extended request of the server.
-
- The method returns a Deferred that is called back with
- the result of the extended request.
-
- @param request: the name of the extended request to make.
- @param data: any other data that goes along with the request.
- """
- return self._sendRequest(FXP_EXTENDED, NS(request) + data)
-
- def packet_VERSION(self, data):
- version, = struct.unpack('!L', data[:4])
- data = data[4:]
- d = {}
- while data:
- k, data = getNS(data)
- v, data = getNS(data)
- d[k]=v
- self.version = version
- self.gotServerVersion(version, d)
-
- def packet_STATUS(self, data):
- d, data = self._parseRequest(data)
- code, = struct.unpack('!L', data[:4])
- data = data[4:]
- if len(data) >= 4:
- msg, data = getNS(data)
- if len(data) >= 4:
- lang, data = getNS(data)
- else:
- lang = ''
- else:
- msg = ''
- lang = ''
- if code == FX_OK:
- d.callback((msg, lang))
- elif code == FX_EOF:
- d.errback(EOFError(msg))
- elif code == FX_OP_UNSUPPORTED:
- d.errback(NotImplementedError(msg))
- else:
- d.errback(SFTPError(code, msg, lang))
-
- def packet_HANDLE(self, data):
- d, data = self._parseRequest(data)
- isFile, name = self.wasAFile.pop(d)
- if isFile:
- cb = ClientFile(self, getNS(data)[0])
- else:
- cb = ClientDirectory(self, getNS(data)[0])
- cb.name = name
- d.callback(cb)
-
- def packet_DATA(self, data):
- d, data = self._parseRequest(data)
- d.callback(getNS(data)[0])
-
- def packet_NAME(self, data):
- d, data = self._parseRequest(data)
- count, = struct.unpack('!L', data[:4])
- data = data[4:]
- files = []
- for i in range(count):
- filename, data = getNS(data)
- longname, data = getNS(data)
- attrs, data = self._parseAttributes(data)
- files.append((filename, longname, attrs))
- d.callback(files)
-
- def packet_ATTRS(self, data):
- d, data = self._parseRequest(data)
- d.callback(self._parseAttributes(data)[0])
-
- def packet_EXTENDED_REPLY(self, data):
- d, data = self._parseRequest(data)
- d.callback(data)
-
- def gotServerVersion(self, serverVersion, extData):
- """
- Called when the client sends their version info.
-
- @param otherVersion: an integer representing the version of the SFTP
- protocol they are claiming.
- @param extData: a dictionary of extended_name : extended_data items.
- These items are sent by the client to indicate additional features.
- """
-
-class ClientFile:
-
- interface.implements(ISFTPFile)
-
- def __init__(self, parent, handle):
- self.parent = parent
- self.handle = NS(handle)
-
- def close(self):
- return self.parent._sendRequest(FXP_CLOSE, self.handle)
-
- def readChunk(self, offset, length):
- data = self.handle + struct.pack("!QL", offset, length)
- return self.parent._sendRequest(FXP_READ, data)
-
- def writeChunk(self, offset, chunk):
- data = self.handle + struct.pack("!Q", offset) + NS(chunk)
- return self.parent._sendRequest(FXP_WRITE, data)
-
- def getAttrs(self):
- return self.parent._sendRequest(FXP_FSTAT, self.handle)
-
- def setAttrs(self, attrs):
- data = self.handle + self.parent._packAttributes(attrs)
- return self.parent._sendRequest(FXP_FSTAT, data)
-
-class ClientDirectory:
-
- def __init__(self, parent, handle):
- self.parent = parent
- self.handle = NS(handle)
- self.filesCache = []
-
- def read(self):
- d = self.parent._sendRequest(FXP_READDIR, self.handle)
- return d
-
- def close(self):
- return self.parent._sendRequest(FXP_CLOSE, self.handle)
-
- def __iter__(self):
- return self
-
- def next(self):
- if self.filesCache:
- return self.filesCache.pop(0)
- d = self.read()
- d.addCallback(self._cbReadDir)
- d.addErrback(self._ebReadDir)
- return d
-
- def _cbReadDir(self, names):
- self.filesCache = names[1:]
- return names[0]
-
- def _ebReadDir(self, reason):
- reason.trap(EOFError)
- def _():
- raise StopIteration
- self.next = _
- return reason
-
-
-class SFTPError(Exception):
-
- def __init__(self, errorCode, errorMessage, lang = ''):
- Exception.__init__(self)
- self.code = errorCode
- self._message = errorMessage
- self.lang = lang
-
-
- def message(self):
- """
- A string received over the network that explains the error to a human.
- """
- # Python 2.6 deprecates assigning to the 'message' attribute of an
- # exception. We define this read-only property here in order to
- # prevent the warning about deprecation while maintaining backwards
- # compatibility with object clients that rely on the 'message'
- # attribute being set correctly. See bug #3897.
- return self._message
- message = property(message)
-
-
- def __str__(self):
- return 'SFTPError %s: %s' % (self.code, self.message)
-
-FXP_INIT = 1
-FXP_VERSION = 2
-FXP_OPEN = 3
-FXP_CLOSE = 4
-FXP_READ = 5
-FXP_WRITE = 6
-FXP_LSTAT = 7
-FXP_FSTAT = 8
-FXP_SETSTAT = 9
-FXP_FSETSTAT = 10
-FXP_OPENDIR = 11
-FXP_READDIR = 12
-FXP_REMOVE = 13
-FXP_MKDIR = 14
-FXP_RMDIR = 15
-FXP_REALPATH = 16
-FXP_STAT = 17
-FXP_RENAME = 18
-FXP_READLINK = 19
-FXP_SYMLINK = 20
-FXP_STATUS = 101
-FXP_HANDLE = 102
-FXP_DATA = 103
-FXP_NAME = 104
-FXP_ATTRS = 105
-FXP_EXTENDED = 200
-FXP_EXTENDED_REPLY = 201
-
-FILEXFER_ATTR_SIZE = 0x00000001
-FILEXFER_ATTR_UIDGID = 0x00000002
-FILEXFER_ATTR_OWNERGROUP = FILEXFER_ATTR_UIDGID
-FILEXFER_ATTR_PERMISSIONS = 0x00000004
-FILEXFER_ATTR_ACMODTIME = 0x00000008
-FILEXFER_ATTR_EXTENDED = 0x80000000L
-
-FILEXFER_TYPE_REGULAR = 1
-FILEXFER_TYPE_DIRECTORY = 2
-FILEXFER_TYPE_SYMLINK = 3
-FILEXFER_TYPE_SPECIAL = 4
-FILEXFER_TYPE_UNKNOWN = 5
-
-FXF_READ = 0x00000001
-FXF_WRITE = 0x00000002
-FXF_APPEND = 0x00000004
-FXF_CREAT = 0x00000008
-FXF_TRUNC = 0x00000010
-FXF_EXCL = 0x00000020
-FXF_TEXT = 0x00000040
-
-FX_OK = 0
-FX_EOF = 1
-FX_NO_SUCH_FILE = 2
-FX_PERMISSION_DENIED = 3
-FX_FAILURE = 4
-FX_BAD_MESSAGE = 5
-FX_NO_CONNECTION = 6
-FX_CONNECTION_LOST = 7
-FX_OP_UNSUPPORTED = 8
-FX_FILE_ALREADY_EXISTS = 11
-# http://tools.ietf.org/wg/secsh/draft-ietf-secsh-filexfer/ defines more
-# useful error codes, but so far OpenSSH doesn't implement them. We use them
-# internally for clarity, but for now define them all as FX_FAILURE to be
-# compatible with existing software.
-FX_NOT_A_DIRECTORY = FX_FAILURE
-FX_FILE_IS_A_DIRECTORY = FX_FAILURE
-
-
-# initialize FileTransferBase.packetTypes:
-g = globals()
-for name in g.keys():
- if name.startswith('FXP_'):
- value = g[name]
- FileTransferBase.packetTypes[value] = name[4:]
-del g, name, value
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/forwarding.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/forwarding.py
deleted file mode 100644
index 753f994..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/forwarding.py
+++ /dev/null
@@ -1,181 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-"""
-This module contains the implementation of the TCP forwarding, which allows
-clients and servers to forward arbitrary TCP data across the connection.
-
-Maintainer: Paul Swartz
-"""
-
-import struct
-
-from twisted.internet import protocol, reactor
-from twisted.python import log
-
-import common, channel
-
-class SSHListenForwardingFactory(protocol.Factory):
- def __init__(self, connection, hostport, klass):
- self.conn = connection
- self.hostport = hostport # tuple
- self.klass = klass
-
- def buildProtocol(self, addr):
- channel = self.klass(conn = self.conn)
- client = SSHForwardingClient(channel)
- channel.client = client
- addrTuple = (addr.host, addr.port)
- channelOpenData = packOpen_direct_tcpip(self.hostport, addrTuple)
- self.conn.openChannel(channel, channelOpenData)
- return client
-
-class SSHListenForwardingChannel(channel.SSHChannel):
-
- def channelOpen(self, specificData):
- log.msg('opened forwarding channel %s' % self.id)
- if len(self.client.buf)>1:
- b = self.client.buf[1:]
- self.write(b)
- self.client.buf = ''
-
- def openFailed(self, reason):
- self.closed()
-
- def dataReceived(self, data):
- self.client.transport.write(data)
-
- def eofReceived(self):
- self.client.transport.loseConnection()
-
- def closed(self):
- if hasattr(self, 'client'):
- log.msg('closing local forwarding channel %s' % self.id)
- self.client.transport.loseConnection()
- del self.client
-
-class SSHListenClientForwardingChannel(SSHListenForwardingChannel):
-
- name = 'direct-tcpip'
-
-class SSHListenServerForwardingChannel(SSHListenForwardingChannel):
-
- name = 'forwarded-tcpip'
-
-class SSHConnectForwardingChannel(channel.SSHChannel):
-
- def __init__(self, hostport, *args, **kw):
- channel.SSHChannel.__init__(self, *args, **kw)
- self.hostport = hostport
- self.client = None
- self.clientBuf = ''
-
- def channelOpen(self, specificData):
- cc = protocol.ClientCreator(reactor, SSHForwardingClient, self)
- log.msg("connecting to %s:%i" % self.hostport)
- cc.connectTCP(*self.hostport).addCallbacks(self._setClient, self._close)
-
- def _setClient(self, client):
- self.client = client
- log.msg("connected to %s:%i" % self.hostport)
- if self.clientBuf:
- self.client.transport.write(self.clientBuf)
- self.clientBuf = None
- if self.client.buf[1:]:
- self.write(self.client.buf[1:])
- self.client.buf = ''
-
- def _close(self, reason):
- log.msg("failed to connect: %s" % reason)
- self.loseConnection()
-
- def dataReceived(self, data):
- if self.client:
- self.client.transport.write(data)
- else:
- self.clientBuf += data
-
- def closed(self):
- if self.client:
- log.msg('closed remote forwarding channel %s' % self.id)
- if self.client.channel:
- self.loseConnection()
- self.client.transport.loseConnection()
- del self.client
-
-def openConnectForwardingClient(remoteWindow, remoteMaxPacket, data, avatar):
- remoteHP, origHP = unpackOpen_direct_tcpip(data)
- return SSHConnectForwardingChannel(remoteHP,
- remoteWindow=remoteWindow,
- remoteMaxPacket=remoteMaxPacket,
- avatar=avatar)
-
-class SSHForwardingClient(protocol.Protocol):
-
- def __init__(self, channel):
- self.channel = channel
- self.buf = '\000'
-
- def dataReceived(self, data):
- if self.buf:
- self.buf += data
- else:
- self.channel.write(data)
-
- def connectionLost(self, reason):
- if self.channel:
- self.channel.loseConnection()
- self.channel = None
-
-
-def packOpen_direct_tcpip((connHost, connPort), (origHost, origPort)):
- """Pack the data suitable for sending in a CHANNEL_OPEN packet.
- """
- conn = common.NS(connHost) + struct.pack('>L', connPort)
- orig = common.NS(origHost) + struct.pack('>L', origPort)
- return conn + orig
-
-packOpen_forwarded_tcpip = packOpen_direct_tcpip
-
-def unpackOpen_direct_tcpip(data):
- """Unpack the data to a usable format.
- """
- connHost, rest = common.getNS(data)
- connPort = int(struct.unpack('>L', rest[:4])[0])
- origHost, rest = common.getNS(rest[4:])
- origPort = int(struct.unpack('>L', rest[:4])[0])
- return (connHost, connPort), (origHost, origPort)
-
-unpackOpen_forwarded_tcpip = unpackOpen_direct_tcpip
-
-def packGlobal_tcpip_forward((host, port)):
- return common.NS(host) + struct.pack('>L', port)
-
-def unpackGlobal_tcpip_forward(data):
- host, rest = common.getNS(data)
- port = int(struct.unpack('>L', rest[:4])[0])
- return host, port
-
-"""This is how the data -> eof -> close stuff /should/ work.
-
-debug3: channel 1: waiting for connection
-debug1: channel 1: connected
-debug1: channel 1: read<=0 rfd 7 len 0
-debug1: channel 1: read failed
-debug1: channel 1: close_read
-debug1: channel 1: input open -> drain
-debug1: channel 1: ibuf empty
-debug1: channel 1: send eof
-debug1: channel 1: input drain -> closed
-debug1: channel 1: rcvd eof
-debug1: channel 1: output open -> drain
-debug1: channel 1: obuf empty
-debug1: channel 1: close_write
-debug1: channel 1: output drain -> closed
-debug1: channel 1: rcvd close
-debug3: channel 1: will not send data after close
-debug1: channel 1: send close
-debug1: channel 1: is dead
-"""
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/keys.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/keys.py
deleted file mode 100644
index bbd5f96..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/keys.py
+++ /dev/null
@@ -1,857 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_keys -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Handling of RSA and DSA keys.
-
-Maintainer: U{Paul Swartz}
-"""
-
-# base library imports
-import base64
-import itertools
-from hashlib import md5, sha1
-
-# external library imports
-from Crypto.Cipher import DES3, AES
-from Crypto.PublicKey import RSA, DSA
-from Crypto import Util
-from pyasn1.error import PyAsn1Error
-from pyasn1.type import univ
-from pyasn1.codec.ber import decoder as berDecoder
-from pyasn1.codec.ber import encoder as berEncoder
-
-# twisted
-from twisted.python import randbytes
-
-# sibling imports
-from twisted.conch.ssh import common, sexpy
-
-
-
-class BadKeyError(Exception):
- """
- Raised when a key isn't what we expected from it.
-
- XXX: we really need to check for bad keys
- """
-
-
-
-class EncryptedKeyError(Exception):
- """
- Raised when an encrypted key is presented to fromString/fromFile without
- a password.
- """
-
-
-
-class Key(object):
- """
- An object representing a key. A key can be either a public or
- private key. A public key can verify a signature; a private key can
- create or verify a signature. To generate a string that can be stored
- on disk, use the toString method. If you have a private key, but want
- the string representation of the public key, use Key.public().toString().
-
- @ivar keyObject: The C{Crypto.PublicKey.pubkey.pubkey} object that
- operations are performed with.
- """
-
- def fromFile(Class, filename, type=None, passphrase=None):
- """
- Return a Key object corresponding to the data in filename. type
- and passphrase function as they do in fromString.
- """
- return Class.fromString(file(filename, 'rb').read(), type, passphrase)
- fromFile = classmethod(fromFile)
-
-
- def fromString(Class, data, type=None, passphrase=None):
- """
- Return a Key object corresponding to the string data.
- type is optionally the type of string, matching a _fromString_*
- method. Otherwise, the _guessStringType() classmethod will be used
- to guess a type. If the key is encrypted, passphrase is used as
- the decryption key.
-
- @type data: C{str}
- @type type: C{None}/C{str}
- @type passphrase: C{None}/C{str}
- @rtype: C{Key}
- """
- if type is None:
- type = Class._guessStringType(data)
- if type is None:
- raise BadKeyError('cannot guess the type of %r' % data)
- method = getattr(Class, '_fromString_%s' % type.upper(), None)
- if method is None:
- raise BadKeyError('no _fromString method for %s' % type)
- if method.func_code.co_argcount == 2: # no passphrase
- if passphrase:
- raise BadKeyError('key not encrypted')
- return method(data)
- else:
- return method(data, passphrase)
- fromString = classmethod(fromString)
-
-
- def _fromString_BLOB(Class, blob):
- """
- Return a public key object corresponding to this public key blob.
- The format of a RSA public key blob is::
- string 'ssh-rsa'
- integer e
- integer n
-
- The format of a DSA public key blob is::
- string 'ssh-dss'
- integer p
- integer q
- integer g
- integer y
-
- @type blob: C{str}
- @return: a C{Crypto.PublicKey.pubkey.pubkey} object
- @raises BadKeyError: if the key type (the first string) is unknown.
- """
- keyType, rest = common.getNS(blob)
- if keyType == 'ssh-rsa':
- e, n, rest = common.getMP(rest, 2)
- return Class(RSA.construct((n, e)))
- elif keyType == 'ssh-dss':
- p, q, g, y, rest = common.getMP(rest, 4)
- return Class(DSA.construct((y, g, p, q)))
- else:
- raise BadKeyError('unknown blob type: %s' % keyType)
- _fromString_BLOB = classmethod(_fromString_BLOB)
-
-
- def _fromString_PRIVATE_BLOB(Class, blob):
- """
- Return a private key object corresponding to this private key blob.
- The blob formats are as follows:
-
- RSA keys::
- string 'ssh-rsa'
- integer n
- integer e
- integer d
- integer u
- integer p
- integer q
-
- DSA keys::
- string 'ssh-dss'
- integer p
- integer q
- integer g
- integer y
- integer x
-
- @type blob: C{str}
- @return: a C{Crypto.PublicKey.pubkey.pubkey} object
- @raises BadKeyError: if the key type (the first string) is unknown.
- """
- keyType, rest = common.getNS(blob)
-
- if keyType == 'ssh-rsa':
- n, e, d, u, p, q, rest = common.getMP(rest, 6)
- rsakey = Class(RSA.construct((n, e, d, p, q, u)))
- return rsakey
- elif keyType == 'ssh-dss':
- p, q, g, y, x, rest = common.getMP(rest, 5)
- dsakey = Class(DSA.construct((y, g, p, q, x)))
- return dsakey
- else:
- raise BadKeyError('unknown blob type: %s' % keyType)
- _fromString_PRIVATE_BLOB = classmethod(_fromString_PRIVATE_BLOB)
-
-
- def _fromString_PUBLIC_OPENSSH(Class, data):
- """
- Return a public key object corresponding to this OpenSSH public key
- string. The format of an OpenSSH public key string is::
-
-
- @type data: C{str}
- @return: A {Crypto.PublicKey.pubkey.pubkey} object
- @raises BadKeyError: if the blob type is unknown.
- """
- blob = base64.decodestring(data.split()[1])
- return Class._fromString_BLOB(blob)
- _fromString_PUBLIC_OPENSSH = classmethod(_fromString_PUBLIC_OPENSSH)
-
-
- def _fromString_PRIVATE_OPENSSH(Class, data, passphrase):
- """
- Return a private key object corresponding to this OpenSSH private key
- string. If the key is encrypted, passphrase MUST be provided.
- Providing a passphrase for an unencrypted key is an error.
-
- The format of an OpenSSH private key string is::
- -----BEGIN PRIVATE KEY-----
- [Proc-Type: 4,ENCRYPTED
- DEK-Info: DES-EDE3-CBC,]
-
- ------END PRIVATE KEY------
-
- The ASN.1 structure of a RSA key is::
- (0, n, e, d, p, q)
-
- The ASN.1 structure of a DSA key is::
- (0, p, q, g, y, x)
-
- @type data: C{str}
- @type passphrase: C{str}
- @return: a C{Crypto.PublicKey.pubkey.pubkey} object
- @raises BadKeyError: if
- * a passphrase is provided for an unencrypted key
- * the ASN.1 encoding is incorrect
- @raises EncryptedKeyError: if
- * a passphrase is not provided for an encrypted key
- """
- lines = data.strip().split('\n')
- kind = lines[0][11:14]
- if lines[1].startswith('Proc-Type: 4,ENCRYPTED'): # encrypted key
- if not passphrase:
- raise EncryptedKeyError('Passphrase must be provided '
- 'for an encrypted key')
-
- # Determine cipher and initialization vector
- try:
- _, cipher_iv_info = lines[2].split(' ', 1)
- cipher, ivdata = cipher_iv_info.rstrip().split(',', 1)
- except ValueError:
- raise BadKeyError('invalid DEK-info %r' % lines[2])
-
- if cipher == 'AES-128-CBC':
- CipherClass = AES
- keySize = 16
- if len(ivdata) != 32:
- raise BadKeyError('AES encrypted key with a bad IV')
- elif cipher == 'DES-EDE3-CBC':
- CipherClass = DES3
- keySize = 24
- if len(ivdata) != 16:
- raise BadKeyError('DES encrypted key with a bad IV')
- else:
- raise BadKeyError('unknown encryption type %r' % cipher)
-
- # extract keyData for decoding
- iv = ''.join([chr(int(ivdata[i:i + 2], 16))
- for i in range(0, len(ivdata), 2)])
- ba = md5(passphrase + iv[:8]).digest()
- bb = md5(ba + passphrase + iv[:8]).digest()
- decKey = (ba + bb)[:keySize]
- b64Data = base64.decodestring(''.join(lines[3:-1]))
- keyData = CipherClass.new(decKey,
- CipherClass.MODE_CBC,
- iv).decrypt(b64Data)
- removeLen = ord(keyData[-1])
- keyData = keyData[:-removeLen]
- else:
- b64Data = ''.join(lines[1:-1])
- keyData = base64.decodestring(b64Data)
-
- try:
- decodedKey = berDecoder.decode(keyData)[0]
- except PyAsn1Error, e:
- raise BadKeyError('Failed to decode key (Bad Passphrase?): %s' % e)
-
- if kind == 'RSA':
- if len(decodedKey) == 2: # alternate RSA key
- decodedKey = decodedKey[0]
- if len(decodedKey) < 6:
- raise BadKeyError('RSA key failed to decode properly')
-
- n, e, d, p, q = [long(value) for value in decodedKey[1:6]]
- if p > q: # make p smaller than q
- p, q = q, p
- return Class(RSA.construct((n, e, d, p, q)))
- elif kind == 'DSA':
- p, q, g, y, x = [long(value) for value in decodedKey[1: 6]]
- if len(decodedKey) < 6:
- raise BadKeyError('DSA key failed to decode properly')
- return Class(DSA.construct((y, g, p, q, x)))
- _fromString_PRIVATE_OPENSSH = classmethod(_fromString_PRIVATE_OPENSSH)
-
-
- def _fromString_PUBLIC_LSH(Class, data):
- """
- Return a public key corresponding to this LSH public key string.
- The LSH public key string format is::
- , ()+))>
-
- The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e.
- The names for a DSA (key type 'dsa') key are: y, g, p, q.
-
- @type data: C{str}
- @return: a C{Crypto.PublicKey.pubkey.pubkey} object
- @raises BadKeyError: if the key type is unknown
- """
- sexp = sexpy.parse(base64.decodestring(data[1:-1]))
- assert sexp[0] == 'public-key'
- kd = {}
- for name, data in sexp[1][1:]:
- kd[name] = common.getMP(common.NS(data))[0]
- if sexp[1][0] == 'dsa':
- return Class(DSA.construct((kd['y'], kd['g'], kd['p'], kd['q'])))
- elif sexp[1][0] == 'rsa-pkcs1-sha1':
- return Class(RSA.construct((kd['n'], kd['e'])))
- else:
- raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
- _fromString_PUBLIC_LSH = classmethod(_fromString_PUBLIC_LSH)
-
-
- def _fromString_PRIVATE_LSH(Class, data):
- """
- Return a private key corresponding to this LSH private key string.
- The LSH private key string format is::
- , (, )+))>
-
- The names for a RSA (key type 'rsa-pkcs1-sha1') key are: n, e, d, p, q.
- The names for a DSA (key type 'dsa') key are: y, g, p, q, x.
-
- @type data: C{str}
- @return: a {Crypto.PublicKey.pubkey.pubkey} object
- @raises BadKeyError: if the key type is unknown
- """
- sexp = sexpy.parse(data)
- assert sexp[0] == 'private-key'
- kd = {}
- for name, data in sexp[1][1:]:
- kd[name] = common.getMP(common.NS(data))[0]
- if sexp[1][0] == 'dsa':
- assert len(kd) == 5, len(kd)
- return Class(DSA.construct((kd['y'], kd['g'], kd['p'],
- kd['q'], kd['x'])))
- elif sexp[1][0] == 'rsa-pkcs1':
- assert len(kd) == 8, len(kd)
- if kd['p'] > kd['q']: # make p smaller than q
- kd['p'], kd['q'] = kd['q'], kd['p']
- return Class(RSA.construct((kd['n'], kd['e'], kd['d'],
- kd['p'], kd['q'])))
- else:
- raise BadKeyError('unknown lsh key type %s' % sexp[1][0])
- _fromString_PRIVATE_LSH = classmethod(_fromString_PRIVATE_LSH)
-
-
- def _fromString_AGENTV3(Class, data):
- """
- Return a private key object corresponsing to the Secure Shell Key
- Agent v3 format.
-
- The SSH Key Agent v3 format for a RSA key is::
- string 'ssh-rsa'
- integer e
- integer d
- integer n
- integer u
- integer p
- integer q
-
- The SSH Key Agent v3 format for a DSA key is::
- string 'ssh-dss'
- integer p
- integer q
- integer g
- integer y
- integer x
-
- @type data: C{str}
- @return: a C{Crypto.PublicKey.pubkey.pubkey} object
- @raises BadKeyError: if the key type (the first string) is unknown
- """
- keyType, data = common.getNS(data)
- if keyType == 'ssh-dss':
- p, data = common.getMP(data)
- q, data = common.getMP(data)
- g, data = common.getMP(data)
- y, data = common.getMP(data)
- x, data = common.getMP(data)
- return Class(DSA.construct((y, g, p, q, x)))
- elif keyType == 'ssh-rsa':
- e, data = common.getMP(data)
- d, data = common.getMP(data)
- n, data = common.getMP(data)
- u, data = common.getMP(data)
- p, data = common.getMP(data)
- q, data = common.getMP(data)
- return Class(RSA.construct((n, e, d, p, q, u)))
- else:
- raise BadKeyError("unknown key type %s" % keyType)
- _fromString_AGENTV3 = classmethod(_fromString_AGENTV3)
-
-
- def _guessStringType(Class, data):
- """
- Guess the type of key in data. The types map to _fromString_*
- methods.
- """
- if data.startswith('ssh-'):
- return 'public_openssh'
- elif data.startswith('-----BEGIN'):
- return 'private_openssh'
- elif data.startswith('{'):
- return 'public_lsh'
- elif data.startswith('('):
- return 'private_lsh'
- elif data.startswith('\x00\x00\x00\x07ssh-'):
- ignored, rest = common.getNS(data)
- count = 0
- while rest:
- count += 1
- ignored, rest = common.getMP(rest)
- if count > 4:
- return 'agentv3'
- else:
- return 'blob'
- _guessStringType = classmethod(_guessStringType)
-
-
- def __init__(self, keyObject):
- """
- Initialize a PublicKey with a C{Crypto.PublicKey.pubkey.pubkey}
- object.
-
- @type keyObject: C{Crypto.PublicKey.pubkey.pubkey}
- """
- self.keyObject = keyObject
-
-
- def __eq__(self, other):
- """
- Return True if other represents an object with the same key.
- """
- if type(self) == type(other):
- return self.type() == other.type() and self.data() == other.data()
- else:
- return NotImplemented
-
-
- def __ne__(self, other):
- """
- Return True if other represents anything other than this key.
- """
- result = self.__eq__(other)
- if result == NotImplemented:
- return result
- return not result
-
-
- def __repr__(self):
- """
- Return a pretty representation of this object.
- """
- lines = [
- '<%s %s (%s bits)' % (
- self.type(),
- self.isPublic() and 'Public Key' or 'Private Key',
- self.keyObject.size())]
- for k, v in sorted(self.data().items()):
- lines.append('attr %s:' % k)
- by = common.MP(v)[4:]
- while by:
- m = by[:15]
- by = by[15:]
- o = ''
- for c in m:
- o = o + '%02x:' % ord(c)
- if len(m) < 15:
- o = o[:-1]
- lines.append('\t' + o)
- lines[-1] = lines[-1] + '>'
- return '\n'.join(lines)
-
-
- def isPublic(self):
- """
- Returns True if this Key is a public key.
- """
- return not self.keyObject.has_private()
-
-
- def public(self):
- """
- Returns a version of this key containing only the public key data.
- If this is a public key, this may or may not be the same object
- as self.
- """
- return Key(self.keyObject.publickey())
-
-
- def fingerprint(self):
- """
- Get the user presentation of the fingerprint of this L{Key}. As
- described by U{RFC 4716 section
- 4}::
-
- The fingerprint of a public key consists of the output of the MD5
- message-digest algorithm [RFC1321]. The input to the algorithm is
- the public key data as specified by [RFC4253]. (...) The output
- of the (MD5) algorithm is presented to the user as a sequence of 16
- octets printed as hexadecimal with lowercase letters and separated
- by colons.
-
- @since: 8.2
-
- @return: the user presentation of this L{Key}'s fingerprint, as a
- string.
-
- @rtype: L{str}
- """
- return ':'.join([x.encode('hex') for x in md5(self.blob()).digest()])
-
-
- def type(self):
- """
- Return the type of the object we wrap. Currently this can only be
- 'RSA' or 'DSA'.
- """
- # the class is Crypto.PublicKey..
- mod = self.keyObject.__class__.__module__
- if mod.startswith('Crypto.PublicKey'):
- type = mod.split('.')[2]
- else:
- raise RuntimeError('unknown type of object: %r' % self.keyObject)
- if type in ('RSA', 'DSA'):
- return type
- else:
- raise RuntimeError('unknown type of key: %s' % type)
-
-
- def sshType(self):
- """
- Return the type of the object we wrap as defined in the ssh protocol.
- Currently this can only be 'ssh-rsa' or 'ssh-dss'.
- """
- return {'RSA': 'ssh-rsa', 'DSA': 'ssh-dss'}[self.type()]
-
-
- def data(self):
- """
- Return the values of the public key as a dictionary.
-
- @rtype: C{dict}
- """
- keyData = {}
- for name in self.keyObject.keydata:
- value = getattr(self.keyObject, name, None)
- if value is not None:
- keyData[name] = value
- return keyData
-
-
- def blob(self):
- """
- Return the public key blob for this key. The blob is the
- over-the-wire format for public keys:
-
- RSA keys::
- string 'ssh-rsa'
- integer e
- integer n
-
- DSA keys::
- string 'ssh-dss'
- integer p
- integer q
- integer g
- integer y
-
- @rtype: C{str}
- """
- type = self.type()
- data = self.data()
- if type == 'RSA':
- return (common.NS('ssh-rsa') + common.MP(data['e']) +
- common.MP(data['n']))
- elif type == 'DSA':
- return (common.NS('ssh-dss') + common.MP(data['p']) +
- common.MP(data['q']) + common.MP(data['g']) +
- common.MP(data['y']))
-
-
- def privateBlob(self):
- """
- Return the private key blob for this key. The blob is the
- over-the-wire format for private keys:
-
- RSA keys::
- string 'ssh-rsa'
- integer n
- integer e
- integer d
- integer u
- integer p
- integer q
-
- DSA keys::
- string 'ssh-dss'
- integer p
- integer q
- integer g
- integer y
- integer x
- """
- type = self.type()
- data = self.data()
- if type == 'RSA':
- return (common.NS('ssh-rsa') + common.MP(data['n']) +
- common.MP(data['e']) + common.MP(data['d']) +
- common.MP(data['u']) + common.MP(data['p']) +
- common.MP(data['q']))
- elif type == 'DSA':
- return (common.NS('ssh-dss') + common.MP(data['p']) +
- common.MP(data['q']) + common.MP(data['g']) +
- common.MP(data['y']) + common.MP(data['x']))
-
-
- def toString(self, type, extra=None):
- """
- Create a string representation of this key. If the key is a private
- key and you want the represenation of its public key, use
- C{key.public().toString()}. type maps to a _toString_* method.
-
- @param type: The type of string to emit. Currently supported values
- are C{'OPENSSH'}, C{'LSH'}, and C{'AGENTV3'}.
- @type type: L{str}
-
- @param extra: Any extra data supported by the selected format which
- is not part of the key itself. For public OpenSSH keys, this is
- a comment. For private OpenSSH keys, this is a passphrase to
- encrypt with.
- @type extra: L{str} or L{NoneType}
-
- @rtype: L{str}
- """
- method = getattr(self, '_toString_%s' % type.upper(), None)
- if method is None:
- raise BadKeyError('unknown type: %s' % type)
- if method.func_code.co_argcount == 2:
- return method(extra)
- else:
- return method()
-
-
- def _toString_OPENSSH(self, extra):
- """
- Return a public or private OpenSSH string. See
- _fromString_PUBLIC_OPENSSH and _fromString_PRIVATE_OPENSSH for the
- string formats. If extra is present, it represents a comment for a
- public key, or a passphrase for a private key.
-
- @param extra: Comment for a public key or passphrase for a
- private key
- @type extra: C{str}
-
- @rtype: C{str}
- """
- data = self.data()
- if self.isPublic():
- b64Data = base64.encodestring(self.blob()).replace('\n', '')
- if not extra:
- extra = ''
- return ('%s %s %s' % (self.sshType(), b64Data, extra)).strip()
- else:
- lines = ['-----BEGIN %s PRIVATE KEY-----' % self.type()]
- if self.type() == 'RSA':
- p, q = data['p'], data['q']
- objData = (0, data['n'], data['e'], data['d'], q, p,
- data['d'] % (q - 1), data['d'] % (p - 1),
- data['u'])
- else:
- objData = (0, data['p'], data['q'], data['g'], data['y'],
- data['x'])
- asn1Sequence = univ.Sequence()
- for index, value in itertools.izip(itertools.count(), objData):
- asn1Sequence.setComponentByPosition(index, univ.Integer(value))
- asn1Data = berEncoder.encode(asn1Sequence)
- if extra:
- iv = randbytes.secureRandom(8)
- hexiv = ''.join(['%02X' % ord(x) for x in iv])
- lines.append('Proc-Type: 4,ENCRYPTED')
- lines.append('DEK-Info: DES-EDE3-CBC,%s\n' % hexiv)
- ba = md5(extra + iv).digest()
- bb = md5(ba + extra + iv).digest()
- encKey = (ba + bb)[:24]
- padLen = 8 - (len(asn1Data) % 8)
- asn1Data += (chr(padLen) * padLen)
- asn1Data = DES3.new(encKey, DES3.MODE_CBC,
- iv).encrypt(asn1Data)
- b64Data = base64.encodestring(asn1Data).replace('\n', '')
- lines += [b64Data[i:i + 64] for i in range(0, len(b64Data), 64)]
- lines.append('-----END %s PRIVATE KEY-----' % self.type())
- return '\n'.join(lines)
-
-
- def _toString_LSH(self):
- """
- Return a public or private LSH key. See _fromString_PUBLIC_LSH and
- _fromString_PRIVATE_LSH for the key formats.
-
- @rtype: C{str}
- """
- data = self.data()
- if self.isPublic():
- if self.type() == 'RSA':
- keyData = sexpy.pack([['public-key',
- ['rsa-pkcs1-sha1',
- ['n', common.MP(data['n'])[4:]],
- ['e', common.MP(data['e'])[4:]]]]])
- elif self.type() == 'DSA':
- keyData = sexpy.pack([['public-key',
- ['dsa',
- ['p', common.MP(data['p'])[4:]],
- ['q', common.MP(data['q'])[4:]],
- ['g', common.MP(data['g'])[4:]],
- ['y', common.MP(data['y'])[4:]]]]])
- return '{' + base64.encodestring(keyData).replace('\n', '') + '}'
- else:
- if self.type() == 'RSA':
- p, q = data['p'], data['q']
- return sexpy.pack([['private-key',
- ['rsa-pkcs1',
- ['n', common.MP(data['n'])[4:]],
- ['e', common.MP(data['e'])[4:]],
- ['d', common.MP(data['d'])[4:]],
- ['p', common.MP(q)[4:]],
- ['q', common.MP(p)[4:]],
- ['a', common.MP(data['d'] % (q - 1))[4:]],
- ['b', common.MP(data['d'] % (p - 1))[4:]],
- ['c', common.MP(data['u'])[4:]]]]])
- elif self.type() == 'DSA':
- return sexpy.pack([['private-key',
- ['dsa',
- ['p', common.MP(data['p'])[4:]],
- ['q', common.MP(data['q'])[4:]],
- ['g', common.MP(data['g'])[4:]],
- ['y', common.MP(data['y'])[4:]],
- ['x', common.MP(data['x'])[4:]]]]])
-
-
- def _toString_AGENTV3(self):
- """
- Return a private Secure Shell Agent v3 key. See
- _fromString_AGENTV3 for the key format.
-
- @rtype: C{str}
- """
- data = self.data()
- if not self.isPublic():
- if self.type() == 'RSA':
- values = (data['e'], data['d'], data['n'], data['u'],
- data['p'], data['q'])
- elif self.type() == 'DSA':
- values = (data['p'], data['q'], data['g'], data['y'],
- data['x'])
- return common.NS(self.sshType()) + ''.join(map(common.MP, values))
-
-
- def sign(self, data):
- """
- Returns a signature with this Key.
-
- @type data: C{str}
- @rtype: C{str}
- """
- if self.type() == 'RSA':
- digest = pkcs1Digest(data, self.keyObject.size() / 8)
- signature = self.keyObject.sign(digest, '')[0]
- ret = common.NS(Util.number.long_to_bytes(signature))
- elif self.type() == 'DSA':
- digest = sha1(data).digest()
- randomBytes = randbytes.secureRandom(19)
- sig = self.keyObject.sign(digest, randomBytes)
- # SSH insists that the DSS signature blob be two 160-bit integers
- # concatenated together. The sig[0], [1] numbers from obj.sign
- # are just numbers, and could be any length from 0 to 160 bits.
- # Make sure they are padded out to 160 bits (20 bytes each)
- ret = common.NS(Util.number.long_to_bytes(sig[0], 20) +
- Util.number.long_to_bytes(sig[1], 20))
- return common.NS(self.sshType()) + ret
-
-
- def verify(self, signature, data):
- """
- Returns true if the signature for data is valid for this Key.
-
- @type signature: C{str}
- @type data: C{str}
- @rtype: C{bool}
- """
- if len(signature) == 40:
- # DSA key with no padding
- signatureType, signature = 'ssh-dss', common.NS(signature)
- else:
- signatureType, signature = common.getNS(signature)
- if signatureType != self.sshType():
- return False
- if self.type() == 'RSA':
- numbers = common.getMP(signature)
- digest = pkcs1Digest(data, self.keyObject.size() / 8)
- elif self.type() == 'DSA':
- signature = common.getNS(signature)[0]
- numbers = [Util.number.bytes_to_long(n) for n in signature[:20],
- signature[20:]]
- digest = sha1(data).digest()
- return self.keyObject.verify(digest, numbers)
-
-
-
-def objectType(obj):
- """
- Return the SSH key type corresponding to a
- C{Crypto.PublicKey.pubkey.pubkey} object.
-
- @type obj: C{Crypto.PublicKey.pubkey.pubkey}
- @rtype: C{str}
- """
- keyDataMapping = {
- ('n', 'e', 'd', 'p', 'q'): 'ssh-rsa',
- ('n', 'e', 'd', 'p', 'q', 'u'): 'ssh-rsa',
- ('y', 'g', 'p', 'q', 'x'): 'ssh-dss'
- }
- try:
- return keyDataMapping[tuple(obj.keydata)]
- except (KeyError, AttributeError):
- raise BadKeyError("invalid key object", obj)
-
-
-
-def pkcs1Pad(data, messageLength):
- """
- Pad out data to messageLength according to the PKCS#1 standard.
- @type data: C{str}
- @type messageLength: C{int}
- """
- lenPad = messageLength - 2 - len(data)
- return '\x01' + ('\xff' * lenPad) + '\x00' + data
-
-
-
-def pkcs1Digest(data, messageLength):
- """
- Create a message digest using the SHA1 hash algorithm according to the
- PKCS#1 standard.
- @type data: C{str}
- @type messageLength: C{str}
- """
- digest = sha1(data).digest()
- return pkcs1Pad(ID_SHA1 + digest, messageLength)
-
-
-
-def lenSig(obj):
- """
- Return the length of the signature in bytes for a key object.
-
- @type obj: C{Crypto.PublicKey.pubkey.pubkey}
- @rtype: C{long}
- """
- return obj.size() / 8
-
-
-ID_SHA1 = '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14'
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/service.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/service.py
deleted file mode 100644
index b5477c4..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/service.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-The parent class for all the SSH services. Currently implemented services
-are ssh-userauth and ssh-connection.
-
-Maintainer: Paul Swartz
-"""
-
-
-from twisted.python import log
-
-class SSHService(log.Logger):
- name = None # this is the ssh name for the service
- protocolMessages = {} # these map #'s -> protocol names
- transport = None # gets set later
-
- def serviceStarted(self):
- """
- called when the service is active on the transport.
- """
-
- def serviceStopped(self):
- """
- called when the service is stopped, either by the connection ending
- or by another service being started
- """
-
- def logPrefix(self):
- return "SSHService %s on %s" % (self.name,
- self.transport.transport.logPrefix())
-
- def packetReceived(self, messageNum, packet):
- """
- called when we receive a packet on the transport
- """
- #print self.protocolMessages
- if messageNum in self.protocolMessages:
- messageType = self.protocolMessages[messageNum]
- f = getattr(self,'ssh_%s' % messageType[4:],
- None)
- if f is not None:
- return f(packet)
- log.msg("couldn't handle %r" % messageNum)
- log.msg(repr(packet))
- self.transport.sendUnimplemented()
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/session.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/session.py
deleted file mode 100644
index e9eca3e..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/session.py
+++ /dev/null
@@ -1,348 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_session -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-This module contains the implementation of SSHSession, which (by default)
-allows access to a shell and a python interpreter over SSH.
-
-Maintainer: Paul Swartz
-"""
-
-import struct
-import signal
-import sys
-import os
-from zope.interface import implements
-
-from twisted.internet import interfaces, protocol
-from twisted.python import log
-from twisted.conch.interfaces import ISession
-from twisted.conch.ssh import common, channel
-
-class SSHSession(channel.SSHChannel):
-
- name = 'session'
- def __init__(self, *args, **kw):
- channel.SSHChannel.__init__(self, *args, **kw)
- self.buf = ''
- self.client = None
- self.session = None
-
- def request_subsystem(self, data):
- subsystem, ignored= common.getNS(data)
- log.msg('asking for subsystem "%s"' % subsystem)
- client = self.avatar.lookupSubsystem(subsystem, data)
- if client:
- pp = SSHSessionProcessProtocol(self)
- proto = wrapProcessProtocol(pp)
- client.makeConnection(proto)
- pp.makeConnection(wrapProtocol(client))
- self.client = pp
- return 1
- else:
- log.msg('failed to get subsystem')
- return 0
-
- def request_shell(self, data):
- log.msg('getting shell')
- if not self.session:
- self.session = ISession(self.avatar)
- try:
- pp = SSHSessionProcessProtocol(self)
- self.session.openShell(pp)
- except:
- log.deferr()
- return 0
- else:
- self.client = pp
- return 1
-
- def request_exec(self, data):
- if not self.session:
- self.session = ISession(self.avatar)
- f,data = common.getNS(data)
- log.msg('executing command "%s"' % f)
- try:
- pp = SSHSessionProcessProtocol(self)
- self.session.execCommand(pp, f)
- except:
- log.deferr()
- return 0
- else:
- self.client = pp
- return 1
-
- def request_pty_req(self, data):
- if not self.session:
- self.session = ISession(self.avatar)
- term, windowSize, modes = parseRequest_pty_req(data)
- log.msg('pty request: %s %s' % (term, windowSize))
- try:
- self.session.getPty(term, windowSize, modes)
- except:
- log.err()
- return 0
- else:
- return 1
-
- def request_window_change(self, data):
- if not self.session:
- self.session = ISession(self.avatar)
- winSize = parseRequest_window_change(data)
- try:
- self.session.windowChanged(winSize)
- except:
- log.msg('error changing window size')
- log.err()
- return 0
- else:
- return 1
-
- def dataReceived(self, data):
- if not self.client:
- #self.conn.sendClose(self)
- self.buf += data
- return
- self.client.transport.write(data)
-
- def extReceived(self, dataType, data):
- if dataType == connection.EXTENDED_DATA_STDERR:
- if self.client and hasattr(self.client.transport, 'writeErr'):
- self.client.transport.writeErr(data)
- else:
- log.msg('weird extended data: %s'%dataType)
-
- def eofReceived(self):
- if self.session:
- self.session.eofReceived()
- elif self.client:
- self.conn.sendClose(self)
-
- def closed(self):
- if self.session:
- self.session.closed()
- elif self.client:
- self.client.transport.loseConnection()
-
- #def closeReceived(self):
- # self.loseConnection() # don't know what to do with this
-
- def loseConnection(self):
- if self.client:
- self.client.transport.loseConnection()
- channel.SSHChannel.loseConnection(self)
-
-class _ProtocolWrapper(protocol.ProcessProtocol):
- """
- This class wraps a L{Protocol} instance in a L{ProcessProtocol} instance.
- """
- def __init__(self, proto):
- self.proto = proto
-
- def connectionMade(self): self.proto.connectionMade()
-
- def outReceived(self, data): self.proto.dataReceived(data)
-
- def processEnded(self, reason): self.proto.connectionLost(reason)
-
-class _DummyTransport:
-
- def __init__(self, proto):
- self.proto = proto
-
- def dataReceived(self, data):
- self.proto.transport.write(data)
-
- def write(self, data):
- self.proto.dataReceived(data)
-
- def writeSequence(self, seq):
- self.write(''.join(seq))
-
- def loseConnection(self):
- self.proto.connectionLost(protocol.connectionDone)
-
-def wrapProcessProtocol(inst):
- if isinstance(inst, protocol.Protocol):
- return _ProtocolWrapper(inst)
- else:
- return inst
-
-def wrapProtocol(proto):
- return _DummyTransport(proto)
-
-
-
-# SUPPORTED_SIGNALS is a list of signals that every session channel is supposed
-# to accept. See RFC 4254
-SUPPORTED_SIGNALS = ["ABRT", "ALRM", "FPE", "HUP", "ILL", "INT", "KILL",
- "PIPE", "QUIT", "SEGV", "TERM", "USR1", "USR2"]
-
-
-
-class SSHSessionProcessProtocol(protocol.ProcessProtocol):
- """I am both an L{IProcessProtocol} and an L{ITransport}.
-
- I am a transport to the remote endpoint and a process protocol to the
- local subsystem.
- """
-
- implements(interfaces.ITransport)
-
- # once initialized, a dictionary mapping signal values to strings
- # that follow RFC 4254.
- _signalValuesToNames = None
-
- def __init__(self, session):
- self.session = session
- self.lostOutOrErrFlag = False
-
- def connectionMade(self):
- if self.session.buf:
- self.transport.write(self.session.buf)
- self.session.buf = None
-
- def outReceived(self, data):
- self.session.write(data)
-
- def errReceived(self, err):
- self.session.writeExtended(connection.EXTENDED_DATA_STDERR, err)
-
- def outConnectionLost(self):
- """
- EOF should only be sent when both STDOUT and STDERR have been closed.
- """
- if self.lostOutOrErrFlag:
- self.session.conn.sendEOF(self.session)
- else:
- self.lostOutOrErrFlag = True
-
- def errConnectionLost(self):
- """
- See outConnectionLost().
- """
- self.outConnectionLost()
-
- def connectionLost(self, reason = None):
- self.session.loseConnection()
-
-
- def _getSignalName(self, signum):
- """
- Get a signal name given a signal number.
- """
- if self._signalValuesToNames is None:
- self._signalValuesToNames = {}
- # make sure that the POSIX ones are the defaults
- for signame in SUPPORTED_SIGNALS:
- signame = 'SIG' + signame
- sigvalue = getattr(signal, signame, None)
- if sigvalue is not None:
- self._signalValuesToNames[sigvalue] = signame
- for k, v in signal.__dict__.items():
- # Check for platform specific signals, ignoring Python specific
- # SIG_DFL and SIG_IGN
- if k.startswith('SIG') and not k.startswith('SIG_'):
- if v not in self._signalValuesToNames:
- self._signalValuesToNames[v] = k + '@' + sys.platform
- return self._signalValuesToNames[signum]
-
-
- def processEnded(self, reason=None):
- """
- When we are told the process ended, try to notify the other side about
- how the process ended using the exit-signal or exit-status requests.
- Also, close the channel.
- """
- if reason is not None:
- err = reason.value
- if err.signal is not None:
- signame = self._getSignalName(err.signal)
- if (getattr(os, 'WCOREDUMP', None) is not None and
- os.WCOREDUMP(err.status)):
- log.msg('exitSignal: %s (core dumped)' % (signame,))
- coreDumped = 1
- else:
- log.msg('exitSignal: %s' % (signame,))
- coreDumped = 0
- self.session.conn.sendRequest(self.session, 'exit-signal',
- common.NS(signame[3:]) + chr(coreDumped) +
- common.NS('') + common.NS(''))
- elif err.exitCode is not None:
- log.msg('exitCode: %r' % (err.exitCode,))
- self.session.conn.sendRequest(self.session, 'exit-status',
- struct.pack('>L', err.exitCode))
- self.session.loseConnection()
-
-
- def getHost(self):
- """
- Return the host from my session's transport.
- """
- return self.session.conn.transport.getHost()
-
-
- def getPeer(self):
- """
- Return the peer from my session's transport.
- """
- return self.session.conn.transport.getPeer()
-
-
- def write(self, data):
- self.session.write(data)
-
-
- def writeSequence(self, seq):
- self.session.write(''.join(seq))
-
-
- def loseConnection(self):
- self.session.loseConnection()
-
-
-
-class SSHSessionClient(protocol.Protocol):
-
- def dataReceived(self, data):
- if self.transport:
- self.transport.write(data)
-
-# methods factored out to make live easier on server writers
-def parseRequest_pty_req(data):
- """Parse the data from a pty-req request into usable data.
-
- @returns: a tuple of (terminal type, (rows, cols, xpixel, ypixel), modes)
- """
- term, rest = common.getNS(data)
- cols, rows, xpixel, ypixel = struct.unpack('>4L', rest[: 16])
- modes, ignored= common.getNS(rest[16:])
- winSize = (rows, cols, xpixel, ypixel)
- modes = [(ord(modes[i]), struct.unpack('>L', modes[i+1: i+5])[0]) for i in range(0, len(modes)-1, 5)]
- return term, winSize, modes
-
-def packRequest_pty_req(term, (rows, cols, xpixel, ypixel), modes):
- """Pack a pty-req request so that it is suitable for sending.
-
- NOTE: modes must be packed before being sent here.
- """
- termPacked = common.NS(term)
- winSizePacked = struct.pack('>4L', cols, rows, xpixel, ypixel)
- modesPacked = common.NS(modes) # depend on the client packing modes
- return termPacked + winSizePacked + modesPacked
-
-def parseRequest_window_change(data):
- """Parse the data from a window-change request into usuable data.
-
- @returns: a tuple of (rows, cols, xpixel, ypixel)
- """
- cols, rows, xpixel, ypixel = struct.unpack('>4L', data)
- return rows, cols, xpixel, ypixel
-
-def packRequest_window_change((rows, cols, xpixel, ypixel)):
- """Pack a window-change request so that it is suitable for sending.
- """
- return struct.pack('>4L', cols, rows, xpixel, ypixel)
-
-import connection
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/sexpy.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/sexpy.py
deleted file mode 100644
index 60c4328..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/sexpy.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-def parse(s):
- s = s.strip()
- expr = []
- while s:
- if s[0] == '(':
- newSexp = []
- if expr:
- expr[-1].append(newSexp)
- expr.append(newSexp)
- s = s[1:]
- continue
- if s[0] == ')':
- aList = expr.pop()
- s=s[1:]
- if not expr:
- assert not s
- return aList
- continue
- i = 0
- while s[i].isdigit(): i+=1
- assert i
- length = int(s[:i])
- data = s[i+1:i+1+length]
- expr[-1].append(data)
- s=s[i+1+length:]
- assert 0, "this should not happen"
-
-def pack(sexp):
- s = ""
- for o in sexp:
- if type(o) in (type(()), type([])):
- s+='('
- s+=pack(o)
- s+=')'
- else:
- s+='%i:%s' % (len(o), o)
- return s
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/transport.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/transport.py
deleted file mode 100644
index 843a6de..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/transport.py
+++ /dev/null
@@ -1,1639 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_transport -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-The lowest level SSH protocol. This handles the key negotiation, the
-encryption and the compression. The transport layer is described in
-RFC 4253.
-
-Maintainer: Paul Swartz
-"""
-
-# base library imports
-import struct
-import zlib
-import array
-from hashlib import md5, sha1
-import string
-import hmac
-
-# external library imports
-from Crypto import Util
-
-# twisted imports
-from twisted.internet import protocol, defer
-
-from twisted.conch import error
-from twisted.python import log, randbytes
-
-
-# sibling imports
-from twisted.conch.ssh import address, keys
-from twisted.conch.ssh.common import NS, getNS, MP, getMP, _MPpow, ffs
-
-
-def _getRandomNumber(random, bits):
- """
- Generate a random number in the range [0, 2 ** bits).
-
- @param bits: The number of bits in the result.
- @type bits: C{int}
-
- @rtype: C{int} or C{long}
- @return: The newly generated random number.
-
- @raise ValueError: if C{bits} is not a multiple of 8.
- """
- if bits % 8:
- raise ValueError("bits (%d) must be a multiple of 8" % (bits,))
- bytes = random(bits / 8)
- result = Util.number.bytes_to_long(bytes)
- return result
-
-
-
-def _generateX(random, bits):
- """
- Generate a new value for the private key x.
-
- From RFC 2631, section 2.2::
-
- X9.42 requires that the private key x be in the interval
- [2, (q - 2)]. x should be randomly generated in this interval.
- """
- while True:
- x = _getRandomNumber(random, bits)
- if 2 <= x <= (2 ** bits) - 2:
- return x
-
-
-class _MACParams(tuple):
- """
- L{_MACParams} represents the parameters necessary to compute SSH MAC
- (Message Authenticate Codes).
-
- L{_MACParams} is a L{tuple} subclass to maintain compatibility with older
- versions of the code. The elements of a L{_MACParams} are::
-
- 0. The digest object used for the MAC
- 1. The inner pad ("ipad") string
- 2. The outer pad ("opad") string
- 3. The size of the digest produced by the digest object
-
- L{_MACParams} is also an object lesson in why tuples are a bad type for
- public APIs.
-
- @ivar key: The HMAC key which will be used.
- """
-
-
-
-class SSHTransportBase(protocol.Protocol):
- """
- Protocol supporting basic SSH functionality: sending/receiving packets
- and message dispatch. To connect to or run a server, you must use
- SSHClientTransport or SSHServerTransport.
-
- @ivar protocolVersion: A string representing the version of the SSH
- protocol we support. Currently defaults to '2.0'.
-
- @ivar version: A string representing the version of the server or client.
- Currently defaults to 'Twisted'.
-
- @ivar comment: An optional string giving more information about the
- server or client.
-
- @ivar supportedCiphers: A list of strings representing the encryption
- algorithms supported, in order from most-preferred to least.
-
- @ivar supportedMACs: A list of strings representing the message
- authentication codes (hashes) supported, in order from most-preferred
- to least. Both this and supportedCiphers can include 'none' to use
- no encryption or authentication, but that must be done manually,
-
- @ivar supportedKeyExchanges: A list of strings representing the
- key exchanges supported, in order from most-preferred to least.
-
- @ivar supportedPublicKeys: A list of strings representing the
- public key types supported, in order from most-preferred to least.
-
- @ivar supportedCompressions: A list of strings representing compression
- types supported, from most-preferred to least.
-
- @ivar supportedLanguages: A list of strings representing languages
- supported, from most-preferred to least.
-
- @ivar supportedVersions: A container of strings representing supported ssh
- protocol version numbers.
-
- @ivar isClient: A boolean indicating whether this is a client or server.
-
- @ivar gotVersion: A boolean indicating whether we have receieved the
- version string from the other side.
-
- @ivar buf: Data we've received but hasn't been parsed into a packet.
-
- @ivar outgoingPacketSequence: the sequence number of the next packet we
- will send.
-
- @ivar incomingPacketSequence: the sequence number of the next packet we
- are expecting from the other side.
-
- @ivar outgoingCompression: an object supporting the .compress(str) and
- .flush() methods, or None if there is no outgoing compression. Used to
- compress outgoing data.
-
- @ivar outgoingCompressionType: A string representing the outgoing
- compression type.
-
- @ivar incomingCompression: an object supporting the .decompress(str)
- method, or None if there is no incoming compression. Used to
- decompress incoming data.
-
- @ivar incomingCompressionType: A string representing the incoming
- compression type.
-
- @ivar ourVersionString: the version string that we sent to the other side.
- Used in the key exchange.
-
- @ivar otherVersionString: the version string sent by the other side. Used
- in the key exchange.
-
- @ivar ourKexInitPayload: the MSG_KEXINIT payload we sent. Used in the key
- exchange.
-
- @ivar otherKexInitPayload: the MSG_KEXINIT payload we received. Used in
- the key exchange
-
- @ivar sessionID: a string that is unique to this SSH session. Created as
- part of the key exchange, sessionID is used to generate the various
- encryption and authentication keys.
-
- @ivar service: an SSHService instance, or None. If it's set to an object,
- it's the currently running service.
-
- @ivar kexAlg: the agreed-upon key exchange algorithm.
-
- @ivar keyAlg: the agreed-upon public key type for the key exchange.
-
- @ivar currentEncryptions: an SSHCiphers instance. It represents the
- current encryption and authentication options for the transport.
-
- @ivar nextEncryptions: an SSHCiphers instance. Held here until the
- MSG_NEWKEYS messages are exchanged, when nextEncryptions is
- transitioned to currentEncryptions.
-
- @ivar first: the first bytes of the next packet. In order to avoid
- decrypting data twice, the first bytes are decrypted and stored until
- the whole packet is available.
-
- @ivar _keyExchangeState: The current protocol state with respect to key
- exchange. This is either C{_KEY_EXCHANGE_NONE} if no key exchange is
- in progress (and returns to this value after any key exchange
- completqes), C{_KEY_EXCHANGE_REQUESTED} if this side of the connection
- initiated a key exchange, and C{_KEY_EXCHANGE_PROGRESSING} if the other
- side of the connection initiated a key exchange. C{_KEY_EXCHANGE_NONE}
- is the initial value (however SSH connections begin with key exchange,
- so it will quickly change to another state).
-
- @ivar _blockedByKeyExchange: Whenever C{_keyExchangeState} is not
- C{_KEY_EXCHANGE_NONE}, this is a C{list} of pending messages which were
- passed to L{sendPacket} but could not be sent because it is not legal
- to send them while a key exchange is in progress. When the key
- exchange completes, another attempt is made to send these messages.
- """
-
-
- protocolVersion = '2.0'
- version = 'Twisted'
- comment = ''
- ourVersionString = ('SSH-' + protocolVersion + '-' + version + ' '
- + comment).strip()
- supportedCiphers = ['aes256-ctr', 'aes256-cbc', 'aes192-ctr', 'aes192-cbc',
- 'aes128-ctr', 'aes128-cbc', 'cast128-ctr',
- 'cast128-cbc', 'blowfish-ctr', 'blowfish-cbc',
- '3des-ctr', '3des-cbc'] # ,'none']
- supportedMACs = ['hmac-sha1', 'hmac-md5'] # , 'none']
- # both of the above support 'none', but for security are disabled by
- # default. to enable them, subclass this class and add it, or do:
- # SSHTransportBase.supportedCiphers.append('none')
- supportedKeyExchanges = ['diffie-hellman-group-exchange-sha1',
- 'diffie-hellman-group1-sha1']
- supportedPublicKeys = ['ssh-rsa', 'ssh-dss']
- supportedCompressions = ['none', 'zlib']
- supportedLanguages = ()
- supportedVersions = ('1.99', '2.0')
- isClient = False
- gotVersion = False
- buf = ''
- outgoingPacketSequence = 0
- incomingPacketSequence = 0
- outgoingCompression = None
- incomingCompression = None
- sessionID = None
- service = None
-
- # There is no key exchange activity in progress.
- _KEY_EXCHANGE_NONE = '_KEY_EXCHANGE_NONE'
-
- # Key exchange is in progress and we started it.
- _KEY_EXCHANGE_REQUESTED = '_KEY_EXCHANGE_REQUESTED'
-
- # Key exchange is in progress and both sides have sent KEXINIT messages.
- _KEY_EXCHANGE_PROGRESSING = '_KEY_EXCHANGE_PROGRESSING'
-
- # There is a fourth conceptual state not represented here: KEXINIT received
- # but not sent. Since we always send a KEXINIT as soon as we get it, we
- # can't ever be in that state.
-
- # The current key exchange state.
- _keyExchangeState = _KEY_EXCHANGE_NONE
- _blockedByKeyExchange = None
-
- def connectionLost(self, reason):
- if self.service:
- self.service.serviceStopped()
- if hasattr(self, 'avatar'):
- self.logoutFunction()
- log.msg('connection lost')
-
-
- def connectionMade(self):
- """
- Called when the connection is made to the other side. We sent our
- version and the MSG_KEXINIT packet.
- """
- self.transport.write('%s\r\n' % (self.ourVersionString,))
- self.currentEncryptions = SSHCiphers('none', 'none', 'none', 'none')
- self.currentEncryptions.setKeys('', '', '', '', '', '')
- self.sendKexInit()
-
-
- def sendKexInit(self):
- """
- Send a I{KEXINIT} message to initiate key exchange or to respond to a
- key exchange initiated by the peer.
-
- @raise RuntimeError: If a key exchange has already been started and it
- is not appropriate to send a I{KEXINIT} message at this time.
-
- @return: C{None}
- """
- if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
- raise RuntimeError(
- "Cannot send KEXINIT while key exchange state is %r" % (
- self._keyExchangeState,))
-
- self.ourKexInitPayload = (chr(MSG_KEXINIT) +
- randbytes.secureRandom(16) +
- NS(','.join(self.supportedKeyExchanges)) +
- NS(','.join(self.supportedPublicKeys)) +
- NS(','.join(self.supportedCiphers)) +
- NS(','.join(self.supportedCiphers)) +
- NS(','.join(self.supportedMACs)) +
- NS(','.join(self.supportedMACs)) +
- NS(','.join(self.supportedCompressions)) +
- NS(','.join(self.supportedCompressions)) +
- NS(','.join(self.supportedLanguages)) +
- NS(','.join(self.supportedLanguages)) +
- '\000' + '\000\000\000\000')
- self.sendPacket(MSG_KEXINIT, self.ourKexInitPayload[1:])
- self._keyExchangeState = self._KEY_EXCHANGE_REQUESTED
- self._blockedByKeyExchange = []
-
-
- def _allowedKeyExchangeMessageType(self, messageType):
- """
- Determine if the given message type may be sent while key exchange is
- in progress.
-
- @param messageType: The type of message
- @type messageType: C{int}
-
- @return: C{True} if the given type of message may be sent while key
- exchange is in progress, C{False} if it may not.
- @rtype: C{bool}
-
- @see: U{http://tools.ietf.org/html/rfc4253#section-7.1}
- """
- # Written somewhat peculularly to reflect the way the specification
- # defines the allowed message types.
- if 1 <= messageType <= 19:
- return messageType not in (MSG_SERVICE_REQUEST, MSG_SERVICE_ACCEPT)
- if 20 <= messageType <= 29:
- return messageType not in (MSG_KEXINIT,)
- return 30 <= messageType <= 49
-
-
- def sendPacket(self, messageType, payload):
- """
- Sends a packet. If it's been set up, compress the data, encrypt it,
- and authenticate it before sending. If key exchange is in progress and
- the message is not part of key exchange, queue it to be sent later.
-
- @param messageType: The type of the packet; generally one of the
- MSG_* values.
- @type messageType: C{int}
- @param payload: The payload for the message.
- @type payload: C{str}
- """
- if self._keyExchangeState != self._KEY_EXCHANGE_NONE:
- if not self._allowedKeyExchangeMessageType(messageType):
- self._blockedByKeyExchange.append((messageType, payload))
- return
-
- payload = chr(messageType) + payload
- if self.outgoingCompression:
- payload = (self.outgoingCompression.compress(payload)
- + self.outgoingCompression.flush(2))
- bs = self.currentEncryptions.encBlockSize
- # 4 for the packet length and 1 for the padding length
- totalSize = 5 + len(payload)
- lenPad = bs - (totalSize % bs)
- if lenPad < 4:
- lenPad = lenPad + bs
- packet = (struct.pack('!LB',
- totalSize + lenPad - 4, lenPad) +
- payload + randbytes.secureRandom(lenPad))
- encPacket = (
- self.currentEncryptions.encrypt(packet) +
- self.currentEncryptions.makeMAC(
- self.outgoingPacketSequence, packet))
- self.transport.write(encPacket)
- self.outgoingPacketSequence += 1
-
-
- def getPacket(self):
- """
- Try to return a decrypted, authenticated, and decompressed packet
- out of the buffer. If there is not enough data, return None.
-
- @rtype: C{str}/C{None}
- """
- bs = self.currentEncryptions.decBlockSize
- ms = self.currentEncryptions.verifyDigestSize
- if len(self.buf) < bs: return # not enough data
- if not hasattr(self, 'first'):
- first = self.currentEncryptions.decrypt(self.buf[:bs])
- else:
- first = self.first
- del self.first
- packetLen, paddingLen = struct.unpack('!LB', first[:5])
- if packetLen > 1048576: # 1024 ** 2
- self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
- 'bad packet length %s' % packetLen)
- return
- if len(self.buf) < packetLen + 4 + ms:
- self.first = first
- return # not enough packet
- if(packetLen + 4) % bs != 0:
- self.sendDisconnect(
- DISCONNECT_PROTOCOL_ERROR,
- 'bad packet mod (%i%%%i == %i)' % (packetLen + 4, bs,
- (packetLen + 4) % bs))
- return
- encData, self.buf = self.buf[:4 + packetLen], self.buf[4 + packetLen:]
- packet = first + self.currentEncryptions.decrypt(encData[bs:])
- if len(packet) != 4 + packetLen:
- self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
- 'bad decryption')
- return
- if ms:
- macData, self.buf = self.buf[:ms], self.buf[ms:]
- if not self.currentEncryptions.verify(self.incomingPacketSequence,
- packet, macData):
- self.sendDisconnect(DISCONNECT_MAC_ERROR, 'bad MAC')
- return
- payload = packet[5:-paddingLen]
- if self.incomingCompression:
- try:
- payload = self.incomingCompression.decompress(payload)
- except: # bare except, because who knows what kind of errors
- # decompression can raise
- log.err()
- self.sendDisconnect(DISCONNECT_COMPRESSION_ERROR,
- 'compression error')
- return
- self.incomingPacketSequence += 1
- return payload
-
-
- def _unsupportedVersionReceived(self, remoteVersion):
- """
- Called when an unsupported version of the ssh protocol is received from
- the remote endpoint.
-
- @param remoteVersion: remote ssh protocol version which is unsupported
- by us.
- @type remoteVersion: C{str}
- """
- self.sendDisconnect(DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED,
- 'bad version ' + remoteVersion)
-
-
- def dataReceived(self, data):
- """
- First, check for the version string (SSH-2.0-*). After that has been
- received, this method adds data to the buffer, and pulls out any
- packets.
-
- @type data: C{str}
- """
- self.buf = self.buf + data
- if not self.gotVersion:
- if self.buf.find('\n', self.buf.find('SSH-')) == -1:
- return
- lines = self.buf.split('\n')
- for p in lines:
- if p.startswith('SSH-'):
- self.gotVersion = True
- self.otherVersionString = p.strip()
- remoteVersion = p.split('-')[1]
- if remoteVersion not in self.supportedVersions:
- self._unsupportedVersionReceived(remoteVersion)
- return
- i = lines.index(p)
- self.buf = '\n'.join(lines[i + 1:])
- packet = self.getPacket()
- while packet:
- messageNum = ord(packet[0])
- self.dispatchMessage(messageNum, packet[1:])
- packet = self.getPacket()
-
-
- def dispatchMessage(self, messageNum, payload):
- """
- Send a received message to the appropriate method.
-
- @type messageNum: C{int}
- @type payload: c{str}
- """
- if messageNum < 50 and messageNum in messages:
- messageType = messages[messageNum][4:]
- f = getattr(self, 'ssh_%s' % messageType, None)
- if f is not None:
- f(payload)
- else:
- log.msg("couldn't handle %s" % messageType)
- log.msg(repr(payload))
- self.sendUnimplemented()
- elif self.service:
- log.callWithLogger(self.service, self.service.packetReceived,
- messageNum, payload)
- else:
- log.msg("couldn't handle %s" % messageNum)
- log.msg(repr(payload))
- self.sendUnimplemented()
-
- def getPeer(self):
- """
- Returns an L{SSHTransportAddress} corresponding to the other (peer)
- side of this transport.
-
- @return: L{SSHTransportAddress} for the peer
- @rtype: L{SSHTransportAddress}
- @since: 12.1
- """
- return address.SSHTransportAddress(self.transport.getPeer())
-
- def getHost(self):
- """
- Returns an L{SSHTransportAddress} corresponding to the this side of
- transport.
-
- @return: L{SSHTransportAddress} for the peer
- @rtype: L{SSHTransportAddress}
- @since: 12.1
- """
- return address.SSHTransportAddress(self.transport.getHost())
-
-
- # Client-initiated rekeying looks like this:
- #
- # C> MSG_KEXINIT
- # S> MSG_KEXINIT
- # C> MSG_KEX_DH_GEX_REQUEST or MSG_KEXDH_INIT
- # S> MSG_KEX_DH_GEX_GROUP or MSG_KEXDH_REPLY
- # C> MSG_KEX_DH_GEX_INIT or --
- # S> MSG_KEX_DH_GEX_REPLY or --
- # C> MSG_NEWKEYS
- # S> MSG_NEWKEYS
- #
- # Server-initiated rekeying is the same, only the first two messages are
- # switched.
-
- def ssh_KEXINIT(self, packet):
- """
- Called when we receive a MSG_KEXINIT message. Payload::
- bytes[16] cookie
- string keyExchangeAlgorithms
- string keyAlgorithms
- string incomingEncryptions
- string outgoingEncryptions
- string incomingAuthentications
- string outgoingAuthentications
- string incomingCompressions
- string outgoingCompressions
- string incomingLanguages
- string outgoingLanguages
- bool firstPacketFollows
- unit32 0 (reserved)
-
- Starts setting up the key exchange, keys, encryptions, and
- authentications. Extended by ssh_KEXINIT in SSHServerTransport and
- SSHClientTransport.
- """
- self.otherKexInitPayload = chr(MSG_KEXINIT) + packet
- #cookie = packet[: 16] # taking this is useless
- k = getNS(packet[16:], 10)
- strings, rest = k[:-1], k[-1]
- (kexAlgs, keyAlgs, encCS, encSC, macCS, macSC, compCS, compSC, langCS,
- langSC) = [s.split(',') for s in strings]
- # these are the server directions
- outs = [encSC, macSC, compSC]
- ins = [encCS, macSC, compCS]
- if self.isClient:
- outs, ins = ins, outs # switch directions
- server = (self.supportedKeyExchanges, self.supportedPublicKeys,
- self.supportedCiphers, self.supportedCiphers,
- self.supportedMACs, self.supportedMACs,
- self.supportedCompressions, self.supportedCompressions)
- client = (kexAlgs, keyAlgs, outs[0], ins[0], outs[1], ins[1],
- outs[2], ins[2])
- if self.isClient:
- server, client = client, server
- self.kexAlg = ffs(client[0], server[0])
- self.keyAlg = ffs(client[1], server[1])
- self.nextEncryptions = SSHCiphers(
- ffs(client[2], server[2]),
- ffs(client[3], server[3]),
- ffs(client[4], server[4]),
- ffs(client[5], server[5]))
- self.outgoingCompressionType = ffs(client[6], server[6])
- self.incomingCompressionType = ffs(client[7], server[7])
- if None in (self.kexAlg, self.keyAlg, self.outgoingCompressionType,
- self.incomingCompressionType):
- self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
- "couldn't match all kex parts")
- return
- if None in self.nextEncryptions.__dict__.values():
- self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
- "couldn't match all kex parts")
- return
- log.msg('kex alg, key alg: %s %s' % (self.kexAlg, self.keyAlg))
- log.msg('outgoing: %s %s %s' % (self.nextEncryptions.outCipType,
- self.nextEncryptions.outMACType,
- self.outgoingCompressionType))
- log.msg('incoming: %s %s %s' % (self.nextEncryptions.inCipType,
- self.nextEncryptions.inMACType,
- self.incomingCompressionType))
-
- if self._keyExchangeState == self._KEY_EXCHANGE_REQUESTED:
- self._keyExchangeState = self._KEY_EXCHANGE_PROGRESSING
- else:
- self.sendKexInit()
-
- return kexAlgs, keyAlgs, rest # for SSHServerTransport to use
-
-
- def ssh_DISCONNECT(self, packet):
- """
- Called when we receive a MSG_DISCONNECT message. Payload::
- long code
- string description
-
- This means that the other side has disconnected. Pass the message up
- and disconnect ourselves.
- """
- reasonCode = struct.unpack('>L', packet[: 4])[0]
- description, foo = getNS(packet[4:])
- self.receiveError(reasonCode, description)
- self.transport.loseConnection()
-
-
- def ssh_IGNORE(self, packet):
- """
- Called when we receieve a MSG_IGNORE message. No payload.
- This means nothing; we simply return.
- """
-
-
- def ssh_UNIMPLEMENTED(self, packet):
- """
- Called when we receieve a MSG_UNIMPLEMENTED message. Payload::
- long packet
-
- This means that the other side did not implement one of our packets.
- """
- seqnum, = struct.unpack('>L', packet)
- self.receiveUnimplemented(seqnum)
-
-
- def ssh_DEBUG(self, packet):
- """
- Called when we receieve a MSG_DEBUG message. Payload::
- bool alwaysDisplay
- string message
- string language
-
- This means the other side has passed along some debugging info.
- """
- alwaysDisplay = bool(packet[0])
- message, lang, foo = getNS(packet[1:], 2)
- self.receiveDebug(alwaysDisplay, message, lang)
-
-
- def setService(self, service):
- """
- Set our service to service and start it running. If we were
- running a service previously, stop it first.
-
- @type service: C{SSHService}
- """
- log.msg('starting service %s' % service.name)
- if self.service:
- self.service.serviceStopped()
- self.service = service
- service.transport = self
- self.service.serviceStarted()
-
-
- def sendDebug(self, message, alwaysDisplay=False, language=''):
- """
- Send a debug message to the other side.
-
- @param message: the message to send.
- @type message: C{str}
- @param alwaysDisplay: if True, tell the other side to always
- display this message.
- @type alwaysDisplay: C{bool}
- @param language: optionally, the language the message is in.
- @type language: C{str}
- """
- self.sendPacket(MSG_DEBUG, chr(alwaysDisplay) + NS(message) +
- NS(language))
-
-
- def sendIgnore(self, message):
- """
- Send a message that will be ignored by the other side. This is
- useful to fool attacks based on guessing packet sizes in the
- encrypted stream.
-
- @param message: data to send with the message
- @type message: C{str}
- """
- self.sendPacket(MSG_IGNORE, NS(message))
-
-
- def sendUnimplemented(self):
- """
- Send a message to the other side that the last packet was not
- understood.
- """
- seqnum = self.incomingPacketSequence
- self.sendPacket(MSG_UNIMPLEMENTED, struct.pack('!L', seqnum))
-
-
- def sendDisconnect(self, reason, desc):
- """
- Send a disconnect message to the other side and then disconnect.
-
- @param reason: the reason for the disconnect. Should be one of the
- DISCONNECT_* values.
- @type reason: C{int}
- @param desc: a descrption of the reason for the disconnection.
- @type desc: C{str}
- """
- self.sendPacket(
- MSG_DISCONNECT, struct.pack('>L', reason) + NS(desc) + NS(''))
- log.msg('Disconnecting with error, code %s\nreason: %s' % (reason,
- desc))
- self.transport.loseConnection()
-
-
- def _getKey(self, c, sharedSecret, exchangeHash):
- """
- Get one of the keys for authentication/encryption.
-
- @type c: C{str}
- @type sharedSecret: C{str}
- @type exchangeHash: C{str}
- """
- k1 = sha1(sharedSecret + exchangeHash + c + self.sessionID)
- k1 = k1.digest()
- k2 = sha1(sharedSecret + exchangeHash + k1).digest()
- return k1 + k2
-
-
- def _keySetup(self, sharedSecret, exchangeHash):
- """
- Set up the keys for the connection and sends MSG_NEWKEYS when
- finished,
-
- @param sharedSecret: a secret string agreed upon using a Diffie-
- Hellman exchange, so it is only shared between
- the server and the client.
- @type sharedSecret: C{str}
- @param exchangeHash: A hash of various data known by both sides.
- @type exchangeHash: C{str}
- """
- if not self.sessionID:
- self.sessionID = exchangeHash
- initIVCS = self._getKey('A', sharedSecret, exchangeHash)
- initIVSC = self._getKey('B', sharedSecret, exchangeHash)
- encKeyCS = self._getKey('C', sharedSecret, exchangeHash)
- encKeySC = self._getKey('D', sharedSecret, exchangeHash)
- integKeyCS = self._getKey('E', sharedSecret, exchangeHash)
- integKeySC = self._getKey('F', sharedSecret, exchangeHash)
- outs = [initIVSC, encKeySC, integKeySC]
- ins = [initIVCS, encKeyCS, integKeyCS]
- if self.isClient: # reverse for the client
- log.msg('REVERSE')
- outs, ins = ins, outs
- self.nextEncryptions.setKeys(outs[0], outs[1], ins[0], ins[1],
- outs[2], ins[2])
- self.sendPacket(MSG_NEWKEYS, '')
-
-
- def _newKeys(self):
- """
- Called back by a subclass once a I{MSG_NEWKEYS} message has been
- received. This indicates key exchange has completed and new encryption
- and compression parameters should be adopted. Any messages which were
- queued during key exchange will also be flushed.
- """
- log.msg('NEW KEYS')
- self.currentEncryptions = self.nextEncryptions
- if self.outgoingCompressionType == 'zlib':
- self.outgoingCompression = zlib.compressobj(6)
- if self.incomingCompressionType == 'zlib':
- self.incomingCompression = zlib.decompressobj()
-
- self._keyExchangeState = self._KEY_EXCHANGE_NONE
- messages = self._blockedByKeyExchange
- self._blockedByKeyExchange = None
- for (messageType, payload) in messages:
- self.sendPacket(messageType, payload)
-
-
- def isEncrypted(self, direction="out"):
- """
- Return True if the connection is encrypted in the given direction.
- Direction must be one of ["out", "in", "both"].
- """
- if direction == "out":
- return self.currentEncryptions.outCipType != 'none'
- elif direction == "in":
- return self.currentEncryptions.inCipType != 'none'
- elif direction == "both":
- return self.isEncrypted("in") and self.isEncrypted("out")
- else:
- raise TypeError('direction must be "out", "in", or "both"')
-
-
- def isVerified(self, direction="out"):
- """
- Return True if the connecction is verified/authenticated in the
- given direction. Direction must be one of ["out", "in", "both"].
- """
- if direction == "out":
- return self.currentEncryptions.outMACType != 'none'
- elif direction == "in":
- return self.currentEncryptions.inMACType != 'none'
- elif direction == "both":
- return self.isVerified("in")and self.isVerified("out")
- else:
- raise TypeError('direction must be "out", "in", or "both"')
-
-
- def loseConnection(self):
- """
- Lose the connection to the other side, sending a
- DISCONNECT_CONNECTION_LOST message.
- """
- self.sendDisconnect(DISCONNECT_CONNECTION_LOST,
- "user closed connection")
-
-
- # client methods
- def receiveError(self, reasonCode, description):
- """
- Called when we receive a disconnect error message from the other
- side.
-
- @param reasonCode: the reason for the disconnect, one of the
- DISCONNECT_ values.
- @type reasonCode: C{int}
- @param description: a human-readable description of the
- disconnection.
- @type description: C{str}
- """
- log.msg('Got remote error, code %s\nreason: %s' % (reasonCode,
- description))
-
-
- def receiveUnimplemented(self, seqnum):
- """
- Called when we receive an unimplemented packet message from the other
- side.
-
- @param seqnum: the sequence number that was not understood.
- @type seqnum: C{int}
- """
- log.msg('other side unimplemented packet #%s' % seqnum)
-
-
- def receiveDebug(self, alwaysDisplay, message, lang):
- """
- Called when we receive a debug message from the other side.
-
- @param alwaysDisplay: if True, this message should always be
- displayed.
- @type alwaysDisplay: C{bool}
- @param message: the debug message
- @type message: C{str}
- @param lang: optionally the language the message is in.
- @type lang: C{str}
- """
- if alwaysDisplay:
- log.msg('Remote Debug Message: %s' % message)
-
-
-
-class SSHServerTransport(SSHTransportBase):
- """
- SSHServerTransport implements the server side of the SSH protocol.
-
- @ivar isClient: since we are never the client, this is always False.
-
- @ivar ignoreNextPacket: if True, ignore the next key exchange packet. This
- is set when the client sends a guessed key exchange packet but with
- an incorrect guess.
-
- @ivar dhGexRequest: the KEX_DH_GEX_REQUEST(_OLD) that the client sent.
- The key generation needs this to be stored.
-
- @ivar g: the Diffie-Hellman group generator.
-
- @ivar p: the Diffie-Hellman group prime.
- """
- isClient = False
- ignoreNextPacket = 0
-
-
- def ssh_KEXINIT(self, packet):
- """
- Called when we receive a MSG_KEXINIT message. For a description
- of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally,
- this method checks if a guessed key exchange packet was sent. If
- it was sent, and it guessed incorrectly, the next key exchange
- packet MUST be ignored.
- """
- retval = SSHTransportBase.ssh_KEXINIT(self, packet)
- if not retval: # disconnected
- return
- else:
- kexAlgs, keyAlgs, rest = retval
- if ord(rest[0]): # first_kex_packet_follows
- if (kexAlgs[0] != self.supportedKeyExchanges[0] or
- keyAlgs[0] != self.supportedPublicKeys[0]):
- self.ignoreNextPacket = True # guess was wrong
-
-
- def _ssh_KEXDH_INIT(self, packet):
- """
- Called to handle the beginning of a diffie-hellman-group1-sha1 key
- exchange.
-
- Unlike other message types, this is not dispatched automatically. It
- is called from C{ssh_KEX_DH_GEX_REQUEST_OLD} because an extra check is
- required to determine if this is really a KEXDH_INIT message or if it
- is a KEX_DH_GEX_REQUEST_OLD message.
-
- The KEXDH_INIT (for diffie-hellman-group1-sha1 exchanges) payload::
-
- integer e (the client's Diffie-Hellman public key)
-
- We send the KEXDH_REPLY with our host key and signature.
- """
- clientDHpublicKey, foo = getMP(packet)
- y = _getRandomNumber(randbytes.secureRandom, 512)
- serverDHpublicKey = _MPpow(DH_GENERATOR, y, DH_PRIME)
- sharedSecret = _MPpow(clientDHpublicKey, y, DH_PRIME)
- h = sha1()
- h.update(NS(self.otherVersionString))
- h.update(NS(self.ourVersionString))
- h.update(NS(self.otherKexInitPayload))
- h.update(NS(self.ourKexInitPayload))
- h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
- h.update(MP(clientDHpublicKey))
- h.update(serverDHpublicKey)
- h.update(sharedSecret)
- exchangeHash = h.digest()
- self.sendPacket(
- MSG_KEXDH_REPLY,
- NS(self.factory.publicKeys[self.keyAlg].blob()) +
- serverDHpublicKey +
- NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
- self._keySetup(sharedSecret, exchangeHash)
-
-
- def ssh_KEX_DH_GEX_REQUEST_OLD(self, packet):
- """
- This represents two different key exchange methods that share the same
- integer value. If the message is determined to be a KEXDH_INIT,
- C{_ssh_KEXDH_INIT} is called to handle it. Otherwise, for
- KEX_DH_GEX_REQUEST_OLD (for diffie-hellman-group-exchange-sha1)
- payload::
-
- integer ideal (ideal size for the Diffie-Hellman prime)
-
- We send the KEX_DH_GEX_GROUP message with the group that is
- closest in size to ideal.
-
- If we were told to ignore the next key exchange packet by ssh_KEXINIT,
- drop it on the floor and return.
- """
- if self.ignoreNextPacket:
- self.ignoreNextPacket = 0
- return
-
- # KEXDH_INIT and KEX_DH_GEX_REQUEST_OLD have the same value, so use
- # another cue to decide what kind of message the peer sent us.
- if self.kexAlg == 'diffie-hellman-group1-sha1':
- return self._ssh_KEXDH_INIT(packet)
- elif self.kexAlg == 'diffie-hellman-group-exchange-sha1':
- self.dhGexRequest = packet
- ideal = struct.unpack('>L', packet)[0]
- self.g, self.p = self.factory.getDHPrime(ideal)
- self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
- else:
- raise error.ConchError('bad kexalg: %s' % self.kexAlg)
-
-
- def ssh_KEX_DH_GEX_REQUEST(self, packet):
- """
- Called when we receive a MSG_KEX_DH_GEX_REQUEST message. Payload::
- integer minimum
- integer ideal
- integer maximum
-
- The client is asking for a Diffie-Hellman group between minimum and
- maximum size, and close to ideal if possible. We reply with a
- MSG_KEX_DH_GEX_GROUP message.
-
- If we were told to ignore the next key exchange packet by ssh_KEXINIT,
- drop it on the floor and return.
- """
- if self.ignoreNextPacket:
- self.ignoreNextPacket = 0
- return
- self.dhGexRequest = packet
- min, ideal, max = struct.unpack('>3L', packet)
- self.g, self.p = self.factory.getDHPrime(ideal)
- self.sendPacket(MSG_KEX_DH_GEX_GROUP, MP(self.p) + MP(self.g))
-
-
- def ssh_KEX_DH_GEX_INIT(self, packet):
- """
- Called when we get a MSG_KEX_DH_GEX_INIT message. Payload::
- integer e (client DH public key)
-
- We send the MSG_KEX_DH_GEX_REPLY message with our host key and
- signature.
- """
- clientDHpublicKey, foo = getMP(packet)
- # TODO: we should also look at the value they send to us and reject
- # insecure values of f (if g==2 and f has a single '1' bit while the
- # rest are '0's, then they must have used a small y also).
-
- # TODO: This could be computed when self.p is set up
- # or do as openssh does and scan f for a single '1' bit instead
-
- pSize = Util.number.size(self.p)
- y = _getRandomNumber(randbytes.secureRandom, pSize)
-
- serverDHpublicKey = _MPpow(self.g, y, self.p)
- sharedSecret = _MPpow(clientDHpublicKey, y, self.p)
- h = sha1()
- h.update(NS(self.otherVersionString))
- h.update(NS(self.ourVersionString))
- h.update(NS(self.otherKexInitPayload))
- h.update(NS(self.ourKexInitPayload))
- h.update(NS(self.factory.publicKeys[self.keyAlg].blob()))
- h.update(self.dhGexRequest)
- h.update(MP(self.p))
- h.update(MP(self.g))
- h.update(MP(clientDHpublicKey))
- h.update(serverDHpublicKey)
- h.update(sharedSecret)
- exchangeHash = h.digest()
- self.sendPacket(
- MSG_KEX_DH_GEX_REPLY,
- NS(self.factory.publicKeys[self.keyAlg].blob()) +
- serverDHpublicKey +
- NS(self.factory.privateKeys[self.keyAlg].sign(exchangeHash)))
- self._keySetup(sharedSecret, exchangeHash)
-
-
- def ssh_NEWKEYS(self, packet):
- """
- Called when we get a MSG_NEWKEYS message. No payload.
- When we get this, the keys have been set on both sides, and we
- start using them to encrypt and authenticate the connection.
- """
- if packet != '':
- self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
- "NEWKEYS takes no data")
- return
- self._newKeys()
-
-
- def ssh_SERVICE_REQUEST(self, packet):
- """
- Called when we get a MSG_SERVICE_REQUEST message. Payload::
- string serviceName
-
- The client has requested a service. If we can start the service,
- start it; otherwise, disconnect with
- DISCONNECT_SERVICE_NOT_AVAILABLE.
- """
- service, rest = getNS(packet)
- cls = self.factory.getService(self, service)
- if not cls:
- self.sendDisconnect(DISCONNECT_SERVICE_NOT_AVAILABLE,
- "don't have service %s" % service)
- return
- else:
- self.sendPacket(MSG_SERVICE_ACCEPT, NS(service))
- self.setService(cls())
-
-
-
-class SSHClientTransport(SSHTransportBase):
- """
- SSHClientTransport implements the client side of the SSH protocol.
-
- @ivar isClient: since we are always the client, this is always True.
-
- @ivar _gotNewKeys: if we receive a MSG_NEWKEYS message before we are
- ready to transition to the new keys, this is set to True so we
- can transition when the keys are ready locally.
-
- @ivar x: our Diffie-Hellman private key.
-
- @ivar e: our Diffie-Hellman public key.
-
- @ivar g: the Diffie-Hellman group generator.
-
- @ivar p: the Diffie-Hellman group prime
-
- @ivar instance: the SSHService object we are requesting.
- """
- isClient = True
-
- def connectionMade(self):
- """
- Called when the connection is started with the server. Just sets
- up a private instance variable.
- """
- SSHTransportBase.connectionMade(self)
- self._gotNewKeys = 0
-
-
- def ssh_KEXINIT(self, packet):
- """
- Called when we receive a MSG_KEXINIT message. For a description
- of the packet, see SSHTransportBase.ssh_KEXINIT(). Additionally,
- this method sends the first key exchange packet. If the agreed-upon
- exchange is diffie-hellman-group1-sha1, generate a public key
- and send it in a MSG_KEXDH_INIT message. If the exchange is
- diffie-hellman-group-exchange-sha1, ask for a 2048 bit group with a
- MSG_KEX_DH_GEX_REQUEST_OLD message.
- """
- if SSHTransportBase.ssh_KEXINIT(self, packet) is None:
- return # we disconnected
- if self.kexAlg == 'diffie-hellman-group1-sha1':
- self.x = _generateX(randbytes.secureRandom, 512)
- self.e = _MPpow(DH_GENERATOR, self.x, DH_PRIME)
- self.sendPacket(MSG_KEXDH_INIT, self.e)
- elif self.kexAlg == 'diffie-hellman-group-exchange-sha1':
- self.sendPacket(MSG_KEX_DH_GEX_REQUEST_OLD, '\x00\x00\x08\x00')
- else:
- raise error.ConchError("somehow, the kexAlg has been set "
- "to something we don't support")
-
-
- def _ssh_KEXDH_REPLY(self, packet):
- """
- Called to handle a reply to a diffie-hellman-group1-sha1 key exchange
- message (KEXDH_INIT).
-
- Like the handler for I{KEXDH_INIT}, this message type has an
- overlapping value. This method is called from C{ssh_KEX_DH_GEX_GROUP}
- if that method detects a diffie-hellman-group1-sha1 key exchange is in
- progress.
-
- Payload::
-
- string serverHostKey
- integer f (server Diffie-Hellman public key)
- string signature
-
- We verify the host key by calling verifyHostKey, then continue in
- _continueKEXDH_REPLY.
- """
- pubKey, packet = getNS(packet)
- f, packet = getMP(packet)
- signature, packet = getNS(packet)
- fingerprint = ':'.join([ch.encode('hex') for ch in
- md5(pubKey).digest()])
- d = self.verifyHostKey(pubKey, fingerprint)
- d.addCallback(self._continueKEXDH_REPLY, pubKey, f, signature)
- d.addErrback(
- lambda unused: self.sendDisconnect(
- DISCONNECT_HOST_KEY_NOT_VERIFIABLE, 'bad host key'))
- return d
-
-
- def ssh_KEX_DH_GEX_GROUP(self, packet):
- """
- This handles two different message which share an integer value.
-
- If the key exchange is diffie-hellman-group-exchange-sha1, this is
- MSG_KEX_DH_GEX_GROUP. Payload::
- string g (group generator)
- string p (group prime)
-
- We generate a Diffie-Hellman public key and send it in a
- MSG_KEX_DH_GEX_INIT message.
- """
- if self.kexAlg == 'diffie-hellman-group1-sha1':
- return self._ssh_KEXDH_REPLY(packet)
- else:
- self.p, rest = getMP(packet)
- self.g, rest = getMP(rest)
- self.x = _generateX(randbytes.secureRandom, 320)
- self.e = _MPpow(self.g, self.x, self.p)
- self.sendPacket(MSG_KEX_DH_GEX_INIT, self.e)
-
-
- def _continueKEXDH_REPLY(self, ignored, pubKey, f, signature):
- """
- The host key has been verified, so we generate the keys.
-
- @param pubKey: the public key blob for the server's public key.
- @type pubKey: C{str}
- @param f: the server's Diffie-Hellman public key.
- @type f: C{long}
- @param signature: the server's signature, verifying that it has the
- correct private key.
- @type signature: C{str}
- """
- serverKey = keys.Key.fromString(pubKey)
- sharedSecret = _MPpow(f, self.x, DH_PRIME)
- h = sha1()
- h.update(NS(self.ourVersionString))
- h.update(NS(self.otherVersionString))
- h.update(NS(self.ourKexInitPayload))
- h.update(NS(self.otherKexInitPayload))
- h.update(NS(pubKey))
- h.update(self.e)
- h.update(MP(f))
- h.update(sharedSecret)
- exchangeHash = h.digest()
- if not serverKey.verify(signature, exchangeHash):
- self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
- 'bad signature')
- return
- self._keySetup(sharedSecret, exchangeHash)
-
-
- def ssh_KEX_DH_GEX_REPLY(self, packet):
- """
- Called when we receieve a MSG_KEX_DH_GEX_REPLY message. Payload::
- string server host key
- integer f (server DH public key)
-
- We verify the host key by calling verifyHostKey, then continue in
- _continueGEX_REPLY.
- """
- pubKey, packet = getNS(packet)
- f, packet = getMP(packet)
- signature, packet = getNS(packet)
- fingerprint = ':'.join(map(lambda c: '%02x'%ord(c),
- md5(pubKey).digest()))
- d = self.verifyHostKey(pubKey, fingerprint)
- d.addCallback(self._continueGEX_REPLY, pubKey, f, signature)
- d.addErrback(
- lambda unused: self.sendDisconnect(
- DISCONNECT_HOST_KEY_NOT_VERIFIABLE, 'bad host key'))
- return d
-
-
- def _continueGEX_REPLY(self, ignored, pubKey, f, signature):
- """
- The host key has been verified, so we generate the keys.
-
- @param pubKey: the public key blob for the server's public key.
- @type pubKey: C{str}
- @param f: the server's Diffie-Hellman public key.
- @type f: C{long}
- @param signature: the server's signature, verifying that it has the
- correct private key.
- @type signature: C{str}
- """
- serverKey = keys.Key.fromString(pubKey)
- sharedSecret = _MPpow(f, self.x, self.p)
- h = sha1()
- h.update(NS(self.ourVersionString))
- h.update(NS(self.otherVersionString))
- h.update(NS(self.ourKexInitPayload))
- h.update(NS(self.otherKexInitPayload))
- h.update(NS(pubKey))
- h.update('\x00\x00\x08\x00')
- h.update(MP(self.p))
- h.update(MP(self.g))
- h.update(self.e)
- h.update(MP(f))
- h.update(sharedSecret)
- exchangeHash = h.digest()
- if not serverKey.verify(signature, exchangeHash):
- self.sendDisconnect(DISCONNECT_KEY_EXCHANGE_FAILED,
- 'bad signature')
- return
- self._keySetup(sharedSecret, exchangeHash)
-
-
- def _keySetup(self, sharedSecret, exchangeHash):
- """
- See SSHTransportBase._keySetup().
- """
- SSHTransportBase._keySetup(self, sharedSecret, exchangeHash)
- if self._gotNewKeys:
- self.ssh_NEWKEYS('')
-
-
- def ssh_NEWKEYS(self, packet):
- """
- Called when we receieve a MSG_NEWKEYS message. No payload.
- If we've finished setting up our own keys, start using them.
- Otherwise, remeber that we've receieved this message.
- """
- if packet != '':
- self.sendDisconnect(DISCONNECT_PROTOCOL_ERROR,
- "NEWKEYS takes no data")
- return
- if not self.nextEncryptions.encBlockSize:
- self._gotNewKeys = 1
- return
- self._newKeys()
- self.connectionSecure()
-
-
- def ssh_SERVICE_ACCEPT(self, packet):
- """
- Called when we receieve a MSG_SERVICE_ACCEPT message. Payload::
- string service name
-
- Start the service we requested.
- """
- if packet == '':
- log.msg('got SERVICE_ACCEPT without payload')
- else:
- name = getNS(packet)[0]
- if name != self.instance.name:
- self.sendDisconnect(
- DISCONNECT_PROTOCOL_ERROR,
- "received accept for service we did not request")
- self.setService(self.instance)
-
-
- def requestService(self, instance):
- """
- Request that a service be run over this transport.
-
- @type instance: subclass of L{twisted.conch.ssh.service.SSHService}
- """
- self.sendPacket(MSG_SERVICE_REQUEST, NS(instance.name))
- self.instance = instance
-
-
- # client methods
- def verifyHostKey(self, hostKey, fingerprint):
- """
- Returns a Deferred that gets a callback if it is a valid key, or
- an errback if not.
-
- @type hostKey: C{str}
- @type fingerprint: C{str}
- @rtype: L{twisted.internet.defer.Deferred}
- """
- # return if it's good
- return defer.fail(NotImplementedError())
-
-
- def connectionSecure(self):
- """
- Called when the encryption has been set up. Generally,
- requestService() is called to run another service over the transport.
- """
- raise NotImplementedError()
-
-
-
-class _DummyCipher:
- """
- A cipher for the none encryption method.
-
- @ivar block_size: the block size of the encryption. In the case of the
- none cipher, this is 8 bytes.
- """
- block_size = 8
-
-
- def encrypt(self, x):
- return x
-
-
- decrypt = encrypt
-
-
-class SSHCiphers:
- """
- SSHCiphers represents all the encryption operations that need to occur
- to encrypt and authenticate the SSH connection.
-
- @cvar cipherMap: A dictionary mapping SSH encryption names to 3-tuples of
- (, , )
- @cvar macMap: A dictionary mapping SSH MAC names to hash modules.
-
- @ivar outCipType: the string type of the outgoing cipher.
- @ivar inCipType: the string type of the incoming cipher.
- @ivar outMACType: the string type of the incoming MAC.
- @ivar inMACType: the string type of the incoming MAC.
- @ivar encBlockSize: the block size of the outgoing cipher.
- @ivar decBlockSize: the block size of the incoming cipher.
- @ivar verifyDigestSize: the size of the incoming MAC.
- @ivar outMAC: a tuple of (, , ,
- ) representing the outgoing MAC.
- @ivar inMAc: see outMAC, but for the incoming MAC.
- """
-
- cipherMap = {
- '3des-cbc': ('DES3', 24, False),
- 'blowfish-cbc': ('Blowfish', 16, False),
- 'aes256-cbc': ('AES', 32, False),
- 'aes192-cbc': ('AES', 24, False),
- 'aes128-cbc': ('AES', 16, False),
- 'cast128-cbc': ('CAST', 16, False),
- 'aes128-ctr': ('AES', 16, True),
- 'aes192-ctr': ('AES', 24, True),
- 'aes256-ctr': ('AES', 32, True),
- '3des-ctr': ('DES3', 24, True),
- 'blowfish-ctr': ('Blowfish', 16, True),
- 'cast128-ctr': ('CAST', 16, True),
- 'none': (None, 0, False),
- }
- macMap = {
- 'hmac-sha1': sha1,
- 'hmac-md5': md5,
- 'none': None
- }
-
-
- def __init__(self, outCip, inCip, outMac, inMac):
- self.outCipType = outCip
- self.inCipType = inCip
- self.outMACType = outMac
- self.inMACType = inMac
- self.encBlockSize = 0
- self.decBlockSize = 0
- self.verifyDigestSize = 0
- self.outMAC = (None, '', '', 0)
- self.inMAC = (None, '', '', 0)
-
-
- def setKeys(self, outIV, outKey, inIV, inKey, outInteg, inInteg):
- """
- Set up the ciphers and hashes using the given keys,
-
- @param outIV: the outgoing initialization vector
- @param outKey: the outgoing encryption key
- @param inIV: the incoming initialization vector
- @param inKey: the incoming encryption key
- @param outInteg: the outgoing integrity key
- @param inInteg: the incoming integrity key.
- """
- o = self._getCipher(self.outCipType, outIV, outKey)
- self.encrypt = o.encrypt
- self.encBlockSize = o.block_size
- o = self._getCipher(self.inCipType, inIV, inKey)
- self.decrypt = o.decrypt
- self.decBlockSize = o.block_size
- self.outMAC = self._getMAC(self.outMACType, outInteg)
- self.inMAC = self._getMAC(self.inMACType, inInteg)
- if self.inMAC:
- self.verifyDigestSize = self.inMAC[3]
-
-
- def _getCipher(self, cip, iv, key):
- """
- Creates an initialized cipher object.
-
- @param cip: the name of the cipher: maps into Crypto.Cipher.*
- @param iv: the initialzation vector
- @param key: the encryption key
- """
- modName, keySize, counterMode = self.cipherMap[cip]
- if not modName: # no cipher
- return _DummyCipher()
- mod = __import__('Crypto.Cipher.%s'%modName, {}, {}, 'x')
- if counterMode:
- return mod.new(key[:keySize], mod.MODE_CTR, iv[:mod.block_size],
- counter=_Counter(iv, mod.block_size))
- else:
- return mod.new(key[:keySize], mod.MODE_CBC, iv[:mod.block_size])
-
-
- def _getMAC(self, mac, key):
- """
- Gets a 4-tuple representing the message authentication code.
- (, , ,
- )
-
- @param mac: a key mapping into macMap
- @type mac: C{str}
- @param key: the MAC key.
- @type key: C{str}
- """
- mod = self.macMap[mac]
- if not mod:
- return (None, '', '', 0)
- ds = mod().digest_size
-
- # Truncation here appears to contravene RFC 2104, section 2. However,
- # implementing the hashing behavior prescribed by the RFC breaks
- # interoperability with OpenSSH (at least version 5.5p1).
- key = key[:ds] + ('\x00' * (64 - ds))
- i = string.translate(key, hmac.trans_36)
- o = string.translate(key, hmac.trans_5C)
- result = _MACParams((mod, i, o, ds))
- result.key = key
- return result
-
-
- def encrypt(self, blocks):
- """
- Encrypt blocks. Overridden by the encrypt method of a
- Crypto.Cipher.* object in setKeys().
-
- @type blocks: C{str}
- """
- raise NotImplementedError()
-
-
- def decrypt(self, blocks):
- """
- Decrypt blocks. See encrypt().
-
- @type blocks: C{str}
- """
- raise NotImplementedError()
-
-
- def makeMAC(self, seqid, data):
- """
- Create a message authentication code (MAC) for the given packet using
- the outgoing MAC values.
-
- @param seqid: the sequence ID of the outgoing packet
- @type seqid: C{int}
- @param data: the data to create a MAC for
- @type data: C{str}
- @rtype: C{str}
- """
- if not self.outMAC[0]:
- return ''
- data = struct.pack('>L', seqid) + data
- return hmac.HMAC(self.outMAC.key, data, self.outMAC[0]).digest()
-
-
- def verify(self, seqid, data, mac):
- """
- Verify an incoming MAC using the incoming MAC values. Return True
- if the MAC is valid.
-
- @param seqid: the sequence ID of the incoming packet
- @type seqid: C{int}
- @param data: the packet data to verify
- @type data: C{str}
- @param mac: the MAC sent with the packet
- @type mac: C{str}
- @rtype: C{bool}
- """
- if not self.inMAC[0]:
- return mac == ''
- data = struct.pack('>L', seqid) + data
- outer = hmac.HMAC(self.inMAC.key, data, self.inMAC[0]).digest()
- return mac == outer
-
-
-class _Counter:
- """
- Stateful counter which returns results packed in a byte string
- """
-
-
- def __init__(self, initialVector, blockSize):
- """
- @type initialVector: C{str}
- @param initialVector: A byte string representing the initial counter
- value.
- @type blockSize: C{int}
- @param blockSize: The length of the output buffer, as well as the
- number of bytes at the beginning of C{initialVector} to consider.
- """
- initialVector = initialVector[:blockSize]
- self.count = getMP('\xff\xff\xff\xff' + initialVector)[0]
- self.blockSize = blockSize
- self.count = Util.number.long_to_bytes(self.count - 1)
- self.count = '\x00' * (self.blockSize - len(self.count)) + self.count
- self.count = array.array('c', self.count)
- self.len = len(self.count) - 1
-
-
- def __call__(self):
- """
- Increment the counter and return the new value.
- """
- i = self.len
- while i > -1:
- self.count[i] = n = chr((ord(self.count[i]) + 1) % 256)
- if n == '\x00':
- i -= 1
- else:
- return self.count.tostring()
-
- self.count = array.array('c', '\x00' * self.blockSize)
- return self.count.tostring()
-
-
-
-# Diffie-Hellman primes from Oakley Group 2 [RFC 2409]
-DH_PRIME = long('17976931348623159077083915679378745319786029604875601170644'
-'442368419718021615851936894783379586492554150218056548598050364644054819923'
-'910005079287700335581663922955313623907650873575991482257486257500742530207'
-'744771258955095793777842444242661733472762929938766870920560605027081084290'
-'7692932019128194467627007L')
-DH_GENERATOR = 2L
-
-
-
-MSG_DISCONNECT = 1
-MSG_IGNORE = 2
-MSG_UNIMPLEMENTED = 3
-MSG_DEBUG = 4
-MSG_SERVICE_REQUEST = 5
-MSG_SERVICE_ACCEPT = 6
-MSG_KEXINIT = 20
-MSG_NEWKEYS = 21
-MSG_KEXDH_INIT = 30
-MSG_KEXDH_REPLY = 31
-MSG_KEX_DH_GEX_REQUEST_OLD = 30
-MSG_KEX_DH_GEX_REQUEST = 34
-MSG_KEX_DH_GEX_GROUP = 31
-MSG_KEX_DH_GEX_INIT = 32
-MSG_KEX_DH_GEX_REPLY = 33
-
-
-
-DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT = 1
-DISCONNECT_PROTOCOL_ERROR = 2
-DISCONNECT_KEY_EXCHANGE_FAILED = 3
-DISCONNECT_RESERVED = 4
-DISCONNECT_MAC_ERROR = 5
-DISCONNECT_COMPRESSION_ERROR = 6
-DISCONNECT_SERVICE_NOT_AVAILABLE = 7
-DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED = 8
-DISCONNECT_HOST_KEY_NOT_VERIFIABLE = 9
-DISCONNECT_CONNECTION_LOST = 10
-DISCONNECT_BY_APPLICATION = 11
-DISCONNECT_TOO_MANY_CONNECTIONS = 12
-DISCONNECT_AUTH_CANCELLED_BY_USER = 13
-DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE = 14
-DISCONNECT_ILLEGAL_USER_NAME = 15
-
-
-
-messages = {}
-for name, value in globals().items():
- # Avoid legacy messages which overlap with never ones
- if name.startswith('MSG_') and not name.startswith('MSG_KEXDH_'):
- messages[value] = name
-# Check for regressions (#5352)
-if 'MSG_KEXDH_INIT' in messages or 'MSG_KEXDH_REPLY' in messages:
- raise RuntimeError(
- "legacy SSH mnemonics should not end up in messages dict")
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/userauth.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/userauth.py
deleted file mode 100644
index abed4f8..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ssh/userauth.py
+++ /dev/null
@@ -1,838 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_userauth -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Implementation of the ssh-userauth service.
-Currently implemented authentication types are public-key and password.
-
-Maintainer: Paul Swartz
-"""
-
-import struct
-from twisted.conch import error, interfaces
-from twisted.conch.ssh import keys, transport, service
-from twisted.conch.ssh.common import NS, getNS
-from twisted.cred import credentials
-from twisted.cred.error import UnauthorizedLogin
-from twisted.internet import defer, reactor
-from twisted.python import failure, log
-
-
-
-class SSHUserAuthServer(service.SSHService):
- """
- A service implementing the server side of the 'ssh-userauth' service. It
- is used to authenticate the user on the other side as being able to access
- this server.
-
- @ivar name: the name of this service: 'ssh-userauth'
- @type name: C{str}
- @ivar authenticatedWith: a list of authentication methods that have
- already been used.
- @type authenticatedWith: C{list}
- @ivar loginTimeout: the number of seconds we wait before disconnecting
- the user for taking too long to authenticate
- @type loginTimeout: C{int}
- @ivar attemptsBeforeDisconnect: the number of failed login attempts we
- allow before disconnecting.
- @type attemptsBeforeDisconnect: C{int}
- @ivar loginAttempts: the number of login attempts that have been made
- @type loginAttempts: C{int}
- @ivar passwordDelay: the number of seconds to delay when the user gives
- an incorrect password
- @type passwordDelay: C{int}
- @ivar interfaceToMethod: a C{dict} mapping credential interfaces to
- authentication methods. The server checks to see which of the
- cred interfaces have checkers and tells the client that those methods
- are valid for authentication.
- @type interfaceToMethod: C{dict}
- @ivar supportedAuthentications: A list of the supported authentication
- methods.
- @type supportedAuthentications: C{list} of C{str}
- @ivar user: the last username the client tried to authenticate with
- @type user: C{str}
- @ivar method: the current authentication method
- @type method: C{str}
- @ivar nextService: the service the user wants started after authentication
- has been completed.
- @type nextService: C{str}
- @ivar portal: the L{twisted.cred.portal.Portal} we are using for
- authentication
- @type portal: L{twisted.cred.portal.Portal}
- @ivar clock: an object with a callLater method. Stubbed out for testing.
- """
-
-
- name = 'ssh-userauth'
- loginTimeout = 10 * 60 * 60
- # 10 minutes before we disconnect them
- attemptsBeforeDisconnect = 20
- # 20 login attempts before a disconnect
- passwordDelay = 1 # number of seconds to delay on a failed password
- clock = reactor
- interfaceToMethod = {
- credentials.ISSHPrivateKey : 'publickey',
- credentials.IUsernamePassword : 'password',
- credentials.IPluggableAuthenticationModules : 'keyboard-interactive',
- }
-
-
- def serviceStarted(self):
- """
- Called when the userauth service is started. Set up instance
- variables, check if we should allow password/keyboard-interactive
- authentication (only allow if the outgoing connection is encrypted) and
- set up a login timeout.
- """
- self.authenticatedWith = []
- self.loginAttempts = 0
- self.user = None
- self.nextService = None
- self._pamDeferred = None
- self.portal = self.transport.factory.portal
-
- self.supportedAuthentications = []
- for i in self.portal.listCredentialsInterfaces():
- if i in self.interfaceToMethod:
- self.supportedAuthentications.append(self.interfaceToMethod[i])
-
- if not self.transport.isEncrypted('in'):
- # don't let us transport password in plaintext
- if 'password' in self.supportedAuthentications:
- self.supportedAuthentications.remove('password')
- if 'keyboard-interactive' in self.supportedAuthentications:
- self.supportedAuthentications.remove('keyboard-interactive')
- self._cancelLoginTimeout = self.clock.callLater(
- self.loginTimeout,
- self.timeoutAuthentication)
-
-
- def serviceStopped(self):
- """
- Called when the userauth service is stopped. Cancel the login timeout
- if it's still going.
- """
- if self._cancelLoginTimeout:
- self._cancelLoginTimeout.cancel()
- self._cancelLoginTimeout = None
-
-
- def timeoutAuthentication(self):
- """
- Called when the user has timed out on authentication. Disconnect
- with a DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE message.
- """
- self._cancelLoginTimeout = None
- self.transport.sendDisconnect(
- transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
- 'you took too long')
-
-
- def tryAuth(self, kind, user, data):
- """
- Try to authenticate the user with the given method. Dispatches to a
- auth_* method.
-
- @param kind: the authentication method to try.
- @type kind: C{str}
- @param user: the username the client is authenticating with.
- @type user: C{str}
- @param data: authentication specific data sent by the client.
- @type data: C{str}
- @return: A Deferred called back if the method succeeded, or erred back
- if it failed.
- @rtype: C{defer.Deferred}
- """
- log.msg('%s trying auth %s' % (user, kind))
- if kind not in self.supportedAuthentications:
- return defer.fail(
- error.ConchError('unsupported authentication, failing'))
- kind = kind.replace('-', '_')
- f = getattr(self,'auth_%s'%kind, None)
- if f:
- ret = f(data)
- if not ret:
- return defer.fail(
- error.ConchError('%s return None instead of a Deferred'
- % kind))
- else:
- return ret
- return defer.fail(error.ConchError('bad auth type: %s' % kind))
-
-
- def ssh_USERAUTH_REQUEST(self, packet):
- """
- The client has requested authentication. Payload::
- string user
- string next service
- string method
-
-
- @type packet: C{str}
- """
- user, nextService, method, rest = getNS(packet, 3)
- if user != self.user or nextService != self.nextService:
- self.authenticatedWith = [] # clear auth state
- self.user = user
- self.nextService = nextService
- self.method = method
- d = self.tryAuth(method, user, rest)
- if not d:
- self._ebBadAuth(
- failure.Failure(error.ConchError('auth returned none')))
- return
- d.addCallback(self._cbFinishedAuth)
- d.addErrback(self._ebMaybeBadAuth)
- d.addErrback(self._ebBadAuth)
- return d
-
-
- def _cbFinishedAuth(self, (interface, avatar, logout)):
- """
- The callback when user has successfully been authenticated. For a
- description of the arguments, see L{twisted.cred.portal.Portal.login}.
- We start the service requested by the user.
- """
- self.transport.avatar = avatar
- self.transport.logoutFunction = logout
- service = self.transport.factory.getService(self.transport,
- self.nextService)
- if not service:
- raise error.ConchError('could not get next service: %s'
- % self.nextService)
- log.msg('%s authenticated with %s' % (self.user, self.method))
- self.transport.sendPacket(MSG_USERAUTH_SUCCESS, '')
- self.transport.setService(service())
-
-
- def _ebMaybeBadAuth(self, reason):
- """
- An intermediate errback. If the reason is
- error.NotEnoughAuthentication, we send a MSG_USERAUTH_FAILURE, but
- with the partial success indicator set.
-
- @type reason: L{twisted.python.failure.Failure}
- """
- reason.trap(error.NotEnoughAuthentication)
- self.transport.sendPacket(MSG_USERAUTH_FAILURE,
- NS(','.join(self.supportedAuthentications)) + '\xff')
-
-
- def _ebBadAuth(self, reason):
- """
- The final errback in the authentication chain. If the reason is
- error.IgnoreAuthentication, we simply return; the authentication
- method has sent its own response. Otherwise, send a failure message
- and (if the method is not 'none') increment the number of login
- attempts.
-
- @type reason: L{twisted.python.failure.Failure}
- """
- if reason.check(error.IgnoreAuthentication):
- return
- if self.method != 'none':
- log.msg('%s failed auth %s' % (self.user, self.method))
- if reason.check(UnauthorizedLogin):
- log.msg('unauthorized login: %s' % reason.getErrorMessage())
- elif reason.check(error.ConchError):
- log.msg('reason: %s' % reason.getErrorMessage())
- else:
- log.msg(reason.getTraceback())
- self.loginAttempts += 1
- if self.loginAttempts > self.attemptsBeforeDisconnect:
- self.transport.sendDisconnect(
- transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
- 'too many bad auths')
- return
- self.transport.sendPacket(
- MSG_USERAUTH_FAILURE,
- NS(','.join(self.supportedAuthentications)) + '\x00')
-
-
- def auth_publickey(self, packet):
- """
- Public key authentication. Payload::
- byte has signature
- string algorithm name
- string key blob
- [string signature] (if has signature is True)
-
- Create a SSHPublicKey credential and verify it using our portal.
- """
- hasSig = ord(packet[0])
- algName, blob, rest = getNS(packet[1:], 2)
- pubKey = keys.Key.fromString(blob)
- signature = hasSig and getNS(rest)[0] or None
- if hasSig:
- b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
- NS(self.user) + NS(self.nextService) + NS('publickey') +
- chr(hasSig) + NS(pubKey.sshType()) + NS(blob))
- c = credentials.SSHPrivateKey(self.user, algName, blob, b,
- signature)
- return self.portal.login(c, None, interfaces.IConchUser)
- else:
- c = credentials.SSHPrivateKey(self.user, algName, blob, None, None)
- return self.portal.login(c, None,
- interfaces.IConchUser).addErrback(self._ebCheckKey,
- packet[1:])
-
-
- def _ebCheckKey(self, reason, packet):
- """
- Called back if the user did not sent a signature. If reason is
- error.ValidPublicKey then this key is valid for the user to
- authenticate with. Send MSG_USERAUTH_PK_OK.
- """
- reason.trap(error.ValidPublicKey)
- # if we make it here, it means that the publickey is valid
- self.transport.sendPacket(MSG_USERAUTH_PK_OK, packet)
- return failure.Failure(error.IgnoreAuthentication())
-
-
- def auth_password(self, packet):
- """
- Password authentication. Payload::
- string password
-
- Make a UsernamePassword credential and verify it with our portal.
- """
- password = getNS(packet[1:])[0]
- c = credentials.UsernamePassword(self.user, password)
- return self.portal.login(c, None, interfaces.IConchUser).addErrback(
- self._ebPassword)
-
-
- def _ebPassword(self, f):
- """
- If the password is invalid, wait before sending the failure in order
- to delay brute-force password guessing.
- """
- d = defer.Deferred()
- self.clock.callLater(self.passwordDelay, d.callback, f)
- return d
-
-
- def auth_keyboard_interactive(self, packet):
- """
- Keyboard interactive authentication. No payload. We create a
- PluggableAuthenticationModules credential and authenticate with our
- portal.
- """
- if self._pamDeferred is not None:
- self.transport.sendDisconnect(
- transport.DISCONNECT_PROTOCOL_ERROR,
- "only one keyboard interactive attempt at a time")
- return defer.fail(error.IgnoreAuthentication())
- c = credentials.PluggableAuthenticationModules(self.user,
- self._pamConv)
- return self.portal.login(c, None, interfaces.IConchUser)
-
-
- def _pamConv(self, items):
- """
- Convert a list of PAM authentication questions into a
- MSG_USERAUTH_INFO_REQUEST. Returns a Deferred that will be called
- back when the user has responses to the questions.
-
- @param items: a list of 2-tuples (message, kind). We only care about
- kinds 1 (password) and 2 (text).
- @type items: C{list}
- @rtype: L{defer.Deferred}
- """
- resp = []
- for message, kind in items:
- if kind == 1: # password
- resp.append((message, 0))
- elif kind == 2: # text
- resp.append((message, 1))
- elif kind in (3, 4):
- return defer.fail(error.ConchError(
- 'cannot handle PAM 3 or 4 messages'))
- else:
- return defer.fail(error.ConchError(
- 'bad PAM auth kind %i' % kind))
- packet = NS('') + NS('') + NS('')
- packet += struct.pack('>L', len(resp))
- for prompt, echo in resp:
- packet += NS(prompt)
- packet += chr(echo)
- self.transport.sendPacket(MSG_USERAUTH_INFO_REQUEST, packet)
- self._pamDeferred = defer.Deferred()
- return self._pamDeferred
-
-
- def ssh_USERAUTH_INFO_RESPONSE(self, packet):
- """
- The user has responded with answers to PAMs authentication questions.
- Parse the packet into a PAM response and callback self._pamDeferred.
- Payload::
- uint32 numer of responses
- string response 1
- ...
- string response n
- """
- d, self._pamDeferred = self._pamDeferred, None
-
- try:
- resp = []
- numResps = struct.unpack('>L', packet[:4])[0]
- packet = packet[4:]
- while len(resp) < numResps:
- response, packet = getNS(packet)
- resp.append((response, 0))
- if packet:
- raise error.ConchError("%i bytes of extra data" % len(packet))
- except:
- d.errback(failure.Failure())
- else:
- d.callback(resp)
-
-
-
-class SSHUserAuthClient(service.SSHService):
- """
- A service implementing the client side of 'ssh-userauth'.
-
- This service will try all authentication methods provided by the server,
- making callbacks for more information when necessary.
-
- @ivar name: the name of this service: 'ssh-userauth'
- @type name: C{str}
- @ivar preferredOrder: a list of authentication methods that should be used
- first, in order of preference, if supported by the server
- @type preferredOrder: C{list}
- @ivar user: the name of the user to authenticate as
- @type user: C{str}
- @ivar instance: the service to start after authentication has finished
- @type instance: L{service.SSHService}
- @ivar authenticatedWith: a list of strings of authentication methods we've tried
- @type authenticatedWith: C{list} of C{str}
- @ivar triedPublicKeys: a list of public key objects that we've tried to
- authenticate with
- @type triedPublicKeys: C{list} of L{Key}
- @ivar lastPublicKey: the last public key object we've tried to authenticate
- with
- @type lastPublicKey: L{Key}
- """
-
-
- name = 'ssh-userauth'
- preferredOrder = ['publickey', 'password', 'keyboard-interactive']
-
-
- def __init__(self, user, instance):
- self.user = user
- self.instance = instance
-
-
- def serviceStarted(self):
- self.authenticatedWith = []
- self.triedPublicKeys = []
- self.lastPublicKey = None
- self.askForAuth('none', '')
-
-
- def askForAuth(self, kind, extraData):
- """
- Send a MSG_USERAUTH_REQUEST.
-
- @param kind: the authentication method to try.
- @type kind: C{str}
- @param extraData: method-specific data to go in the packet
- @type extraData: C{str}
- """
- self.lastAuth = kind
- self.transport.sendPacket(MSG_USERAUTH_REQUEST, NS(self.user) +
- NS(self.instance.name) + NS(kind) + extraData)
-
-
- def tryAuth(self, kind):
- """
- Dispatch to an authentication method.
-
- @param kind: the authentication method
- @type kind: C{str}
- """
- kind = kind.replace('-', '_')
- log.msg('trying to auth with %s' % (kind,))
- f = getattr(self,'auth_%s' % (kind,), None)
- if f:
- return f()
-
-
- def _ebAuth(self, ignored, *args):
- """
- Generic callback for a failed authentication attempt. Respond by
- asking for the list of accepted methods (the 'none' method)
- """
- self.askForAuth('none', '')
-
-
- def ssh_USERAUTH_SUCCESS(self, packet):
- """
- We received a MSG_USERAUTH_SUCCESS. The server has accepted our
- authentication, so start the next service.
- """
- self.transport.setService(self.instance)
-
-
- def ssh_USERAUTH_FAILURE(self, packet):
- """
- We received a MSG_USERAUTH_FAILURE. Payload::
- string methods
- byte partial success
-
- If partial success is C{True}, then the previous method succeeded but is
- not sufficent for authentication. C{methods} is a comma-separated list
- of accepted authentication methods.
-
- We sort the list of methods by their position in C{self.preferredOrder},
- removing methods that have already succeeded. We then call
- C{self.tryAuth} with the most preferred method.
-
- @param packet: the L{MSG_USERAUTH_FAILURE} payload.
- @type packet: C{str}
-
- @return: a L{defer.Deferred} that will be callbacked with C{None} as
- soon as all authentication methods have been tried, or C{None} if no
- more authentication methods are available.
- @rtype: C{defer.Deferred} or C{None}
- """
- canContinue, partial = getNS(packet)
- partial = ord(partial)
- if partial:
- self.authenticatedWith.append(self.lastAuth)
-
- def orderByPreference(meth):
- """
- Invoked once per authentication method in order to extract a
- comparison key which is then used for sorting.
-
- @param meth: the authentication method.
- @type meth: C{str}
-
- @return: the comparison key for C{meth}.
- @rtype: C{int}
- """
- if meth in self.preferredOrder:
- return self.preferredOrder.index(meth)
- else:
- # put the element at the end of the list.
- return len(self.preferredOrder)
-
- canContinue = sorted([meth for meth in canContinue.split(',')
- if meth not in self.authenticatedWith],
- key=orderByPreference)
-
- log.msg('can continue with: %s' % canContinue)
- return self._cbUserauthFailure(None, iter(canContinue))
-
-
- def _cbUserauthFailure(self, result, iterator):
- if result:
- return
- try:
- method = iterator.next()
- except StopIteration:
- self.transport.sendDisconnect(
- transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
- 'no more authentication methods available')
- else:
- d = defer.maybeDeferred(self.tryAuth, method)
- d.addCallback(self._cbUserauthFailure, iterator)
- return d
-
-
- def ssh_USERAUTH_PK_OK(self, packet):
- """
- This message (number 60) can mean several different messages depending
- on the current authentication type. We dispatch to individual methods
- in order to handle this request.
- """
- func = getattr(self, 'ssh_USERAUTH_PK_OK_%s' %
- self.lastAuth.replace('-', '_'), None)
- if func is not None:
- return func(packet)
- else:
- self.askForAuth('none', '')
-
-
- def ssh_USERAUTH_PK_OK_publickey(self, packet):
- """
- This is MSG_USERAUTH_PK. Our public key is valid, so we create a
- signature and try to authenticate with it.
- """
- publicKey = self.lastPublicKey
- b = (NS(self.transport.sessionID) + chr(MSG_USERAUTH_REQUEST) +
- NS(self.user) + NS(self.instance.name) + NS('publickey') +
- '\x01' + NS(publicKey.sshType()) + NS(publicKey.blob()))
- d = self.signData(publicKey, b)
- if not d:
- self.askForAuth('none', '')
- # this will fail, we'll move on
- return
- d.addCallback(self._cbSignedData)
- d.addErrback(self._ebAuth)
-
-
- def ssh_USERAUTH_PK_OK_password(self, packet):
- """
- This is MSG_USERAUTH_PASSWD_CHANGEREQ. The password given has expired.
- We ask for an old password and a new password, then send both back to
- the server.
- """
- prompt, language, rest = getNS(packet, 2)
- self._oldPass = self._newPass = None
- d = self.getPassword('Old Password: ')
- d = d.addCallbacks(self._setOldPass, self._ebAuth)
- d.addCallback(lambda ignored: self.getPassword(prompt))
- d.addCallbacks(self._setNewPass, self._ebAuth)
-
-
- def ssh_USERAUTH_PK_OK_keyboard_interactive(self, packet):
- """
- This is MSG_USERAUTH_INFO_RESPONSE. The server has sent us the
- questions it wants us to answer, so we ask the user and sent the
- responses.
- """
- name, instruction, lang, data = getNS(packet, 3)
- numPrompts = struct.unpack('!L', data[:4])[0]
- data = data[4:]
- prompts = []
- for i in range(numPrompts):
- prompt, data = getNS(data)
- echo = bool(ord(data[0]))
- data = data[1:]
- prompts.append((prompt, echo))
- d = self.getGenericAnswers(name, instruction, prompts)
- d.addCallback(self._cbGenericAnswers)
- d.addErrback(self._ebAuth)
-
-
- def _cbSignedData(self, signedData):
- """
- Called back out of self.signData with the signed data. Send the
- authentication request with the signature.
-
- @param signedData: the data signed by the user's private key.
- @type signedData: C{str}
- """
- publicKey = self.lastPublicKey
- self.askForAuth('publickey', '\x01' + NS(publicKey.sshType()) +
- NS(publicKey.blob()) + NS(signedData))
-
-
- def _setOldPass(self, op):
- """
- Called back when we are choosing a new password. Simply store the old
- password for now.
-
- @param op: the old password as entered by the user
- @type op: C{str}
- """
- self._oldPass = op
-
-
- def _setNewPass(self, np):
- """
- Called back when we are choosing a new password. Get the old password
- and send the authentication message with both.
-
- @param np: the new password as entered by the user
- @type np: C{str}
- """
- op = self._oldPass
- self._oldPass = None
- self.askForAuth('password', '\xff' + NS(op) + NS(np))
-
-
- def _cbGenericAnswers(self, responses):
- """
- Called back when we are finished answering keyboard-interactive
- questions. Send the info back to the server in a
- MSG_USERAUTH_INFO_RESPONSE.
-
- @param responses: a list of C{str} responses
- @type responses: C{list}
- """
- data = struct.pack('!L', len(responses))
- for r in responses:
- data += NS(r.encode('UTF8'))
- self.transport.sendPacket(MSG_USERAUTH_INFO_RESPONSE, data)
-
-
- def auth_publickey(self):
- """
- Try to authenticate with a public key. Ask the user for a public key;
- if the user has one, send the request to the server and return True.
- Otherwise, return False.
-
- @rtype: C{bool}
- """
- d = defer.maybeDeferred(self.getPublicKey)
- d.addBoth(self._cbGetPublicKey)
- return d
-
-
- def _cbGetPublicKey(self, publicKey):
- if not isinstance(publicKey, keys.Key): # failure or None
- publicKey = None
- if publicKey is not None:
- self.lastPublicKey = publicKey
- self.triedPublicKeys.append(publicKey)
- log.msg('using key of type %s' % publicKey.type())
- self.askForAuth('publickey', '\x00' + NS(publicKey.sshType()) +
- NS(publicKey.blob()))
- return True
- else:
- return False
-
-
- def auth_password(self):
- """
- Try to authenticate with a password. Ask the user for a password.
- If the user will return a password, return True. Otherwise, return
- False.
-
- @rtype: C{bool}
- """
- d = self.getPassword()
- if d:
- d.addCallbacks(self._cbPassword, self._ebAuth)
- return True
- else: # returned None, don't do password auth
- return False
-
-
- def auth_keyboard_interactive(self):
- """
- Try to authenticate with keyboard-interactive authentication. Send
- the request to the server and return True.
-
- @rtype: C{bool}
- """
- log.msg('authing with keyboard-interactive')
- self.askForAuth('keyboard-interactive', NS('') + NS(''))
- return True
-
-
- def _cbPassword(self, password):
- """
- Called back when the user gives a password. Send the request to the
- server.
-
- @param password: the password the user entered
- @type password: C{str}
- """
- self.askForAuth('password', '\x00' + NS(password))
-
-
- def signData(self, publicKey, signData):
- """
- Sign the given data with the given public key.
-
- By default, this will call getPrivateKey to get the private key,
- then sign the data using Key.sign().
-
- This method is factored out so that it can be overridden to use
- alternate methods, such as a key agent.
-
- @param publicKey: The public key object returned from L{getPublicKey}
- @type publicKey: L{keys.Key}
-
- @param signData: the data to be signed by the private key.
- @type signData: C{str}
- @return: a Deferred that's called back with the signature
- @rtype: L{defer.Deferred}
- """
- key = self.getPrivateKey()
- if not key:
- return
- return key.addCallback(self._cbSignData, signData)
-
-
- def _cbSignData(self, privateKey, signData):
- """
- Called back when the private key is returned. Sign the data and
- return the signature.
-
- @param privateKey: the private key object
- @type publicKey: L{keys.Key}
- @param signData: the data to be signed by the private key.
- @type signData: C{str}
- @return: the signature
- @rtype: C{str}
- """
- return privateKey.sign(signData)
-
-
- def getPublicKey(self):
- """
- Return a public key for the user. If no more public keys are
- available, return C{None}.
-
- This implementation always returns C{None}. Override it in a
- subclass to actually find and return a public key object.
-
- @rtype: L{Key} or L{NoneType}
- """
- return None
-
-
- def getPrivateKey(self):
- """
- Return a L{Deferred} that will be called back with the private key
- object corresponding to the last public key from getPublicKey().
- If the private key is not available, errback on the Deferred.
-
- @rtype: L{Deferred} called back with L{Key}
- """
- return defer.fail(NotImplementedError())
-
-
- def getPassword(self, prompt = None):
- """
- Return a L{Deferred} that will be called back with a password.
- prompt is a string to display for the password, or None for a generic
- 'user@hostname's password: '.
-
- @type prompt: C{str}/C{None}
- @rtype: L{defer.Deferred}
- """
- return defer.fail(NotImplementedError())
-
-
- def getGenericAnswers(self, name, instruction, prompts):
- """
- Returns a L{Deferred} with the responses to the promopts.
-
- @param name: The name of the authentication currently in progress.
- @param instruction: Describes what the authentication wants.
- @param prompts: A list of (prompt, echo) pairs, where prompt is a
- string to display and echo is a boolean indicating whether the
- user's response should be echoed as they type it.
- """
- return defer.fail(NotImplementedError())
-
-
-MSG_USERAUTH_REQUEST = 50
-MSG_USERAUTH_FAILURE = 51
-MSG_USERAUTH_SUCCESS = 52
-MSG_USERAUTH_BANNER = 53
-MSG_USERAUTH_INFO_RESPONSE = 61
-MSG_USERAUTH_PK_OK = 60
-
-messages = {}
-for k, v in locals().items():
- if k[:4]=='MSG_':
- messages[v] = k
-
-SSHUserAuthServer.protocolMessages = messages
-SSHUserAuthClient.protocolMessages = messages
-del messages
-del v
-
-# Doubles, not included in the protocols' mappings
-MSG_USERAUTH_PASSWD_CHANGEREQ = 60
-MSG_USERAUTH_INFO_REQUEST = 60
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/stdio.py b/Darwin/lib/python2.7/site-packages/twisted/conch/stdio.py
deleted file mode 100644
index c45fc3b..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/stdio.py
+++ /dev/null
@@ -1,95 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_manhole -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Asynchronous local terminal input handling
-
-@author: Jp Calderone
-"""
-
-import os, tty, sys, termios
-
-from twisted.internet import reactor, stdio, protocol, defer
-from twisted.python import failure, reflect, log
-
-from twisted.conch.insults.insults import ServerProtocol
-from twisted.conch.manhole import ColoredManhole
-
-class UnexpectedOutputError(Exception):
- pass
-
-class TerminalProcessProtocol(protocol.ProcessProtocol):
- def __init__(self, proto):
- self.proto = proto
- self.onConnection = defer.Deferred()
-
- def connectionMade(self):
- self.proto.makeConnection(self)
- self.onConnection.callback(None)
- self.onConnection = None
-
- def write(self, bytes):
- self.transport.write(bytes)
-
- def outReceived(self, bytes):
- self.proto.dataReceived(bytes)
-
- def errReceived(self, bytes):
- self.transport.loseConnection()
- if self.proto is not None:
- self.proto.connectionLost(failure.Failure(UnexpectedOutputError(bytes)))
- self.proto = None
-
- def childConnectionLost(self, childFD):
- if self.proto is not None:
- self.proto.childConnectionLost(childFD)
-
- def processEnded(self, reason):
- if self.proto is not None:
- self.proto.connectionLost(reason)
- self.proto = None
-
-
-
-class ConsoleManhole(ColoredManhole):
- """
- A manhole protocol specifically for use with L{stdio.StandardIO}.
- """
- def connectionLost(self, reason):
- """
- When the connection is lost, there is nothing more to do. Stop the
- reactor so that the process can exit.
- """
- reactor.stop()
-
-
-
-def runWithProtocol(klass):
- fd = sys.__stdin__.fileno()
- oldSettings = termios.tcgetattr(fd)
- tty.setraw(fd)
- try:
- p = ServerProtocol(klass)
- stdio.StandardIO(p)
- reactor.run()
- finally:
- termios.tcsetattr(fd, termios.TCSANOW, oldSettings)
- os.write(fd, "\r\x1bc\r")
-
-
-
-def main(argv=None):
- log.startLogging(file('child.log', 'w'))
-
- if argv is None:
- argv = sys.argv[1:]
- if argv:
- klass = reflect.namedClass(argv[0])
- else:
- klass = ConsoleManhole
- runWithProtocol(klass)
-
-
-if __name__ == '__main__':
- main()
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/tap.py b/Darwin/lib/python2.7/site-packages/twisted/conch/tap.py
deleted file mode 100644
index 5e58699..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/tap.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_tap -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Support module for making SSH servers with twistd.
-"""
-
-from twisted.conch import unix
-from twisted.conch import checkers as conch_checkers
-from twisted.conch.openssh_compat import factory
-from twisted.cred import portal, checkers, strcred
-from twisted.python import usage
-from twisted.application import strports
-try:
- from twisted.cred import pamauth
-except ImportError:
- pamauth = None
-
-
-
-class Options(usage.Options, strcred.AuthOptionMixin):
- synopsis = "[-i ] [-p ] [-d ] "
- longdesc = ("Makes a Conch SSH server. If no authentication methods are "
- "specified, the default authentication methods are UNIX passwords, "
- "SSH public keys, and PAM if it is available. If --auth options are "
- "passed, only the measures specified will be used.")
- optParameters = [
- ["interface", "i", "", "local interface to which we listen"],
- ["port", "p", "tcp:22", "Port on which to listen"],
- ["data", "d", "/etc", "directory to look for host keys in"],
- ["moduli", "", None, "directory to look for moduli in "
- "(if different from --data)"]
- ]
- compData = usage.Completions(
- optActions={"data": usage.CompleteDirs(descr="data directory"),
- "moduli": usage.CompleteDirs(descr="moduli directory"),
- "interface": usage.CompleteNetInterfaces()}
- )
-
-
- def __init__(self, *a, **kw):
- usage.Options.__init__(self, *a, **kw)
-
- # call the default addCheckers (for backwards compatibility) that will
- # be used if no --auth option is provided - note that conch's
- # UNIXPasswordDatabase is used, instead of twisted.plugins.cred_unix's
- # checker
- super(Options, self).addChecker(conch_checkers.UNIXPasswordDatabase())
- super(Options, self).addChecker(conch_checkers.SSHPublicKeyDatabase())
- if pamauth is not None:
- super(Options, self).addChecker(
- checkers.PluggableAuthenticationModulesChecker())
- self._usingDefaultAuth = True
-
-
- def addChecker(self, checker):
- """
- Add the checker specified. If any checkers are added, the default
- checkers are automatically cleared and the only checkers will be the
- specified one(s).
- """
- if self._usingDefaultAuth:
- self['credCheckers'] = []
- self['credInterfaces'] = {}
- self._usingDefaultAuth = False
- super(Options, self).addChecker(checker)
-
-
-
-def makeService(config):
- """
- Construct a service for operating a SSH server.
-
- @param config: An L{Options} instance specifying server options, including
- where server keys are stored and what authentication methods to use.
-
- @return: An L{IService} provider which contains the requested SSH server.
- """
-
- t = factory.OpenSSHFactory()
-
- r = unix.UnixSSHRealm()
- t.portal = portal.Portal(r, config.get('credCheckers', []))
- t.dataRoot = config['data']
- t.moduliRoot = config['moduli'] or config['data']
-
- port = config['port']
- if config['interface']:
- # Add warning here
- port += ':interface=' + config['interface']
- return strports.service(port, t)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/telnet.py b/Darwin/lib/python2.7/site-packages/twisted/conch/telnet.py
deleted file mode 100644
index c90fe1a..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/telnet.py
+++ /dev/null
@@ -1,1086 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_telnet -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Telnet protocol implementation.
-
-@author: Jean-Paul Calderone
-"""
-
-import struct
-
-from zope.interface import implements
-
-from twisted.internet import protocol, interfaces as iinternet, defer
-from twisted.python import log
-
-MODE = chr(1)
-EDIT = 1
-TRAPSIG = 2
-MODE_ACK = 4
-SOFT_TAB = 8
-LIT_ECHO = 16
-
-# Characters gleaned from the various (and conflicting) RFCs. Not all of these are correct.
-
-NULL = chr(0) # No operation.
-BEL = chr(7) # Produces an audible or
- # visible signal (which does
- # NOT move the print head).
-BS = chr(8) # Moves the print head one
- # character position towards
- # the left margin.
-HT = chr(9) # Moves the printer to the
- # next horizontal tab stop.
- # It remains unspecified how
- # either party determines or
- # establishes where such tab
- # stops are located.
-LF = chr(10) # Moves the printer to the
- # next print line, keeping the
- # same horizontal position.
-VT = chr(11) # Moves the printer to the
- # next vertical tab stop. It
- # remains unspecified how
- # either party determines or
- # establishes where such tab
- # stops are located.
-FF = chr(12) # Moves the printer to the top
- # of the next page, keeping
- # the same horizontal position.
-CR = chr(13) # Moves the printer to the left
- # margin of the current line.
-
-ECHO = chr(1) # User-to-Server: Asks the server to send
- # Echos of the transmitted data.
-SGA = chr(3) # Suppress Go Ahead. Go Ahead is silly
- # and most modern servers should suppress
- # it.
-NAWS = chr(31) # Negotiate About Window Size. Indicate that
- # information about the size of the terminal
- # can be communicated.
-LINEMODE = chr(34) # Allow line buffering to be
- # negotiated about.
-
-SE = chr(240) # End of subnegotiation parameters.
-NOP = chr(241) # No operation.
-DM = chr(242) # "Data Mark": The data stream portion
- # of a Synch. This should always be
- # accompanied by a TCP Urgent
- # notification.
-BRK = chr(243) # NVT character Break.
-IP = chr(244) # The function Interrupt Process.
-AO = chr(245) # The function Abort Output
-AYT = chr(246) # The function Are You There.
-EC = chr(247) # The function Erase Character.
-EL = chr(248) # The function Erase Line
-GA = chr(249) # The Go Ahead signal.
-SB = chr(250) # Indicates that what follows is
- # subnegotiation of the indicated
- # option.
-WILL = chr(251) # Indicates the desire to begin
- # performing, or confirmation that
- # you are now performing, the
- # indicated option.
-WONT = chr(252) # Indicates the refusal to perform,
- # or continue performing, the
- # indicated option.
-DO = chr(253) # Indicates the request that the
- # other party perform, or
- # confirmation that you are expecting
- # the other party to perform, the
- # indicated option.
-DONT = chr(254) # Indicates the demand that the
- # other party stop performing,
- # or confirmation that you are no
- # longer expecting the other party
- # to perform, the indicated option.
-IAC = chr(255) # Data Byte 255. Introduces a
- # telnet command.
-
-LINEMODE_MODE = chr(1)
-LINEMODE_EDIT = chr(1)
-LINEMODE_TRAPSIG = chr(2)
-LINEMODE_MODE_ACK = chr(4)
-LINEMODE_SOFT_TAB = chr(8)
-LINEMODE_LIT_ECHO = chr(16)
-LINEMODE_FORWARDMASK = chr(2)
-LINEMODE_SLC = chr(3)
-LINEMODE_SLC_SYNCH = chr(1)
-LINEMODE_SLC_BRK = chr(2)
-LINEMODE_SLC_IP = chr(3)
-LINEMODE_SLC_AO = chr(4)
-LINEMODE_SLC_AYT = chr(5)
-LINEMODE_SLC_EOR = chr(6)
-LINEMODE_SLC_ABORT = chr(7)
-LINEMODE_SLC_EOF = chr(8)
-LINEMODE_SLC_SUSP = chr(9)
-LINEMODE_SLC_EC = chr(10)
-LINEMODE_SLC_EL = chr(11)
-
-LINEMODE_SLC_EW = chr(12)
-LINEMODE_SLC_RP = chr(13)
-LINEMODE_SLC_LNEXT = chr(14)
-LINEMODE_SLC_XON = chr(15)
-LINEMODE_SLC_XOFF = chr(16)
-LINEMODE_SLC_FORW1 = chr(17)
-LINEMODE_SLC_FORW2 = chr(18)
-LINEMODE_SLC_MCL = chr(19)
-LINEMODE_SLC_MCR = chr(20)
-LINEMODE_SLC_MCWL = chr(21)
-LINEMODE_SLC_MCWR = chr(22)
-LINEMODE_SLC_MCBOL = chr(23)
-LINEMODE_SLC_MCEOL = chr(24)
-LINEMODE_SLC_INSRT = chr(25)
-LINEMODE_SLC_OVER = chr(26)
-LINEMODE_SLC_ECR = chr(27)
-LINEMODE_SLC_EWR = chr(28)
-LINEMODE_SLC_EBOL = chr(29)
-LINEMODE_SLC_EEOL = chr(30)
-
-LINEMODE_SLC_DEFAULT = chr(3)
-LINEMODE_SLC_VALUE = chr(2)
-LINEMODE_SLC_CANTCHANGE = chr(1)
-LINEMODE_SLC_NOSUPPORT = chr(0)
-LINEMODE_SLC_LEVELBITS = chr(3)
-
-LINEMODE_SLC_ACK = chr(128)
-LINEMODE_SLC_FLUSHIN = chr(64)
-LINEMODE_SLC_FLUSHOUT = chr(32)
-LINEMODE_EOF = chr(236)
-LINEMODE_SUSP = chr(237)
-LINEMODE_ABORT = chr(238)
-
-class ITelnetProtocol(iinternet.IProtocol):
- def unhandledCommand(command, argument):
- """A command was received but not understood.
-
- @param command: the command received.
- @type command: C{str}, a single character.
- @param argument: the argument to the received command.
- @type argument: C{str}, a single character, or None if the command that
- was unhandled does not provide an argument.
- """
-
- def unhandledSubnegotiation(command, bytes):
- """A subnegotiation command was received but not understood.
-
- @param command: the command being subnegotiated. That is, the first
- byte after the SB command.
- @type command: C{str}, a single character.
- @param bytes: all other bytes of the subneogation. That is, all but the
- first bytes between SB and SE, with IAC un-escaping applied.
- @type bytes: C{list} of C{str}, each a single character
- """
-
- def enableLocal(option):
- """Enable the given option locally.
-
- This should enable the given option on this side of the
- telnet connection and return True. If False is returned,
- the option will be treated as still disabled and the peer
- will be notified.
-
- @param option: the option to be enabled.
- @type option: C{str}, a single character.
- """
-
- def enableRemote(option):
- """Indicate whether the peer should be allowed to enable this option.
-
- Returns True if the peer should be allowed to enable this option,
- False otherwise.
-
- @param option: the option to be enabled.
- @type option: C{str}, a single character.
- """
-
- def disableLocal(option):
- """Disable the given option locally.
-
- Unlike enableLocal, this method cannot fail. The option must be
- disabled.
-
- @param option: the option to be disabled.
- @type option: C{str}, a single character.
- """
-
- def disableRemote(option):
- """Indicate that the peer has disabled this option.
-
- @param option: the option to be disabled.
- @type option: C{str}, a single character.
- """
-
-
-
-class ITelnetTransport(iinternet.ITransport):
- def do(option):
- """
- Indicate a desire for the peer to begin performing the given option.
-
- Returns a Deferred that fires with True when the peer begins performing
- the option, or fails with L{OptionRefused} when the peer refuses to
- perform it. If the peer is already performing the given option, the
- Deferred will fail with L{AlreadyEnabled}. If a negotiation regarding
- this option is already in progress, the Deferred will fail with
- L{AlreadyNegotiating}.
-
- Note: It is currently possible that this Deferred will never fire,
- if the peer never responds, or if the peer believes the option to
- already be enabled.
- """
-
-
- def dont(option):
- """
- Indicate a desire for the peer to cease performing the given option.
-
- Returns a Deferred that fires with True when the peer ceases performing
- the option. If the peer is not performing the given option, the
- Deferred will fail with L{AlreadyDisabled}. If negotiation regarding
- this option is already in progress, the Deferred will fail with
- L{AlreadyNegotiating}.
-
- Note: It is currently possible that this Deferred will never fire,
- if the peer never responds, or if the peer believes the option to
- already be disabled.
- """
-
-
- def will(option):
- """
- Indicate our willingness to begin performing this option locally.
-
- Returns a Deferred that fires with True when the peer agrees to allow us
- to begin performing this option, or fails with L{OptionRefused} if the
- peer refuses to allow us to begin performing it. If the option is
- already enabled locally, the Deferred will fail with L{AlreadyEnabled}.
- If negotiation regarding this option is already in progress, the
- Deferred will fail with L{AlreadyNegotiating}.
-
- Note: It is currently possible that this Deferred will never fire,
- if the peer never responds, or if the peer believes the option to
- already be enabled.
- """
-
-
- def wont(option):
- """
- Indicate that we will stop performing the given option.
-
- Returns a Deferred that fires with True when the peer acknowledges
- we have stopped performing this option. If the option is already
- disabled locally, the Deferred will fail with L{AlreadyDisabled}.
- If negotiation regarding this option is already in progress,
- the Deferred will fail with L{AlreadyNegotiating}.
-
- Note: It is currently possible that this Deferred will never fire,
- if the peer never responds, or if the peer believes the option to
- already be disabled.
- """
-
-
- def requestNegotiation(about, bytes):
- """
- Send a subnegotiation request.
-
- @param about: A byte indicating the feature being negotiated.
- @param bytes: Any number of bytes containing specific information
- about the negotiation being requested. No values in this string
- need to be escaped, as this function will escape any value which
- requires it.
- """
-
-
-
-class TelnetError(Exception):
- pass
-
-class NegotiationError(TelnetError):
- def __str__(self):
- return self.__class__.__module__ + '.' + self.__class__.__name__ + ':' + repr(self.args[0])
-
-class OptionRefused(NegotiationError):
- pass
-
-class AlreadyEnabled(NegotiationError):
- pass
-
-class AlreadyDisabled(NegotiationError):
- pass
-
-class AlreadyNegotiating(NegotiationError):
- pass
-
-class TelnetProtocol(protocol.Protocol):
- implements(ITelnetProtocol)
-
- def unhandledCommand(self, command, argument):
- pass
-
- def unhandledSubnegotiation(self, command, bytes):
- pass
-
- def enableLocal(self, option):
- pass
-
- def enableRemote(self, option):
- pass
-
- def disableLocal(self, option):
- pass
-
- def disableRemote(self, option):
- pass
-
-
-class Telnet(protocol.Protocol):
- """
- @ivar commandMap: A mapping of bytes to callables. When a
- telnet command is received, the command byte (the first byte
- after IAC) is looked up in this dictionary. If a callable is
- found, it is invoked with the argument of the command, or None
- if the command takes no argument. Values should be added to
- this dictionary if commands wish to be handled. By default,
- only WILL, WONT, DO, and DONT are handled. These should not
- be overridden, as this class handles them correctly and
- provides an API for interacting with them.
-
- @ivar negotiationMap: A mapping of bytes to callables. When
- a subnegotiation command is received, the command byte (the
- first byte after SB) is looked up in this dictionary. If
- a callable is found, it is invoked with the argument of the
- subnegotiation. Values should be added to this dictionary if
- subnegotiations are to be handled. By default, no values are
- handled.
-
- @ivar options: A mapping of option bytes to their current
- state. This state is likely of little use to user code.
- Changes should not be made to it.
-
- @ivar state: A string indicating the current parse state. It
- can take on the values "data", "escaped", "command", "newline",
- "subnegotiation", and "subnegotiation-escaped". Changes
- should not be made to it.
-
- @ivar transport: This protocol's transport object.
- """
-
- # One of a lot of things
- state = 'data'
-
- def __init__(self):
- self.options = {}
- self.negotiationMap = {}
- self.commandMap = {
- WILL: self.telnet_WILL,
- WONT: self.telnet_WONT,
- DO: self.telnet_DO,
- DONT: self.telnet_DONT}
-
- def _write(self, bytes):
- self.transport.write(bytes)
-
- class _OptionState:
- """
- Represents the state of an option on both sides of a telnet
- connection.
-
- @ivar us: The state of the option on this side of the connection.
-
- @ivar him: The state of the option on the other side of the
- connection.
- """
- class _Perspective:
- """
- Represents the state of an option on side of the telnet
- connection. Some options can be enabled on a particular side of
- the connection (RFC 1073 for example: only the client can have
- NAWS enabled). Other options can be enabled on either or both
- sides (such as RFC 1372: each side can have its own flow control
- state).
-
- @ivar state: C{'yes'} or C{'no'} indicating whether or not this
- option is enabled on one side of the connection.
-
- @ivar negotiating: A boolean tracking whether negotiation about
- this option is in progress.
-
- @ivar onResult: When negotiation about this option has been
- initiated by this side of the connection, a L{Deferred}
- which will fire with the result of the negotiation. C{None}
- at other times.
- """
- state = 'no'
- negotiating = False
- onResult = None
-
- def __str__(self):
- return self.state + ('*' * self.negotiating)
-
- def __init__(self):
- self.us = self._Perspective()
- self.him = self._Perspective()
-
- def __repr__(self):
- return '<_OptionState us=%s him=%s>' % (self.us, self.him)
-
- def getOptionState(self, opt):
- return self.options.setdefault(opt, self._OptionState())
-
- def _do(self, option):
- self._write(IAC + DO + option)
-
- def _dont(self, option):
- self._write(IAC + DONT + option)
-
- def _will(self, option):
- self._write(IAC + WILL + option)
-
- def _wont(self, option):
- self._write(IAC + WONT + option)
-
- def will(self, option):
- """Indicate our willingness to enable an option.
- """
- s = self.getOptionState(option)
- if s.us.negotiating or s.him.negotiating:
- return defer.fail(AlreadyNegotiating(option))
- elif s.us.state == 'yes':
- return defer.fail(AlreadyEnabled(option))
- else:
- s.us.negotiating = True
- s.us.onResult = d = defer.Deferred()
- self._will(option)
- return d
-
- def wont(self, option):
- """Indicate we are not willing to enable an option.
- """
- s = self.getOptionState(option)
- if s.us.negotiating or s.him.negotiating:
- return defer.fail(AlreadyNegotiating(option))
- elif s.us.state == 'no':
- return defer.fail(AlreadyDisabled(option))
- else:
- s.us.negotiating = True
- s.us.onResult = d = defer.Deferred()
- self._wont(option)
- return d
-
- def do(self, option):
- s = self.getOptionState(option)
- if s.us.negotiating or s.him.negotiating:
- return defer.fail(AlreadyNegotiating(option))
- elif s.him.state == 'yes':
- return defer.fail(AlreadyEnabled(option))
- else:
- s.him.negotiating = True
- s.him.onResult = d = defer.Deferred()
- self._do(option)
- return d
-
- def dont(self, option):
- s = self.getOptionState(option)
- if s.us.negotiating or s.him.negotiating:
- return defer.fail(AlreadyNegotiating(option))
- elif s.him.state == 'no':
- return defer.fail(AlreadyDisabled(option))
- else:
- s.him.negotiating = True
- s.him.onResult = d = defer.Deferred()
- self._dont(option)
- return d
-
-
- def requestNegotiation(self, about, bytes):
- """
- Send a negotiation message for the option C{about} with C{bytes} as the
- payload.
-
- @see: L{ITelnetTransport.requestNegotiation}
- """
- bytes = bytes.replace(IAC, IAC * 2)
- self._write(IAC + SB + about + bytes + IAC + SE)
-
-
- def dataReceived(self, data):
- appDataBuffer = []
-
- for b in data:
- if self.state == 'data':
- if b == IAC:
- self.state = 'escaped'
- elif b == '\r':
- self.state = 'newline'
- else:
- appDataBuffer.append(b)
- elif self.state == 'escaped':
- if b == IAC:
- appDataBuffer.append(b)
- self.state = 'data'
- elif b == SB:
- self.state = 'subnegotiation'
- self.commands = []
- elif b in (NOP, DM, BRK, IP, AO, AYT, EC, EL, GA):
- self.state = 'data'
- if appDataBuffer:
- self.applicationDataReceived(''.join(appDataBuffer))
- del appDataBuffer[:]
- self.commandReceived(b, None)
- elif b in (WILL, WONT, DO, DONT):
- self.state = 'command'
- self.command = b
- else:
- raise ValueError("Stumped", b)
- elif self.state == 'command':
- self.state = 'data'
- command = self.command
- del self.command
- if appDataBuffer:
- self.applicationDataReceived(''.join(appDataBuffer))
- del appDataBuffer[:]
- self.commandReceived(command, b)
- elif self.state == 'newline':
- self.state = 'data'
- if b == '\n':
- appDataBuffer.append('\n')
- elif b == '\0':
- appDataBuffer.append('\r')
- elif b == IAC:
- # IAC isn't really allowed after \r, according to the
- # RFC, but handling it this way is less surprising than
- # delivering the IAC to the app as application data.
- # The purpose of the restriction is to allow terminals
- # to unambiguously interpret the behavior of the CR
- # after reading only one more byte. CR LF is supposed
- # to mean one thing (cursor to next line, first column),
- # CR NUL another (cursor to first column). Absent the
- # NUL, it still makes sense to interpret this as CR and
- # then apply all the usual interpretation to the IAC.
- appDataBuffer.append('\r')
- self.state = 'escaped'
- else:
- appDataBuffer.append('\r' + b)
- elif self.state == 'subnegotiation':
- if b == IAC:
- self.state = 'subnegotiation-escaped'
- else:
- self.commands.append(b)
- elif self.state == 'subnegotiation-escaped':
- if b == SE:
- self.state = 'data'
- commands = self.commands
- del self.commands
- if appDataBuffer:
- self.applicationDataReceived(''.join(appDataBuffer))
- del appDataBuffer[:]
- self.negotiate(commands)
- else:
- self.state = 'subnegotiation'
- self.commands.append(b)
- else:
- raise ValueError("How'd you do this?")
-
- if appDataBuffer:
- self.applicationDataReceived(''.join(appDataBuffer))
-
-
- def connectionLost(self, reason):
- for state in self.options.values():
- if state.us.onResult is not None:
- d = state.us.onResult
- state.us.onResult = None
- d.errback(reason)
- if state.him.onResult is not None:
- d = state.him.onResult
- state.him.onResult = None
- d.errback(reason)
-
- def applicationDataReceived(self, bytes):
- """Called with application-level data.
- """
-
- def unhandledCommand(self, command, argument):
- """Called for commands for which no handler is installed.
- """
-
- def commandReceived(self, command, argument):
- cmdFunc = self.commandMap.get(command)
- if cmdFunc is None:
- self.unhandledCommand(command, argument)
- else:
- cmdFunc(argument)
-
- def unhandledSubnegotiation(self, command, bytes):
- """Called for subnegotiations for which no handler is installed.
- """
-
- def negotiate(self, bytes):
- command, bytes = bytes[0], bytes[1:]
- cmdFunc = self.negotiationMap.get(command)
- if cmdFunc is None:
- self.unhandledSubnegotiation(command, bytes)
- else:
- cmdFunc(bytes)
-
- def telnet_WILL(self, option):
- s = self.getOptionState(option)
- self.willMap[s.him.state, s.him.negotiating](self, s, option)
-
- def will_no_false(self, state, option):
- # He is unilaterally offering to enable an option.
- if self.enableRemote(option):
- state.him.state = 'yes'
- self._do(option)
- else:
- self._dont(option)
-
- def will_no_true(self, state, option):
- # Peer agreed to enable an option in response to our request.
- state.him.state = 'yes'
- state.him.negotiating = False
- d = state.him.onResult
- state.him.onResult = None
- d.callback(True)
- assert self.enableRemote(option), "enableRemote must return True in this context (for option %r)" % (option,)
-
- def will_yes_false(self, state, option):
- # He is unilaterally offering to enable an already-enabled option.
- # Ignore this.
- pass
-
- def will_yes_true(self, state, option):
- # This is a bogus state. It is here for completeness. It will
- # never be entered.
- assert False, "will_yes_true can never be entered, but was called with %r, %r" % (state, option)
-
- willMap = {('no', False): will_no_false, ('no', True): will_no_true,
- ('yes', False): will_yes_false, ('yes', True): will_yes_true}
-
- def telnet_WONT(self, option):
- s = self.getOptionState(option)
- self.wontMap[s.him.state, s.him.negotiating](self, s, option)
-
- def wont_no_false(self, state, option):
- # He is unilaterally demanding that an already-disabled option be/remain disabled.
- # Ignore this (although we could record it and refuse subsequent enable attempts
- # from our side - he can always refuse them again though, so we won't)
- pass
-
- def wont_no_true(self, state, option):
- # Peer refused to enable an option in response to our request.
- state.him.negotiating = False
- d = state.him.onResult
- state.him.onResult = None
- d.errback(OptionRefused(option))
-
- def wont_yes_false(self, state, option):
- # Peer is unilaterally demanding that an option be disabled.
- state.him.state = 'no'
- self.disableRemote(option)
- self._dont(option)
-
- def wont_yes_true(self, state, option):
- # Peer agreed to disable an option at our request.
- state.him.state = 'no'
- state.him.negotiating = False
- d = state.him.onResult
- state.him.onResult = None
- d.callback(True)
- self.disableRemote(option)
-
- wontMap = {('no', False): wont_no_false, ('no', True): wont_no_true,
- ('yes', False): wont_yes_false, ('yes', True): wont_yes_true}
-
- def telnet_DO(self, option):
- s = self.getOptionState(option)
- self.doMap[s.us.state, s.us.negotiating](self, s, option)
-
- def do_no_false(self, state, option):
- # Peer is unilaterally requesting that we enable an option.
- if self.enableLocal(option):
- state.us.state = 'yes'
- self._will(option)
- else:
- self._wont(option)
-
- def do_no_true(self, state, option):
- # Peer agreed to allow us to enable an option at our request.
- state.us.state = 'yes'
- state.us.negotiating = False
- d = state.us.onResult
- state.us.onResult = None
- d.callback(True)
- self.enableLocal(option)
-
- def do_yes_false(self, state, option):
- # Peer is unilaterally requesting us to enable an already-enabled option.
- # Ignore this.
- pass
-
- def do_yes_true(self, state, option):
- # This is a bogus state. It is here for completeness. It will never be
- # entered.
- assert False, "do_yes_true can never be entered, but was called with %r, %r" % (state, option)
-
- doMap = {('no', False): do_no_false, ('no', True): do_no_true,
- ('yes', False): do_yes_false, ('yes', True): do_yes_true}
-
- def telnet_DONT(self, option):
- s = self.getOptionState(option)
- self.dontMap[s.us.state, s.us.negotiating](self, s, option)
-
- def dont_no_false(self, state, option):
- # Peer is unilaterally demanding us to disable an already-disabled option.
- # Ignore this.
- pass
-
- def dont_no_true(self, state, option):
- # Offered option was refused. Fail the Deferred returned by the
- # previous will() call.
- state.us.negotiating = False
- d = state.us.onResult
- state.us.onResult = None
- d.errback(OptionRefused(option))
-
- def dont_yes_false(self, state, option):
- # Peer is unilaterally demanding we disable an option.
- state.us.state = 'no'
- self.disableLocal(option)
- self._wont(option)
-
- def dont_yes_true(self, state, option):
- # Peer acknowledged our notice that we will disable an option.
- state.us.state = 'no'
- state.us.negotiating = False
- d = state.us.onResult
- state.us.onResult = None
- d.callback(True)
- self.disableLocal(option)
-
- dontMap = {('no', False): dont_no_false, ('no', True): dont_no_true,
- ('yes', False): dont_yes_false, ('yes', True): dont_yes_true}
-
- def enableLocal(self, option):
- """
- Reject all attempts to enable options.
- """
- return False
-
-
- def enableRemote(self, option):
- """
- Reject all attempts to enable options.
- """
- return False
-
-
- def disableLocal(self, option):
- """
- Signal a programming error by raising an exception.
-
- L{enableLocal} must return true for the given value of C{option} in
- order for this method to be called. If a subclass of L{Telnet}
- overrides enableLocal to allow certain options to be enabled, it must
- also override disableLocal to disable those options.
-
- @raise NotImplementedError: Always raised.
- """
- raise NotImplementedError(
- "Don't know how to disable local telnet option %r" % (option,))
-
-
- def disableRemote(self, option):
- """
- Signal a programming error by raising an exception.
-
- L{enableRemote} must return true for the given value of C{option} in
- order for this method to be called. If a subclass of L{Telnet}
- overrides enableRemote to allow certain options to be enabled, it must
- also override disableRemote tto disable those options.
-
- @raise NotImplementedError: Always raised.
- """
- raise NotImplementedError(
- "Don't know how to disable remote telnet option %r" % (option,))
-
-
-
-class ProtocolTransportMixin:
- def write(self, bytes):
- self.transport.write(bytes.replace('\n', '\r\n'))
-
- def writeSequence(self, seq):
- self.transport.writeSequence(seq)
-
- def loseConnection(self):
- self.transport.loseConnection()
-
- def getHost(self):
- return self.transport.getHost()
-
- def getPeer(self):
- return self.transport.getPeer()
-
-class TelnetTransport(Telnet, ProtocolTransportMixin):
- """
- @ivar protocol: An instance of the protocol to which this
- transport is connected, or None before the connection is
- established and after it is lost.
-
- @ivar protocolFactory: A callable which returns protocol instances
- which provide L{ITelnetProtocol}. This will be invoked when a
- connection is established. It is passed *protocolArgs and
- **protocolKwArgs.
-
- @ivar protocolArgs: A tuple of additional arguments to
- pass to protocolFactory.
-
- @ivar protocolKwArgs: A dictionary of additional arguments
- to pass to protocolFactory.
- """
-
- disconnecting = False
-
- protocolFactory = None
- protocol = None
-
- def __init__(self, protocolFactory=None, *a, **kw):
- Telnet.__init__(self)
- if protocolFactory is not None:
- self.protocolFactory = protocolFactory
- self.protocolArgs = a
- self.protocolKwArgs = kw
-
- def connectionMade(self):
- if self.protocolFactory is not None:
- self.protocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs)
- assert ITelnetProtocol.providedBy(self.protocol)
- try:
- factory = self.factory
- except AttributeError:
- pass
- else:
- self.protocol.factory = factory
- self.protocol.makeConnection(self)
-
- def connectionLost(self, reason):
- Telnet.connectionLost(self, reason)
- if self.protocol is not None:
- try:
- self.protocol.connectionLost(reason)
- finally:
- del self.protocol
-
- def enableLocal(self, option):
- return self.protocol.enableLocal(option)
-
- def enableRemote(self, option):
- return self.protocol.enableRemote(option)
-
- def disableLocal(self, option):
- return self.protocol.disableLocal(option)
-
- def disableRemote(self, option):
- return self.protocol.disableRemote(option)
-
- def unhandledSubnegotiation(self, command, bytes):
- self.protocol.unhandledSubnegotiation(command, bytes)
-
- def unhandledCommand(self, command, argument):
- self.protocol.unhandledCommand(command, argument)
-
- def applicationDataReceived(self, bytes):
- self.protocol.dataReceived(bytes)
-
- def write(self, data):
- ProtocolTransportMixin.write(self, data.replace('\xff','\xff\xff'))
-
-
-class TelnetBootstrapProtocol(TelnetProtocol, ProtocolTransportMixin):
- implements()
-
- protocol = None
-
- def __init__(self, protocolFactory, *args, **kw):
- self.protocolFactory = protocolFactory
- self.protocolArgs = args
- self.protocolKwArgs = kw
-
- def connectionMade(self):
- self.transport.negotiationMap[NAWS] = self.telnet_NAWS
- self.transport.negotiationMap[LINEMODE] = self.telnet_LINEMODE
-
- for opt in (LINEMODE, NAWS, SGA):
- self.transport.do(opt).addErrback(log.err)
- for opt in (ECHO,):
- self.transport.will(opt).addErrback(log.err)
-
- self.protocol = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs)
-
- try:
- factory = self.factory
- except AttributeError:
- pass
- else:
- self.protocol.factory = factory
-
- self.protocol.makeConnection(self)
-
- def connectionLost(self, reason):
- if self.protocol is not None:
- try:
- self.protocol.connectionLost(reason)
- finally:
- del self.protocol
-
- def dataReceived(self, data):
- self.protocol.dataReceived(data)
-
- def enableLocal(self, opt):
- if opt == ECHO:
- return True
- elif opt == SGA:
- return True
- else:
- return False
-
- def enableRemote(self, opt):
- if opt == LINEMODE:
- self.transport.requestNegotiation(LINEMODE, MODE + chr(TRAPSIG))
- return True
- elif opt == NAWS:
- return True
- elif opt == SGA:
- return True
- else:
- return False
-
- def telnet_NAWS(self, bytes):
- # NAWS is client -> server *only*. self.protocol will
- # therefore be an ITerminalTransport, the `.protocol'
- # attribute of which will be an ITerminalProtocol. Maybe.
- # You know what, XXX TODO clean this up.
- if len(bytes) == 4:
- width, height = struct.unpack('!HH', ''.join(bytes))
- self.protocol.terminalProtocol.terminalSize(width, height)
- else:
- log.msg("Wrong number of NAWS bytes")
-
-
- linemodeSubcommands = {
- LINEMODE_SLC: 'SLC'}
- def telnet_LINEMODE(self, bytes):
- revmap = {}
- linemodeSubcommand = bytes[0]
- if 0:
- # XXX TODO: This should be enabled to parse linemode subnegotiation.
- getattr(self, 'linemode_' + self.linemodeSubcommands[linemodeSubcommand])(bytes[1:])
-
- def linemode_SLC(self, bytes):
- chunks = zip(*[iter(bytes)]*3)
- for slcFunction, slcValue, slcWhat in chunks:
- # Later, we should parse stuff.
- 'SLC', ord(slcFunction), ord(slcValue), ord(slcWhat)
-
-from twisted.protocols import basic
-
-class StatefulTelnetProtocol(basic.LineReceiver, TelnetProtocol):
- delimiter = '\n'
-
- state = 'Discard'
-
- def connectionLost(self, reason):
- basic.LineReceiver.connectionLost(self, reason)
- TelnetProtocol.connectionLost(self, reason)
-
- def lineReceived(self, line):
- oldState = self.state
- newState = getattr(self, "telnet_" + oldState)(line)
- if newState is not None:
- if self.state == oldState:
- self.state = newState
- else:
- log.msg("Warning: state changed and new state returned")
-
- def telnet_Discard(self, line):
- pass
-
-from twisted.cred import credentials
-
-class AuthenticatingTelnetProtocol(StatefulTelnetProtocol):
- """A protocol which prompts for credentials and attempts to authenticate them.
-
- Username and password prompts are given (the password is obscured). When the
- information is collected, it is passed to a portal and an avatar implementing
- L{ITelnetProtocol} is requested. If an avatar is returned, it connected to this
- protocol's transport, and this protocol's transport is connected to it.
- Otherwise, the user is re-prompted for credentials.
- """
-
- state = "User"
- protocol = None
-
- def __init__(self, portal):
- self.portal = portal
-
- def connectionMade(self):
- self.transport.write("Username: ")
-
- def connectionLost(self, reason):
- StatefulTelnetProtocol.connectionLost(self, reason)
- if self.protocol is not None:
- try:
- self.protocol.connectionLost(reason)
- self.logout()
- finally:
- del self.protocol, self.logout
-
- def telnet_User(self, line):
- self.username = line
- self.transport.will(ECHO)
- self.transport.write("Password: ")
- return 'Password'
-
- def telnet_Password(self, line):
- username, password = self.username, line
- del self.username
- def login(ignored):
- creds = credentials.UsernamePassword(username, password)
- d = self.portal.login(creds, None, ITelnetProtocol)
- d.addCallback(self._cbLogin)
- d.addErrback(self._ebLogin)
- self.transport.wont(ECHO).addCallback(login)
- return 'Discard'
-
- def _cbLogin(self, ial):
- interface, protocol, logout = ial
- assert interface is ITelnetProtocol
- self.protocol = protocol
- self.logout = logout
- self.state = 'Command'
-
- protocol.makeConnection(self.transport)
- self.transport.protocol = protocol
-
- def _ebLogin(self, failure):
- self.transport.write("\nAuthentication failed\n")
- self.transport.write("Username: ")
- self.state = "User"
-
-__all__ = [
- # Exceptions
- 'TelnetError', 'NegotiationError', 'OptionRefused',
- 'AlreadyNegotiating', 'AlreadyEnabled', 'AlreadyDisabled',
-
- # Interfaces
- 'ITelnetProtocol', 'ITelnetTransport',
-
- # Other stuff, protocols, etc.
- 'Telnet', 'TelnetProtocol', 'TelnetTransport',
- 'TelnetBootstrapProtocol',
-
- ]
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/__init__.py
deleted file mode 100644
index d09b412..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-'conch tests'
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/keydata.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/keydata.py
deleted file mode 100644
index 9417ec5..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/keydata.py
+++ /dev/null
@@ -1,208 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_keys -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Data used by test_keys as well as others.
-"""
-RSAData = {
- 'n':long('1062486685755247411169438309495398947372127791189432809481'
- '382072971106157632182084539383569281493520117634129557550415277'
- '516685881326038852354459895734875625093273594925884531272867425'
- '864910490065695876046999646807138717162833156501L'),
- 'e':35L,
- 'd':long('6678487739032983727350755088256793383481946116047863373882'
- '973030104095847973715959961839578340816412167985957218887914482'
- '713602371850869127033494910375212470664166001439410214474266799'
- '85974425203903884190893469297150446322896587555L'),
- 'q':long('3395694744258061291019136154000709371890447462086362702627'
- '9704149412726577280741108645721676968699696898960891593323L'),
- 'p':long('3128922844292337321766351031842562691837301298995834258844'
- '4720539204069737532863831050930719431498338835415515173887L')}
-
-DSAData = {
- 'y':long('2300663509295750360093768159135720439490120577534296730713'
- '348508834878775464483169644934425336771277908527130096489120714'
- '610188630979820723924744291603865L'),
- 'g':long('4451569990409370769930903934104221766858515498655655091803'
- '866645719060300558655677517139568505649468378587802312867198352'
- '1161998270001677664063945776405L'),
- 'p':long('7067311773048598659694590252855127633397024017439939353776'
- '608320410518694001356789646664502838652272205440894335303988504'
- '978724817717069039110940675621677L'),
- 'q':1184501645189849666738820838619601267690550087703L,
- 'x':863951293559205482820041244219051653999559962819L}
-
-publicRSA_openssh = ("ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEArzJx8OYOnJmzf4tfBE"
-"vLi8DVPrJ3/c9k2I/Az64fxjHf9imyRJbixtQhlH9lfNjUIx+4LmrJH5QNRsFporcHDKOTwTTYL"
-"h5KmRpslkYHRivcJSkbh/C+BR3utDS555mV comment")
-
-privateRSA_openssh = """-----BEGIN RSA PRIVATE KEY-----
-MIIByAIBAAJhAK8ycfDmDpyZs3+LXwRLy4vA1T6yd/3PZNiPwM+uH8Yx3/YpskSW
-4sbUIZR/ZXzY1CMfuC5qyR+UDUbBaaK3Bwyjk8E02C4eSpkabJZGB0Yr3CUpG4fw
-vgUd7rQ0ueeZlQIBIwJgbh+1VZfr7WftK5lu7MHtqE1S1vPWZQYE3+VUn8yJADyb
-Z4fsZaCrzW9lkIqXkE3GIY+ojdhZhkO1gbG0118sIgphwSWKRxK0mvh6ERxKqIt1
-xJEJO74EykXZV4oNJ8sjAjEA3J9r2ZghVhGN6V8DnQrTk24Td0E8hU8AcP0FVP+8
-PQm/g/aXf2QQkQT+omdHVEJrAjEAy0pL0EBH6EVS98evDCBtQw22OZT52qXlAwZ2
-gyTriKFVoqjeEjt3SZKKqXHSApP/AjBLpF99zcJJZRq2abgYlf9lv1chkrWqDHUu
-DZttmYJeEfiFBBavVYIF1dOlZT0G8jMCMBc7sOSZodFnAiryP+Qg9otSBjJ3bQML
-pSTqy7c3a2AScC/YyOwkDaICHnnD3XyjMwIxALRzl0tQEKMXs6hH8ToUdlLROCrP
-EhQ0wahUTCk1gKA4uPD6TMTChavbh4K63OvbKg==
------END RSA PRIVATE KEY-----"""
-
-# some versions of OpenSSH generate these (slightly different keys)
-privateRSA_openssh_alternate = """-----BEGIN RSA PRIVATE KEY-----
-MIIBzjCCAcgCAQACYQCvMnHw5g6cmbN/i18ES8uLwNU+snf9z2TYj8DPrh/GMd/2
-KbJEluLG1CGUf2V82NQjH7guaskflA1GwWmitwcMo5PBNNguHkqZGmyWRgdGK9wl
-KRuH8L4FHe60NLnnmZUCASMCYG4ftVWX6+1n7SuZbuzB7ahNUtbz1mUGBN/lVJ/M
-iQA8m2eH7GWgq81vZZCKl5BNxiGPqI3YWYZDtYGxtNdfLCIKYcElikcStJr4ehEc
-SqiLdcSRCTu+BMpF2VeKDSfLIwIxANyfa9mYIVYRjelfA50K05NuE3dBPIVPAHD9
-BVT/vD0Jv4P2l39kEJEE/qJnR1RCawIxAMtKS9BAR+hFUvfHrwwgbUMNtjmU+dql
-5QMGdoMk64ihVaKo3hI7d0mSiqlx0gKT/wIwS6Rffc3CSWUatmm4GJX/Zb9XIZK1
-qgx1Lg2bbZmCXhH4hQQWr1WCBdXTpWU9BvIzAjAXO7DkmaHRZwIq8j/kIPaLUgYy
-d20DC6Uk6su3N2tgEnAv2MjsJA2iAh55w918ozMCMQC0c5dLUBCjF7OoR/E6FHZS
-0TgqzxIUNMGoVEwpNYCgOLjw+kzEwoWr24eCutzr2yowAA==
-------END RSA PRIVATE KEY------"""
-
-# encrypted with the passphrase 'encrypted'
-privateRSA_openssh_encrypted = """-----BEGIN RSA PRIVATE KEY-----
-Proc-Type: 4,ENCRYPTED
-DEK-Info: DES-EDE3-CBC,FFFFFFFFFFFFFFFF
-
-30qUR7DYY/rpVJu159paRM1mUqt/IMibfEMTKWSjNhCVD21hskftZCJROw/WgIFt
-ncusHpJMkjgwEpho0KyKilcC7zxjpunTex24Meb5pCdXCrYft8AyUkRdq3dugMqT
-4nuWuWxziluBhKQ2M9tPGcEOeulU4vVjceZt2pZhZQVBf08o3XUv5/7RYd24M9md
-WIo+5zdj2YQkI6xMFTP954O/X32ME1KQt98wgNEy6mxhItbvf00mH3woALwEKP3v
-PSMxxtx3VKeDKd9YTOm1giKkXZUf91vZWs0378tUBrU4U5qJxgryTjvvVKOtofj6
-4qQy6+r6M6wtwVlXBgeRm2gBPvL3nv6MsROp3E6ztBd/e7A8fSec+UTq3ko/EbGP
-0QG+IG5tg8FsdITxQ9WAIITZL3Rc6hA5Ymx1VNhySp3iSiso8Jof27lku4pyuvRV
-ko/B3N2H7LnQrGV0GyrjeYocW/qZh/PCsY48JBFhlNQexn2mn44AJW3y5xgbhvKA
-3mrmMD1hD17ZvZxi4fPHjbuAyM1vFqhQx63eT9ijbwJ91svKJl5O5MIv41mCRonm
-hxvOXw8S0mjSasyofptzzQCtXxFLQigXbpQBltII+Ys=
------END RSA PRIVATE KEY-----"""
-
-# encrypted with the passphrase 'testxp'. NB: this key was generated by
-# OpenSSH, so it doesn't use the same key data as the other keys here.
-privateRSA_openssh_encrypted_aes = """-----BEGIN RSA PRIVATE KEY-----
-Proc-Type: 4,ENCRYPTED
-DEK-Info: AES-128-CBC,0673309A6ACCAB4B77DEE1C1E536AC26
-
-4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n
-T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H
-g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB
-sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5
-9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV
-gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW
-0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE
-vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS
-hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC+OEKP+/s6HSKuqk
-2bzcl3/TcZXNSM815hnFRpz0anuyAsvwPNRyvxG2/DacJHL1f6luV4B0o6W410yf
-qXQx01DLo7nuyhJqoH3UGCyyXB+/QUs0mbG2PAEn3f5dVs31JMdbt+PrxURXXjKk
-4cexpUcIpqqlfpIRe3RD0sDVbH4OXsGhi2kiTfPZu7mgyFxKopRbn1KwU1qKinfY
-EU9O4PoTak/tPT+5jFNhaP+HrURoi/pU8EAUNSktl7xAkHYwkN/9Cm7DeBghgf3n
-8+tyCGYDsB5utPD0/Xe9yx0Qhc/kMm4xIyQDyA937dk3mUvLC9vulnAP8I+Izim0
-fZ182+D1bWwykoD0997mUHG/AUChWR01V1OLwRyPv2wUtiS8VNG76Y2aqKlgqP1P
-V+IvIEqR4ERvSBVFzXNF8Y6j/sVxo8+aZw+d0L1Ns/R55deErGg3B8i/2EqGd3r+
-0jps9BqFHHWW87n3VyEB3jWCMj8Vi2EJIfa/7pSaViFIQn8LiBLf+zxG5LTOToK5
-xkN42fReDcqi3UNfKNGnv4dsplyTR2hyx65lsj4bRKDGLKOuB1y7iB0AGb0LtcAI
-dcsVlcCeUquDXtqKvRnwfIMg+ZunyjqHBhj3qgRgbXbT6zjaSdNnih569aTg0Vup
-VykzZ7+n/KVcGLmvX0NesdoI7TKbq4TnEIOynuG5Sf+2GpARO5bjcWKSZeN/Ybgk
-gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c
-8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw
-SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7
-CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE
-xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P
------END RSA PRIVATE KEY-----"""
-
-publicRSA_lsh = ("{KDEwOnB1YmxpYy1rZXkoMTQ6cnNhLXBrY3MxLXNoYTEoMTpuOTc6AK8yc"
-"fDmDpyZs3+LXwRLy4vA1T6yd/3PZNiPwM+uH8Yx3/YpskSW4sbUIZR/ZXzY1CMfuC5qyR+UDUbB"
-"aaK3Bwyjk8E02C4eSpkabJZGB0Yr3CUpG4fwvgUd7rQ0ueeZlSkoMTplMTojKSkp}")
-
-privateRSA_lsh = ("(11:private-key(9:rsa-pkcs1(1:n97:\x00\xaf2q\xf0\xe6\x0e"
-"\x9c\x99\xb3\x7f\x8b_\x04K\xcb\x8b\xc0\xd5>\xb2w\xfd\xcfd\xd8\x8f\xc0\xcf"
-"\xae\x1f\xc61\xdf\xf6)\xb2D\x96\xe2\xc6\xd4!\x94\x7fe|\xd8\xd4#\x1f\xb8.j"
-"\xc9\x1f\x94\rF\xc1i\xa2\xb7\x07\x0c\xa3\x93\xc14\xd8.\x1eJ\x99\x1al\x96F"
-"\x07F+\xdc%)\x1b\x87\xf0\xbe\x05\x1d\xee\xb44\xb9\xe7\x99\x95)(1:e1:#)(1:d9"
-"6:n\x1f\xb5U\x97\xeb\xedg\xed+\x99n\xec\xc1\xed\xa8MR\xd6\xf3\xd6e\x06\x04"
-"\xdf\xe5T\x9f\xcc\x89\x00<\x9bg\x87\xece\xa0\xab\xcdoe\x90\x8a\x97\x90M\xc6"
-'!\x8f\xa8\x8d\xd8Y\x86C\xb5\x81\xb1\xb4\xd7_,"\na\xc1%\x8aG\x12\xb4\x9a\xf8'
-"z\x11\x1cJ\xa8\x8bu\xc4\x91\t;\xbe\x04\xcaE\xd9W\x8a\r\'\xcb#)(1:p49:\x00"
-"\xdc\x9fk\xd9\x98!V\x11\x8d\xe9_\x03\x9d\n\xd3\x93n\x13wA<\x85O\x00p\xfd"
-"\x05T\xff\xbc=\t\xbf\x83\xf6\x97\x7fd\x10\x91\x04\xfe\xa2gGTBk)(1:q49:\x00"
-"\xcbJK\xd0@G\xe8ER\xf7\xc7\xaf\x0c mC\r\xb69\x94\xf9\xda\xa5\xe5\x03\x06v"
-"\x83$\xeb\x88\xa1U\xa2\xa8\xde\x12;wI\x92\x8a\xa9q\xd2\x02\x93\xff)(1:a48:K"
-"\xa4_}\xcd\xc2Ie\x1a\xb6i\xb8\x18\x95\xffe\xbfW!\x92\xb5\xaa\x0cu.\r\x9bm"
-"\x99\x82^\x11\xf8\x85\x04\x16\xafU\x82\x05\xd5\xd3\xa5e=\x06\xf23)(1:b48:"
-"\x17;\xb0\xe4\x99\xa1\xd1g\x02*\xf2?\xe4 \xf6\x8bR\x062wm\x03\x0b\xa5$\xea"
-"\xcb\xb77k`\x12p/\xd8\xc8\xec$\r\xa2\x02\x1ey\xc3\xdd|\xa33)(1:c49:\x00\xb4"
-"s\x97KP\x10\xa3\x17\xb3\xa8G\xf1:\x14vR\xd18*\xcf\x12\x144\xc1\xa8TL)5\x80"
-"\xa08\xb8\xf0\xfaL\xc4\xc2\x85\xab\xdb\x87\x82\xba\xdc\xeb\xdb*)))")
-
-privateRSA_agentv3 = ("\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x01#\x00\x00\x00`"
-"n\x1f\xb5U\x97\xeb\xedg\xed+\x99n\xec\xc1\xed\xa8MR\xd6\xf3\xd6e\x06\x04"
-"\xdf\xe5T\x9f\xcc\x89\x00<\x9bg\x87\xece\xa0\xab\xcdoe\x90\x8a\x97\x90M\xc6"
-'!\x8f\xa8\x8d\xd8Y\x86C\xb5\x81\xb1\xb4\xd7_,"\na\xc1%\x8aG\x12\xb4\x9a\xf8'
-"z\x11\x1cJ\xa8\x8bu\xc4\x91\t;\xbe\x04\xcaE\xd9W\x8a\r\'\xcb#\x00\x00\x00a"
-"\x00\xaf2q\xf0\xe6\x0e\x9c\x99\xb3\x7f\x8b_\x04K\xcb\x8b\xc0\xd5>\xb2w\xfd"
-"\xcfd\xd8\x8f\xc0\xcf\xae\x1f\xc61\xdf\xf6)\xb2D\x96\xe2\xc6\xd4!\x94\x7fe|"
-"\xd8\xd4#\x1f\xb8.j\xc9\x1f\x94\rF\xc1i\xa2\xb7\x07\x0c\xa3\x93\xc14\xd8."
-"\x1eJ\x99\x1al\x96F\x07F+\xdc%)\x1b\x87\xf0\xbe\x05\x1d\xee\xb44\xb9\xe7"
-"\x99\x95\x00\x00\x001\x00\xb4s\x97KP\x10\xa3\x17\xb3\xa8G\xf1:\x14vR\xd18*"
-"\xcf\x12\x144\xc1\xa8TL)5\x80\xa08\xb8\xf0\xfaL\xc4\xc2\x85\xab\xdb\x87\x82"
-"\xba\xdc\xeb\xdb*\x00\x00\x001\x00\xcbJK\xd0@G\xe8ER\xf7\xc7\xaf\x0c mC\r"
-"\xb69\x94\xf9\xda\xa5\xe5\x03\x06v\x83$\xeb\x88\xa1U\xa2\xa8\xde\x12;wI\x92"
-"\x8a\xa9q\xd2\x02\x93\xff\x00\x00\x001\x00\xdc\x9fk\xd9\x98!V\x11\x8d\xe9_"
-"\x03\x9d\n\xd3\x93n\x13wA<\x85O\x00p\xfd\x05T\xff\xbc=\t\xbf\x83\xf6\x97"
-"\x7fd\x10\x91\x04\xfe\xa2gGTBk")
-
-publicDSA_openssh = ("ssh-dss AAAAB3NzaC1kc3MAAABBAIbwTOSsZ7Bl7U1KyMNqV13Tu7"
-"yRAtTr70PVI3QnfrPumf2UzCgpL1ljbKxSfAi05XvrE/1vfCFAsFYXRZLhQy0AAAAVAM965Akmo"
-"6eAi7K+k9qDR4TotFAXAAAAQADZlpTW964haQWS4vC063NGdldT6xpUGDcDRqbm90CoPEa2RmNO"
-"uOqi8lnbhYraEzypYH3K4Gzv/bxCBnKtHRUAAABAK+1osyWBS0+P90u/rAuko6chZ98thUSY2kL"
-"SHp6hLKyy2bjnT29h7haELE+XHfq2bM9fckDx2FLOSIJzy83VmQ== comment")
-
-privateDSA_openssh = """-----BEGIN DSA PRIVATE KEY-----
-MIH4AgEAAkEAhvBM5KxnsGXtTUrIw2pXXdO7vJEC1OvvQ9UjdCd+s+6Z/ZTMKCkv
-WWNsrFJ8CLTle+sT/W98IUCwVhdFkuFDLQIVAM965Akmo6eAi7K+k9qDR4TotFAX
-AkAA2ZaU1veuIWkFkuLwtOtzRnZXU+saVBg3A0am5vdAqDxGtkZjTrjqovJZ24WK
-2hM8qWB9yuBs7/28QgZyrR0VAkAr7WizJYFLT4/3S7+sC6SjpyFn3y2FRJjaQtIe
-nqEsrLLZuOdPb2HuFoQsT5cd+rZsz19yQPHYUs5IgnPLzdWZAhUAl1TqdmlAG/b4
-nnVchGiO9sML8MM=
------END DSA PRIVATE KEY-----"""
-
-publicDSA_lsh = ("{KDEwOnB1YmxpYy1rZXkoMzpkc2EoMTpwNjU6AIbwTOSsZ7Bl7U1KyMNqV"
-"13Tu7yRAtTr70PVI3QnfrPumf2UzCgpL1ljbKxSfAi05XvrE/1vfCFAsFYXRZLhQy0pKDE6cTIx"
-"OgDPeuQJJqOngIuyvpPag0eE6LRQFykoMTpnNjQ6ANmWlNb3riFpBZLi8LTrc0Z2V1PrGlQYNwN"
-"Gpub3QKg8RrZGY0646qLyWduFitoTPKlgfcrgbO/9vEIGcq0dFSkoMTp5NjQ6K+1osyWBS0+P90"
-"u/rAuko6chZ98thUSY2kLSHp6hLKyy2bjnT29h7haELE+XHfq2bM9fckDx2FLOSIJzy83VmSkpK"
-"Q==}")
-
-privateDSA_lsh = ("(11:private-key(3:dsa(1:p65:\x00\x86\xf0L\xe4\xacg\xb0e"
-"\xedMJ\xc8\xc3jW]\xd3\xbb\xbc\x91\x02\xd4\xeb\xefC\xd5#t'~\xb3\xee\x99\xfd"
-"\x94\xcc()/Ycl\xacR|\x08\xb4\xe5{\xeb\x13\xfdo|!@\xb0V\x17E\x92\xe1C-)(1:q2"
-"1:\x00\xcfz\xe4\t&\xa3\xa7\x80\x8b\xb2\xbe\x93\xda\x83G\x84\xe8\xb4P\x17)(1"
-":g64:\x00\xd9\x96\x94\xd6\xf7\xae!i\x05\x92\xe2\xf0\xb4\xebsFvWS\xeb\x1aT"
-"\x187\x03F\xa6\xe6\xf7@\xa8)".
- """
- addr = self.buildAddress()
- stringValue = stringFunction(addr)
- addressValue = stringFunction(addr.address)
- self.assertEqual(stringValue,
- "SSHTransportAddress(%s)" % addressValue)
-
-
- def buildAddress(self):
- """
- Create an arbitrary new C{SSHTransportAddress}. A new instance is
- created for each call, but always for the same address.
- """
- return SSHTransportAddress(IPv4Address("TCP", "127.0.0.1", 22))
-
-
- def buildDifferentAddress(self):
- """
- Like C{buildAddress}, but with a different fixed address.
- """
- return SSHTransportAddress(IPv4Address("TCP", "127.0.0.2", 22))
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_agent.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_agent.py
deleted file mode 100644
index 532a0e5..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_agent.py
+++ /dev/null
@@ -1,399 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.ssh.agent}.
-"""
-
-import struct
-
-from twisted.trial import unittest
-
-try:
- import OpenSSL
-except ImportError:
- iosim = None
-else:
- from twisted.test import iosim
-
-try:
- import Crypto.Cipher.DES3
-except ImportError:
- Crypto = None
-
-try:
- import pyasn1
-except ImportError:
- pyasn1 = None
-
-if Crypto and pyasn1:
- from twisted.conch.ssh import keys, agent
-else:
- keys = agent = None
-
-from twisted.conch.test import keydata
-from twisted.conch.error import ConchError, MissingKeyStoreError
-
-
-class StubFactory(object):
- """
- Mock factory that provides the keys attribute required by the
- SSHAgentServerProtocol
- """
- def __init__(self):
- self.keys = {}
-
-
-
-class AgentTestBase(unittest.TestCase):
- """
- Tests for SSHAgentServer/Client.
- """
- if iosim is None:
- skip = "iosim requires SSL, but SSL is not available"
- elif agent is None or keys is None:
- skip = "Cannot run without PyCrypto or PyASN1"
-
- def setUp(self):
- # wire up our client <-> server
- self.client, self.server, self.pump = iosim.connectedServerAndClient(
- agent.SSHAgentServer, agent.SSHAgentClient)
-
- # the server's end of the protocol is stateful and we store it on the
- # factory, for which we only need a mock
- self.server.factory = StubFactory()
-
- # pub/priv keys of each kind
- self.rsaPrivate = keys.Key.fromString(keydata.privateRSA_openssh)
- self.dsaPrivate = keys.Key.fromString(keydata.privateDSA_openssh)
-
- self.rsaPublic = keys.Key.fromString(keydata.publicRSA_openssh)
- self.dsaPublic = keys.Key.fromString(keydata.publicDSA_openssh)
-
-
-
-class TestServerProtocolContractWithFactory(AgentTestBase):
- """
- The server protocol is stateful and so uses its factory to track state
- across requests. This test asserts that the protocol raises if its factory
- doesn't provide the necessary storage for that state.
- """
- def test_factorySuppliesKeyStorageForServerProtocol(self):
- # need a message to send into the server
- msg = struct.pack('!LB',1, agent.AGENTC_REQUEST_IDENTITIES)
- del self.server.factory.__dict__['keys']
- self.assertRaises(MissingKeyStoreError,
- self.server.dataReceived, msg)
-
-
-
-class TestUnimplementedVersionOneServer(AgentTestBase):
- """
- Tests for methods with no-op implementations on the server. We need these
- for clients, such as openssh, that try v1 methods before going to v2.
-
- Because the client doesn't expose these operations with nice method names,
- we invoke sendRequest directly with an op code.
- """
-
- def test_agentc_REQUEST_RSA_IDENTITIES(self):
- """
- assert that we get the correct op code for an RSA identities request
- """
- d = self.client.sendRequest(agent.AGENTC_REQUEST_RSA_IDENTITIES, '')
- self.pump.flush()
- def _cb(packet):
- self.assertEqual(
- agent.AGENT_RSA_IDENTITIES_ANSWER, ord(packet[0]))
- return d.addCallback(_cb)
-
-
- def test_agentc_REMOVE_RSA_IDENTITY(self):
- """
- assert that we get the correct op code for an RSA remove identity request
- """
- d = self.client.sendRequest(agent.AGENTC_REMOVE_RSA_IDENTITY, '')
- self.pump.flush()
- return d.addCallback(self.assertEqual, '')
-
-
- def test_agentc_REMOVE_ALL_RSA_IDENTITIES(self):
- """
- assert that we get the correct op code for an RSA remove all identities
- request.
- """
- d = self.client.sendRequest(agent.AGENTC_REMOVE_ALL_RSA_IDENTITIES, '')
- self.pump.flush()
- return d.addCallback(self.assertEqual, '')
-
-
-
-if agent is not None:
- class CorruptServer(agent.SSHAgentServer):
- """
- A misbehaving server that returns bogus response op codes so that we can
- verify that our callbacks that deal with these op codes handle such
- miscreants.
- """
- def agentc_REQUEST_IDENTITIES(self, data):
- self.sendResponse(254, '')
-
-
- def agentc_SIGN_REQUEST(self, data):
- self.sendResponse(254, '')
-
-
-
-class TestClientWithBrokenServer(AgentTestBase):
- """
- verify error handling code in the client using a misbehaving server
- """
-
- def setUp(self):
- AgentTestBase.setUp(self)
- self.client, self.server, self.pump = iosim.connectedServerAndClient(
- CorruptServer, agent.SSHAgentClient)
- # the server's end of the protocol is stateful and we store it on the
- # factory, for which we only need a mock
- self.server.factory = StubFactory()
-
-
- def test_signDataCallbackErrorHandling(self):
- """
- Assert that L{SSHAgentClient.signData} raises a ConchError
- if we get a response from the server whose opcode doesn't match
- the protocol for data signing requests.
- """
- d = self.client.signData(self.rsaPublic.blob(), "John Hancock")
- self.pump.flush()
- return self.assertFailure(d, ConchError)
-
-
- def test_requestIdentitiesCallbackErrorHandling(self):
- """
- Assert that L{SSHAgentClient.requestIdentities} raises a ConchError
- if we get a response from the server whose opcode doesn't match
- the protocol for identity requests.
- """
- d = self.client.requestIdentities()
- self.pump.flush()
- return self.assertFailure(d, ConchError)
-
-
-
-class TestAgentKeyAddition(AgentTestBase):
- """
- Test adding different flavors of keys to an agent.
- """
-
- def test_addRSAIdentityNoComment(self):
- """
- L{SSHAgentClient.addIdentity} adds the private key it is called
- with to the SSH agent server to which it is connected, associating
- it with the comment it is called with.
-
- This test asserts that ommitting the comment produces an
- empty string for the comment on the server.
- """
- d = self.client.addIdentity(self.rsaPrivate.privateBlob())
- self.pump.flush()
- def _check(ignored):
- serverKey = self.server.factory.keys[self.rsaPrivate.blob()]
- self.assertEqual(self.rsaPrivate, serverKey[0])
- self.assertEqual('', serverKey[1])
- return d.addCallback(_check)
-
-
- def test_addDSAIdentityNoComment(self):
- """
- L{SSHAgentClient.addIdentity} adds the private key it is called
- with to the SSH agent server to which it is connected, associating
- it with the comment it is called with.
-
- This test asserts that ommitting the comment produces an
- empty string for the comment on the server.
- """
- d = self.client.addIdentity(self.dsaPrivate.privateBlob())
- self.pump.flush()
- def _check(ignored):
- serverKey = self.server.factory.keys[self.dsaPrivate.blob()]
- self.assertEqual(self.dsaPrivate, serverKey[0])
- self.assertEqual('', serverKey[1])
- return d.addCallback(_check)
-
-
- def test_addRSAIdentityWithComment(self):
- """
- L{SSHAgentClient.addIdentity} adds the private key it is called
- with to the SSH agent server to which it is connected, associating
- it with the comment it is called with.
-
- This test asserts that the server receives/stores the comment
- as sent by the client.
- """
- d = self.client.addIdentity(
- self.rsaPrivate.privateBlob(), comment='My special key')
- self.pump.flush()
- def _check(ignored):
- serverKey = self.server.factory.keys[self.rsaPrivate.blob()]
- self.assertEqual(self.rsaPrivate, serverKey[0])
- self.assertEqual('My special key', serverKey[1])
- return d.addCallback(_check)
-
-
- def test_addDSAIdentityWithComment(self):
- """
- L{SSHAgentClient.addIdentity} adds the private key it is called
- with to the SSH agent server to which it is connected, associating
- it with the comment it is called with.
-
- This test asserts that the server receives/stores the comment
- as sent by the client.
- """
- d = self.client.addIdentity(
- self.dsaPrivate.privateBlob(), comment='My special key')
- self.pump.flush()
- def _check(ignored):
- serverKey = self.server.factory.keys[self.dsaPrivate.blob()]
- self.assertEqual(self.dsaPrivate, serverKey[0])
- self.assertEqual('My special key', serverKey[1])
- return d.addCallback(_check)
-
-
-
-class TestAgentClientFailure(AgentTestBase):
- def test_agentFailure(self):
- """
- verify that the client raises ConchError on AGENT_FAILURE
- """
- d = self.client.sendRequest(254, '')
- self.pump.flush()
- return self.assertFailure(d, ConchError)
-
-
-
-class TestAgentIdentityRequests(AgentTestBase):
- """
- Test operations against a server with identities already loaded.
- """
-
- def setUp(self):
- AgentTestBase.setUp(self)
- self.server.factory.keys[self.dsaPrivate.blob()] = (
- self.dsaPrivate, 'a comment')
- self.server.factory.keys[self.rsaPrivate.blob()] = (
- self.rsaPrivate, 'another comment')
-
-
- def test_signDataRSA(self):
- """
- Sign data with an RSA private key and then verify it with the public
- key.
- """
- d = self.client.signData(self.rsaPublic.blob(), "John Hancock")
- self.pump.flush()
- def _check(sig):
- expected = self.rsaPrivate.sign("John Hancock")
- self.assertEqual(expected, sig)
- self.assertTrue(self.rsaPublic.verify(sig, "John Hancock"))
- return d.addCallback(_check)
-
-
- def test_signDataDSA(self):
- """
- Sign data with a DSA private key and then verify it with the public
- key.
- """
- d = self.client.signData(self.dsaPublic.blob(), "John Hancock")
- self.pump.flush()
- def _check(sig):
- # Cannot do this b/c DSA uses random numbers when signing
- # expected = self.dsaPrivate.sign("John Hancock")
- # self.assertEqual(expected, sig)
- self.assertTrue(self.dsaPublic.verify(sig, "John Hancock"))
- return d.addCallback(_check)
-
-
- def test_signDataRSAErrbackOnUnknownBlob(self):
- """
- Assert that we get an errback if we try to sign data using a key that
- wasn't added.
- """
- del self.server.factory.keys[self.rsaPublic.blob()]
- d = self.client.signData(self.rsaPublic.blob(), "John Hancock")
- self.pump.flush()
- return self.assertFailure(d, ConchError)
-
-
- def test_requestIdentities(self):
- """
- Assert that we get all of the keys/comments that we add when we issue a
- request for all identities.
- """
- d = self.client.requestIdentities()
- self.pump.flush()
- def _check(keyt):
- expected = {}
- expected[self.dsaPublic.blob()] = 'a comment'
- expected[self.rsaPublic.blob()] = 'another comment'
-
- received = {}
- for k in keyt:
- received[keys.Key.fromString(k[0], type='blob').blob()] = k[1]
- self.assertEqual(expected, received)
- return d.addCallback(_check)
-
-
-
-class TestAgentKeyRemoval(AgentTestBase):
- """
- Test support for removing keys in a remote server.
- """
-
- def setUp(self):
- AgentTestBase.setUp(self)
- self.server.factory.keys[self.dsaPrivate.blob()] = (
- self.dsaPrivate, 'a comment')
- self.server.factory.keys[self.rsaPrivate.blob()] = (
- self.rsaPrivate, 'another comment')
-
-
- def test_removeRSAIdentity(self):
- """
- Assert that we can remove an RSA identity.
- """
- # only need public key for this
- d = self.client.removeIdentity(self.rsaPrivate.blob())
- self.pump.flush()
-
- def _check(ignored):
- self.assertEqual(1, len(self.server.factory.keys))
- self.assertIn(self.dsaPrivate.blob(), self.server.factory.keys)
- self.assertNotIn(self.rsaPrivate.blob(), self.server.factory.keys)
- return d.addCallback(_check)
-
-
- def test_removeDSAIdentity(self):
- """
- Assert that we can remove a DSA identity.
- """
- # only need public key for this
- d = self.client.removeIdentity(self.dsaPrivate.blob())
- self.pump.flush()
-
- def _check(ignored):
- self.assertEqual(1, len(self.server.factory.keys))
- self.assertIn(self.rsaPrivate.blob(), self.server.factory.keys)
- return d.addCallback(_check)
-
-
- def test_removeAllIdentities(self):
- """
- Assert that we can remove all identities.
- """
- d = self.client.removeAllIdentities()
- self.pump.flush()
-
- def _check(ignored):
- self.assertEqual(0, len(self.server.factory.keys))
- return d.addCallback(_check)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_cftp.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_cftp.py
deleted file mode 100644
index 3647d6f..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_cftp.py
+++ /dev/null
@@ -1,992 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_cftp -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE file for details.
-
-"""
-Tests for L{twisted.conch.scripts.cftp}.
-"""
-
-import locale
-import time, sys, os, operator, getpass, struct
-from StringIO import StringIO
-
-from twisted.conch.test.test_ssh import Crypto, pyasn1
-
-_reason = None
-if Crypto and pyasn1:
- try:
- from twisted.conch import unix
- from twisted.conch.scripts import cftp
- from twisted.conch.scripts.cftp import SSHSession
- from twisted.conch.test.test_filetransfer import FileTransferForTestAvatar
- except ImportError as e:
- unix = None
- _reason = str(e)
- del e
-else:
- unix = None
-
-from twisted.python.fakepwd import UserDatabase
-from twisted.trial.unittest import TestCase
-from twisted.cred import portal
-from twisted.internet import reactor, protocol, interfaces, defer, error
-from twisted.internet.utils import getProcessOutputAndValue
-from twisted.python import log
-from twisted.conch import ls
-from twisted.test.proto_helpers import StringTransport
-from twisted.internet.task import Clock
-
-from twisted.conch.test import test_ssh, test_conch
-from twisted.conch.test.test_filetransfer import SFTPTestBase
-from twisted.conch.test.test_filetransfer import FileTransferTestAvatar
-from twisted.conch.test.test_conch import FakeStdio
-
-
-
-class SSHSessionTests(TestCase):
- """
- Tests for L{twisted.conch.scripts.cftp.SSHSession}.
- """
- def test_eofReceived(self):
- """
- L{twisted.conch.scripts.cftp.SSHSession.eofReceived} loses the write
- half of its stdio connection.
- """
- stdio = FakeStdio()
- channel = SSHSession()
- channel.stdio = stdio
- channel.eofReceived()
- self.assertTrue(stdio.writeConnLost)
-
-
-
-class ListingTests(TestCase):
- """
- Tests for L{lsLine}, the function which generates an entry for a file or
- directory in an SFTP I{ls} command's output.
- """
- if getattr(time, 'tzset', None) is None:
- skip = "Cannot test timestamp formatting code without time.tzset"
-
- def setUp(self):
- """
- Patch the L{ls} module's time function so the results of L{lsLine} are
- deterministic.
- """
- self.now = 123456789
- def fakeTime():
- return self.now
- self.patch(ls, 'time', fakeTime)
-
- # Make sure that the timezone ends up the same after these tests as
- # it was before.
- if 'TZ' in os.environ:
- self.addCleanup(operator.setitem, os.environ, 'TZ', os.environ['TZ'])
- self.addCleanup(time.tzset)
- else:
- def cleanup():
- # os.environ.pop is broken! Don't use it! Ever! Or die!
- try:
- del os.environ['TZ']
- except KeyError:
- pass
- time.tzset()
- self.addCleanup(cleanup)
-
-
- def _lsInTimezone(self, timezone, stat):
- """
- Call L{ls.lsLine} after setting the timezone to C{timezone} and return
- the result.
- """
- # Set the timezone to a well-known value so the timestamps are
- # predictable.
- os.environ['TZ'] = timezone
- time.tzset()
- return ls.lsLine('foo', stat)
-
-
- def test_oldFile(self):
- """
- A file with an mtime six months (approximately) or more in the past has
- a listing including a low-resolution timestamp.
- """
- # Go with 7 months. That's more than 6 months.
- then = self.now - (60 * 60 * 24 * 31 * 7)
- stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))
-
- self.assertEqual(
- self._lsInTimezone('America/New_York', stat),
- '!--------- 0 0 0 0 Apr 26 1973 foo')
- self.assertEqual(
- self._lsInTimezone('Pacific/Auckland', stat),
- '!--------- 0 0 0 0 Apr 27 1973 foo')
-
-
- def test_oldSingleDigitDayOfMonth(self):
- """
- A file with a high-resolution timestamp which falls on a day of the
- month which can be represented by one decimal digit is formatted with
- one padding 0 to preserve the columns which come after it.
- """
- # A point about 7 months in the past, tweaked to fall on the first of a
- # month so we test the case we want to test.
- then = self.now - (60 * 60 * 24 * 31 * 7) + (60 * 60 * 24 * 5)
- stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))
-
- self.assertEqual(
- self._lsInTimezone('America/New_York', stat),
- '!--------- 0 0 0 0 May 01 1973 foo')
- self.assertEqual(
- self._lsInTimezone('Pacific/Auckland', stat),
- '!--------- 0 0 0 0 May 02 1973 foo')
-
-
- def test_newFile(self):
- """
- A file with an mtime fewer than six months (approximately) in the past
- has a listing including a high-resolution timestamp excluding the year.
- """
- # A point about three months in the past.
- then = self.now - (60 * 60 * 24 * 31 * 3)
- stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))
-
- self.assertEqual(
- self._lsInTimezone('America/New_York', stat),
- '!--------- 0 0 0 0 Aug 28 17:33 foo')
- self.assertEqual(
- self._lsInTimezone('Pacific/Auckland', stat),
- '!--------- 0 0 0 0 Aug 29 09:33 foo')
-
-
- def test_localeIndependent(self):
- """
- The month name in the date is locale independent.
- """
- # A point about three months in the past.
- then = self.now - (60 * 60 * 24 * 31 * 3)
- stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))
-
- # Fake that we're in a language where August is not Aug (e.g.: Spanish)
- currentLocale = locale.getlocale()
- locale.setlocale(locale.LC_ALL, "es_AR.UTF8")
- self.addCleanup(locale.setlocale, locale.LC_ALL, currentLocale)
-
- self.assertEqual(
- self._lsInTimezone('America/New_York', stat),
- '!--------- 0 0 0 0 Aug 28 17:33 foo')
- self.assertEqual(
- self._lsInTimezone('Pacific/Auckland', stat),
- '!--------- 0 0 0 0 Aug 29 09:33 foo')
-
- # if alternate locale is not available, the previous test will be
- # skipped, please install this locale for it to run
- currentLocale = locale.getlocale()
- try:
- try:
- locale.setlocale(locale.LC_ALL, "es_AR.UTF8")
- except locale.Error:
- test_localeIndependent.skip = "The es_AR.UTF8 locale is not installed."
- finally:
- locale.setlocale(locale.LC_ALL, currentLocale)
-
-
- def test_newSingleDigitDayOfMonth(self):
- """
- A file with a high-resolution timestamp which falls on a day of the
- month which can be represented by one decimal digit is formatted with
- one padding 0 to preserve the columns which come after it.
- """
- # A point about three months in the past, tweaked to fall on the first
- # of a month so we test the case we want to test.
- then = self.now - (60 * 60 * 24 * 31 * 3) + (60 * 60 * 24 * 4)
- stat = os.stat_result((0, 0, 0, 0, 0, 0, 0, 0, then, 0))
-
- self.assertEqual(
- self._lsInTimezone('America/New_York', stat),
- '!--------- 0 0 0 0 Sep 01 17:33 foo')
- self.assertEqual(
- self._lsInTimezone('Pacific/Auckland', stat),
- '!--------- 0 0 0 0 Sep 02 09:33 foo')
-
-
-
-class StdioClientTests(TestCase):
- """
- Tests for L{cftp.StdioClient}.
- """
- def setUp(self):
- """
- Create a L{cftp.StdioClient} hooked up to dummy transport and a fake
- user database.
- """
- class Connection:
- pass
-
- conn = Connection()
- conn.transport = StringTransport()
- conn.transport.localClosed = False
-
- self.client = cftp.StdioClient(conn)
- self.database = self.client._pwd = UserDatabase()
-
- # Intentionally bypassing makeConnection - that triggers some code
- # which uses features not provided by our dumb Connection fake.
- self.client.transport = StringTransport()
-
-
- def test_exec(self):
- """
- The I{exec} command runs its arguments locally in a child process
- using the user's shell.
- """
- self.database.addUser(
- getpass.getuser(), 'secret', os.getuid(), 1234, 'foo', 'bar',
- sys.executable)
-
- d = self.client._dispatchCommand("exec print 1 + 2")
- d.addCallback(self.assertEqual, "3\n")
- return d
-
-
- def test_execWithoutShell(self):
- """
- If the local user has no shell, the I{exec} command runs its arguments
- using I{/bin/sh}.
- """
- self.database.addUser(
- getpass.getuser(), 'secret', os.getuid(), 1234, 'foo', 'bar', '')
-
- d = self.client._dispatchCommand("exec echo hello")
- d.addCallback(self.assertEqual, "hello\n")
- return d
-
-
- def test_bang(self):
- """
- The I{exec} command is run for lines which start with C{"!"}.
- """
- self.database.addUser(
- getpass.getuser(), 'secret', os.getuid(), 1234, 'foo', 'bar',
- '/bin/sh')
-
- d = self.client._dispatchCommand("!echo hello")
- d.addCallback(self.assertEqual, "hello\n")
- return d
-
-
- def setKnownConsoleSize(self, width, height):
- """
- For the duration of this test, patch C{cftp}'s C{fcntl} module to return
- a fixed width and height.
-
- @param width: the width in characters
- @type width: C{int}
- @param height: the height in characters
- @type height: C{int}
- """
- import tty # local import to avoid win32 issues
- class FakeFcntl(object):
- def ioctl(self, fd, opt, mutate):
- if opt != tty.TIOCGWINSZ:
- self.fail("Only window-size queries supported.")
- return struct.pack("4H", height, width, 0, 0)
- self.patch(cftp, "fcntl", FakeFcntl())
-
-
- def test_progressReporting(self):
- """
- L{StdioClient._printProgressBar} prints a progress description,
- including percent done, amount transferred, transfer rate, and time
- remaining, all based the given start time, the given L{FileWrapper}'s
- progress information and the reactor's current time.
- """
- # Use a short, known console width because this simple test doesn't need
- # to test the console padding.
- self.setKnownConsoleSize(10, 34)
- clock = self.client.reactor = Clock()
- wrapped = StringIO("x")
- wrapped.name = "sample"
- wrapper = cftp.FileWrapper(wrapped)
- wrapper.size = 1024 * 10
- startTime = clock.seconds()
- clock.advance(2.0)
- wrapper.total += 4096
- self.client._printProgressBar(wrapper, startTime)
- self.assertEqual(self.client.transport.value(),
- "\rsample 40% 4.0kB 2.0kBps 00:03 ")
-
-
- def test_reportNoProgress(self):
- """
- L{StdioClient._printProgressBar} prints a progress description that
- indicates 0 bytes transferred if no bytes have been transferred and no
- time has passed.
- """
- self.setKnownConsoleSize(10, 34)
- clock = self.client.reactor = Clock()
- wrapped = StringIO("x")
- wrapped.name = "sample"
- wrapper = cftp.FileWrapper(wrapped)
- startTime = clock.seconds()
- self.client._printProgressBar(wrapper, startTime)
- self.assertEqual(self.client.transport.value(),
- "\rsample 0% 0.0B 0.0Bps 00:00 ")
-
-
-
-class FileTransferTestRealm:
- def __init__(self, testDir):
- self.testDir = testDir
-
- def requestAvatar(self, avatarID, mind, *interfaces):
- a = FileTransferTestAvatar(self.testDir)
- return interfaces[0], a, lambda: None
-
-
-class SFTPTestProcess(protocol.ProcessProtocol):
- """
- Protocol for testing cftp. Provides an interface between Python (where all
- the tests are) and the cftp client process (which does the work that is
- being tested).
- """
-
- def __init__(self, onOutReceived):
- """
- @param onOutReceived: A L{Deferred} to be fired as soon as data is
- received from stdout.
- """
- self.clearBuffer()
- self.onOutReceived = onOutReceived
- self.onProcessEnd = None
- self._expectingCommand = None
- self._processEnded = False
-
- def clearBuffer(self):
- """
- Clear any buffered data received from stdout. Should be private.
- """
- self.buffer = ''
- self._linesReceived = []
- self._lineBuffer = ''
-
- def outReceived(self, data):
- """
- Called by Twisted when the cftp client prints data to stdout.
- """
- log.msg('got %s' % data)
- lines = (self._lineBuffer + data).split('\n')
- self._lineBuffer = lines.pop(-1)
- self._linesReceived.extend(lines)
- # XXX - not strictly correct.
- # We really want onOutReceived to fire after the first 'cftp>' prompt
- # has been received. (See use in TestOurServerCmdLineClient.setUp)
- if self.onOutReceived is not None:
- d, self.onOutReceived = self.onOutReceived, None
- d.callback(data)
- self.buffer += data
- self._checkForCommand()
-
- def _checkForCommand(self):
- prompt = 'cftp> '
- if self._expectingCommand and self._lineBuffer == prompt:
- buf = '\n'.join(self._linesReceived)
- if buf.startswith(prompt):
- buf = buf[len(prompt):]
- self.clearBuffer()
- d, self._expectingCommand = self._expectingCommand, None
- d.callback(buf)
-
- def errReceived(self, data):
- """
- Called by Twisted when the cftp client prints data to stderr.
- """
- log.msg('err: %s' % data)
-
- def getBuffer(self):
- """
- Return the contents of the buffer of data received from stdout.
- """
- return self.buffer
-
- def runCommand(self, command):
- """
- Issue the given command via the cftp client. Return a C{Deferred} that
- fires when the server returns a result. Note that the C{Deferred} will
- callback even if the server returns some kind of error.
-
- @param command: A string containing an sftp command.
-
- @return: A C{Deferred} that fires when the sftp server returns a
- result. The payload is the server's response string.
- """
- self._expectingCommand = defer.Deferred()
- self.clearBuffer()
- self.transport.write(command + '\n')
- return self._expectingCommand
-
- def runScript(self, commands):
- """
- Run each command in sequence and return a Deferred that fires when all
- commands are completed.
-
- @param commands: A list of strings containing sftp commands.
-
- @return: A C{Deferred} that fires when all commands are completed. The
- payload is a list of response strings from the server, in the same
- order as the commands.
- """
- sem = defer.DeferredSemaphore(1)
- dl = [sem.run(self.runCommand, command) for command in commands]
- return defer.gatherResults(dl)
-
- def killProcess(self):
- """
- Kill the process if it is still running.
-
- If the process is still running, sends a KILL signal to the transport
- and returns a C{Deferred} which fires when L{processEnded} is called.
-
- @return: a C{Deferred}.
- """
- if self._processEnded:
- return defer.succeed(None)
- self.onProcessEnd = defer.Deferred()
- self.transport.signalProcess('KILL')
- return self.onProcessEnd
-
- def processEnded(self, reason):
- """
- Called by Twisted when the cftp client process ends.
- """
- self._processEnded = True
- if self.onProcessEnd:
- d, self.onProcessEnd = self.onProcessEnd, None
- d.callback(None)
-
-
-class CFTPClientTestBase(SFTPTestBase):
- def setUp(self):
- f = open('dsa_test.pub','w')
- f.write(test_ssh.publicDSA_openssh)
- f.close()
- f = open('dsa_test','w')
- f.write(test_ssh.privateDSA_openssh)
- f.close()
- os.chmod('dsa_test', 33152)
- f = open('kh_test','w')
- f.write('127.0.0.1 ' + test_ssh.publicRSA_openssh)
- f.close()
- return SFTPTestBase.setUp(self)
-
- def startServer(self):
- realm = FileTransferTestRealm(self.testDir)
- p = portal.Portal(realm)
- p.registerChecker(test_ssh.ConchTestPublicKeyChecker())
- fac = test_ssh.ConchTestServerFactory()
- fac.portal = p
- self.server = reactor.listenTCP(0, fac, interface="127.0.0.1")
-
- def stopServer(self):
- if not hasattr(self.server.factory, 'proto'):
- return self._cbStopServer(None)
- self.server.factory.proto.expectedLoseConnection = 1
- d = defer.maybeDeferred(
- self.server.factory.proto.transport.loseConnection)
- d.addCallback(self._cbStopServer)
- return d
-
- def _cbStopServer(self, ignored):
- return defer.maybeDeferred(self.server.stopListening)
-
- def tearDown(self):
- for f in ['dsa_test.pub', 'dsa_test', 'kh_test']:
- try:
- os.remove(f)
- except:
- pass
- return SFTPTestBase.tearDown(self)
-
-
-
-class TestOurServerCmdLineClient(CFTPClientTestBase):
-
- def setUp(self):
- CFTPClientTestBase.setUp(self)
-
- self.startServer()
- cmds = ('-p %i -l testuser '
- '--known-hosts kh_test '
- '--user-authentications publickey '
- '--host-key-algorithms ssh-rsa '
- '-i dsa_test '
- '-a '
- '-v '
- '127.0.0.1')
- port = self.server.getHost().port
- cmds = test_conch._makeArgs((cmds % port).split(), mod='cftp')
- log.msg('running %s %s' % (sys.executable, cmds))
- d = defer.Deferred()
- self.processProtocol = SFTPTestProcess(d)
- d.addCallback(lambda _: self.processProtocol.clearBuffer())
- env = os.environ.copy()
- env['PYTHONPATH'] = os.pathsep.join(sys.path)
- reactor.spawnProcess(self.processProtocol, sys.executable, cmds,
- env=env)
- return d
-
- def tearDown(self):
- d = self.stopServer()
- d.addCallback(lambda _: self.processProtocol.killProcess())
- return d
-
- def _killProcess(self, ignored):
- try:
- self.processProtocol.transport.signalProcess('KILL')
- except error.ProcessExitedAlready:
- pass
-
- def runCommand(self, command):
- """
- Run the given command with the cftp client. Return a C{Deferred} that
- fires when the command is complete. Payload is the server's output for
- that command.
- """
- return self.processProtocol.runCommand(command)
-
- def runScript(self, *commands):
- """
- Run the given commands with the cftp client. Returns a C{Deferred}
- that fires when the commands are all complete. The C{Deferred}'s
- payload is a list of output for each command.
- """
- return self.processProtocol.runScript(commands)
-
- def testCdPwd(self):
- """
- Test that 'pwd' reports the current remote directory, that 'lpwd'
- reports the current local directory, and that changing to a
- subdirectory then changing to its parent leaves you in the original
- remote directory.
- """
- # XXX - not actually a unit test, see docstring.
- homeDir = os.path.join(os.getcwd(), self.testDir)
- d = self.runScript('pwd', 'lpwd', 'cd testDirectory', 'cd ..', 'pwd')
- d.addCallback(lambda xs: xs[:3] + xs[4:])
- d.addCallback(self.assertEqual,
- [homeDir, os.getcwd(), '', homeDir])
- return d
-
- def testChAttrs(self):
- """
- Check that 'ls -l' output includes the access permissions and that
- this output changes appropriately with 'chmod'.
- """
- def _check(results):
- self.flushLoggedErrors()
- self.assertTrue(results[0].startswith('-rw-r--r--'))
- self.assertEqual(results[1], '')
- self.assertTrue(results[2].startswith('----------'), results[2])
- self.assertEqual(results[3], '')
-
- d = self.runScript('ls -l testfile1', 'chmod 0 testfile1',
- 'ls -l testfile1', 'chmod 644 testfile1')
- return d.addCallback(_check)
- # XXX test chgrp/own
-
-
- def testList(self):
- """
- Check 'ls' works as expected. Checks for wildcards, hidden files,
- listing directories and listing empty directories.
- """
- def _check(results):
- self.assertEqual(results[0], ['testDirectory', 'testRemoveFile',
- 'testRenameFile', 'testfile1'])
- self.assertEqual(results[1], ['testDirectory', 'testRemoveFile',
- 'testRenameFile', 'testfile1'])
- self.assertEqual(results[2], ['testRemoveFile', 'testRenameFile'])
- self.assertEqual(results[3], ['.testHiddenFile', 'testRemoveFile',
- 'testRenameFile'])
- self.assertEqual(results[4], [''])
- d = self.runScript('ls', 'ls ../' + os.path.basename(self.testDir),
- 'ls *File', 'ls -a *File', 'ls -l testDirectory')
- d.addCallback(lambda xs: [x.split('\n') for x in xs])
- return d.addCallback(_check)
-
-
- def testHelp(self):
- """
- Check that running the '?' command returns help.
- """
- d = self.runCommand('?')
- d.addCallback(self.assertEqual,
- cftp.StdioClient(None).cmd_HELP('').strip())
- return d
-
- def assertFilesEqual(self, name1, name2, msg=None):
- """
- Assert that the files at C{name1} and C{name2} contain exactly the
- same data.
- """
- f1 = file(name1).read()
- f2 = file(name2).read()
- self.assertEqual(f1, f2, msg)
-
-
- def testGet(self):
- """
- Test that 'get' saves the remote file to the correct local location,
- that the output of 'get' is correct and that 'rm' actually removes
- the file.
- """
- # XXX - not actually a unit test
- expectedOutput = ("Transferred %s/%s/testfile1 to %s/test file2"
- % (os.getcwd(), self.testDir, self.testDir))
- def _checkGet(result):
- self.assertTrue(result.endswith(expectedOutput))
- self.assertFilesEqual(self.testDir + '/testfile1',
- self.testDir + '/test file2',
- "get failed")
- return self.runCommand('rm "test file2"')
-
- d = self.runCommand('get testfile1 "%s/test file2"' % (self.testDir,))
- d.addCallback(_checkGet)
- d.addCallback(lambda _: self.assertFalse(
- os.path.exists(self.testDir + '/test file2')))
- return d
-
-
- def testWildcardGet(self):
- """
- Test that 'get' works correctly when given wildcard parameters.
- """
- def _check(ignored):
- self.assertFilesEqual(self.testDir + '/testRemoveFile',
- 'testRemoveFile',
- 'testRemoveFile get failed')
- self.assertFilesEqual(self.testDir + '/testRenameFile',
- 'testRenameFile',
- 'testRenameFile get failed')
-
- d = self.runCommand('get testR*')
- return d.addCallback(_check)
-
-
- def testPut(self):
- """
- Check that 'put' uploads files correctly and that they can be
- successfully removed. Also check the output of the put command.
- """
- # XXX - not actually a unit test
- expectedOutput = ('Transferred %s/testfile1 to %s/%s/test"file2'
- % (self.testDir, os.getcwd(), self.testDir))
- def _checkPut(result):
- self.assertFilesEqual(self.testDir + '/testfile1',
- self.testDir + '/test"file2')
- self.assertTrue(result.endswith(expectedOutput))
- return self.runCommand('rm "test\\"file2"')
-
- d = self.runCommand('put %s/testfile1 "test\\"file2"'
- % (self.testDir,))
- d.addCallback(_checkPut)
- d.addCallback(lambda _: self.assertFalse(
- os.path.exists(self.testDir + '/test"file2')))
- return d
-
-
- def test_putOverLongerFile(self):
- """
- Check that 'put' uploads files correctly when overwriting a longer
- file.
- """
- # XXX - not actually a unit test
- f = file(os.path.join(self.testDir, 'shorterFile'), 'w')
- f.write("a")
- f.close()
- f = file(os.path.join(self.testDir, 'longerFile'), 'w')
- f.write("bb")
- f.close()
- def _checkPut(result):
- self.assertFilesEqual(self.testDir + '/shorterFile',
- self.testDir + '/longerFile')
-
- d = self.runCommand('put %s/shorterFile longerFile'
- % (self.testDir,))
- d.addCallback(_checkPut)
- return d
-
-
- def test_putMultipleOverLongerFile(self):
- """
- Check that 'put' uploads files correctly when overwriting a longer
- file and you use a wildcard to specify the files to upload.
- """
- # XXX - not actually a unit test
- os.mkdir(os.path.join(self.testDir, 'dir'))
- f = file(os.path.join(self.testDir, 'dir', 'file'), 'w')
- f.write("a")
- f.close()
- f = file(os.path.join(self.testDir, 'file'), 'w')
- f.write("bb")
- f.close()
- def _checkPut(result):
- self.assertFilesEqual(self.testDir + '/dir/file',
- self.testDir + '/file')
-
- d = self.runCommand('put %s/dir/*'
- % (self.testDir,))
- d.addCallback(_checkPut)
- return d
-
-
- def testWildcardPut(self):
- """
- What happens if you issue a 'put' command and include a wildcard (i.e.
- '*') in parameter? Check that all files matching the wildcard are
- uploaded to the correct directory.
- """
- def check(results):
- self.assertEqual(results[0], '')
- self.assertEqual(results[2], '')
- self.assertFilesEqual(self.testDir + '/testRemoveFile',
- self.testDir + '/../testRemoveFile',
- 'testRemoveFile get failed')
- self.assertFilesEqual(self.testDir + '/testRenameFile',
- self.testDir + '/../testRenameFile',
- 'testRenameFile get failed')
-
- d = self.runScript('cd ..',
- 'put %s/testR*' % (self.testDir,),
- 'cd %s' % os.path.basename(self.testDir))
- d.addCallback(check)
- return d
-
-
- def testLink(self):
- """
- Test that 'ln' creates a file which appears as a link in the output of
- 'ls'. Check that removing the new file succeeds without output.
- """
- def _check(results):
- self.flushLoggedErrors()
- self.assertEqual(results[0], '')
- self.assertTrue(results[1].startswith('l'), 'link failed')
- return self.runCommand('rm testLink')
-
- d = self.runScript('ln testLink testfile1', 'ls -l testLink')
- d.addCallback(_check)
- d.addCallback(self.assertEqual, '')
- return d
-
-
- def testRemoteDirectory(self):
- """
- Test that we can create and remove directories with the cftp client.
- """
- def _check(results):
- self.assertEqual(results[0], '')
- self.assertTrue(results[1].startswith('d'))
- return self.runCommand('rmdir testMakeDirectory')
-
- d = self.runScript('mkdir testMakeDirectory',
- 'ls -l testMakeDirector?')
- d.addCallback(_check)
- d.addCallback(self.assertEqual, '')
- return d
-
-
- def test_existingRemoteDirectory(self):
- """
- Test that a C{mkdir} on an existing directory fails with the
- appropriate error, and doesn't log an useless error server side.
- """
- def _check(results):
- self.assertEqual(results[0], '')
- self.assertEqual(results[1],
- 'remote error 11: mkdir failed')
-
- d = self.runScript('mkdir testMakeDirectory',
- 'mkdir testMakeDirectory')
- d.addCallback(_check)
- return d
-
-
- def testLocalDirectory(self):
- """
- Test that we can create a directory locally and remove it with the
- cftp client. This test works because the 'remote' server is running
- out of a local directory.
- """
- d = self.runCommand('lmkdir %s/testLocalDirectory' % (self.testDir,))
- d.addCallback(self.assertEqual, '')
- d.addCallback(lambda _: self.runCommand('rmdir testLocalDirectory'))
- d.addCallback(self.assertEqual, '')
- return d
-
-
- def testRename(self):
- """
- Test that we can rename a file.
- """
- def _check(results):
- self.assertEqual(results[0], '')
- self.assertEqual(results[1], 'testfile2')
- return self.runCommand('rename testfile2 testfile1')
-
- d = self.runScript('rename testfile1 testfile2', 'ls testfile?')
- d.addCallback(_check)
- d.addCallback(self.assertEqual, '')
- return d
-
-
-
-class TestOurServerBatchFile(CFTPClientTestBase):
- def setUp(self):
- CFTPClientTestBase.setUp(self)
- self.startServer()
-
- def tearDown(self):
- CFTPClientTestBase.tearDown(self)
- return self.stopServer()
-
- def _getBatchOutput(self, f):
- fn = self.mktemp()
- open(fn, 'w').write(f)
- port = self.server.getHost().port
- cmds = ('-p %i -l testuser '
- '--known-hosts kh_test '
- '--user-authentications publickey '
- '--host-key-algorithms ssh-rsa '
- '-i dsa_test '
- '-a '
- '-v -b %s 127.0.0.1') % (port, fn)
- cmds = test_conch._makeArgs(cmds.split(), mod='cftp')[1:]
- log.msg('running %s %s' % (sys.executable, cmds))
- env = os.environ.copy()
- env['PYTHONPATH'] = os.pathsep.join(sys.path)
-
- self.server.factory.expectedLoseConnection = 1
-
- d = getProcessOutputAndValue(sys.executable, cmds, env=env)
-
- def _cleanup(res):
- os.remove(fn)
- return res
-
- d.addCallback(lambda res: res[0])
- d.addBoth(_cleanup)
-
- return d
-
- def testBatchFile(self):
- """Test whether batch file function of cftp ('cftp -b batchfile').
- This works by treating the file as a list of commands to be run.
- """
- cmds = """pwd
-ls
-exit
-"""
- def _cbCheckResult(res):
- res = res.split('\n')
- log.msg('RES %s' % str(res))
- self.assertIn(self.testDir, res[1])
- self.assertEqual(res[3:-2], ['testDirectory', 'testRemoveFile',
- 'testRenameFile', 'testfile1'])
-
- d = self._getBatchOutput(cmds)
- d.addCallback(_cbCheckResult)
- return d
-
- def testError(self):
- """Test that an error in the batch file stops running the batch.
- """
- cmds = """chown 0 missingFile
-pwd
-exit
-"""
- def _cbCheckResult(res):
- self.assertNotIn(self.testDir, res)
-
- d = self._getBatchOutput(cmds)
- d.addCallback(_cbCheckResult)
- return d
-
- def testIgnoredError(self):
- """Test that a minus sign '-' at the front of a line ignores
- any errors.
- """
- cmds = """-chown 0 missingFile
-pwd
-exit
-"""
- def _cbCheckResult(res):
- self.assertIn(self.testDir, res)
-
- d = self._getBatchOutput(cmds)
- d.addCallback(_cbCheckResult)
- return d
-
-
-
-class TestOurServerSftpClient(CFTPClientTestBase):
- """
- Test the sftp server against sftp command line client.
- """
-
- def setUp(self):
- CFTPClientTestBase.setUp(self)
- return self.startServer()
-
-
- def tearDown(self):
- return self.stopServer()
-
-
- def test_extendedAttributes(self):
- """
- Test the return of extended attributes by the server: the sftp client
- should ignore them, but still be able to parse the response correctly.
-
- This test is mainly here to check that
- L{filetransfer.FILEXFER_ATTR_EXTENDED} has the correct value.
- """
- fn = self.mktemp()
- open(fn, 'w').write("ls .\nexit")
- port = self.server.getHost().port
-
- oldGetAttr = FileTransferForTestAvatar._getAttrs
- def _getAttrs(self, s):
- attrs = oldGetAttr(self, s)
- attrs["ext_foo"] = "bar"
- return attrs
-
- self.patch(FileTransferForTestAvatar, "_getAttrs", _getAttrs)
-
- self.server.factory.expectedLoseConnection = True
- cmds = ('-o', 'IdentityFile=dsa_test',
- '-o', 'UserKnownHostsFile=kh_test',
- '-o', 'HostKeyAlgorithms=ssh-rsa',
- '-o', 'Port=%i' % (port,), '-b', fn, 'testuser@127.0.0.1')
- d = getProcessOutputAndValue("sftp", cmds)
- def check(result):
- self.assertEqual(result[2], 0)
- for i in ['testDirectory', 'testRemoveFile',
- 'testRenameFile', 'testfile1']:
- self.assertIn(i, result[0])
- return d.addCallback(check)
-
-
-
-if unix is None or Crypto is None or pyasn1 is None or interfaces.IReactorProcess(reactor, None) is None:
- if _reason is None:
- _reason = "don't run w/o spawnProcess or PyCrypto or pyasn1"
- TestOurServerCmdLineClient.skip = _reason
- TestOurServerBatchFile.skip = _reason
- TestOurServerSftpClient.skip = _reason
- StdioClientTests.skip = _reason
- SSHSessionTests.skip = _reason
-else:
- from twisted.python.procutils import which
- if not which('sftp'):
- TestOurServerSftpClient.skip = "no sftp command-line client available"
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_channel.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_channel.py
deleted file mode 100644
index a46596d..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_channel.py
+++ /dev/null
@@ -1,279 +0,0 @@
-# Copyright (C) 2007-2008 Twisted Matrix Laboratories
-# See LICENSE for details
-
-"""
-Test ssh/channel.py.
-"""
-from twisted.conch.ssh import channel
-from twisted.trial import unittest
-
-
-class MockTransport(object):
- """
- A mock Transport. All we use is the getPeer() and getHost() methods.
- Channels implement the ITransport interface, and their getPeer() and
- getHost() methods return ('SSH', ) so
- we need to implement these methods so they have something to draw
- from.
- """
- def getPeer(self):
- return ('MockPeer',)
-
- def getHost(self):
- return ('MockHost',)
-
-
-class MockConnection(object):
- """
- A mock for twisted.conch.ssh.connection.SSHConnection. Record the data
- that channels send, and when they try to close the connection.
-
- @ivar data: a C{dict} mapping channel id #s to lists of data sent by that
- channel.
- @ivar extData: a C{dict} mapping channel id #s to lists of 2-tuples
- (extended data type, data) sent by that channel.
- @ivar closes: a C{dict} mapping channel id #s to True if that channel sent
- a close message.
- """
- transport = MockTransport()
-
- def __init__(self):
- self.data = {}
- self.extData = {}
- self.closes = {}
-
- def logPrefix(self):
- """
- Return our logging prefix.
- """
- return "MockConnection"
-
- def sendData(self, channel, data):
- """
- Record the sent data.
- """
- self.data.setdefault(channel, []).append(data)
-
- def sendExtendedData(self, channel, type, data):
- """
- Record the sent extended data.
- """
- self.extData.setdefault(channel, []).append((type, data))
-
- def sendClose(self, channel):
- """
- Record that the channel sent a close message.
- """
- self.closes[channel] = True
-
-
-class ChannelTestCase(unittest.TestCase):
-
- def setUp(self):
- """
- Initialize the channel. remoteMaxPacket is 10 so that data is able
- to be sent (the default of 0 means no data is sent because no packets
- are made).
- """
- self.conn = MockConnection()
- self.channel = channel.SSHChannel(conn=self.conn,
- remoteMaxPacket=10)
- self.channel.name = 'channel'
-
- def test_init(self):
- """
- Test that SSHChannel initializes correctly. localWindowSize defaults
- to 131072 (2**17) and localMaxPacket to 32768 (2**15) as reasonable
- defaults (what OpenSSH uses for those variables).
-
- The values in the second set of assertions are meaningless; they serve
- only to verify that the instance variables are assigned in the correct
- order.
- """
- c = channel.SSHChannel(conn=self.conn)
- self.assertEqual(c.localWindowSize, 131072)
- self.assertEqual(c.localWindowLeft, 131072)
- self.assertEqual(c.localMaxPacket, 32768)
- self.assertEqual(c.remoteWindowLeft, 0)
- self.assertEqual(c.remoteMaxPacket, 0)
- self.assertEqual(c.conn, self.conn)
- self.assertEqual(c.data, None)
- self.assertEqual(c.avatar, None)
-
- c2 = channel.SSHChannel(1, 2, 3, 4, 5, 6, 7)
- self.assertEqual(c2.localWindowSize, 1)
- self.assertEqual(c2.localWindowLeft, 1)
- self.assertEqual(c2.localMaxPacket, 2)
- self.assertEqual(c2.remoteWindowLeft, 3)
- self.assertEqual(c2.remoteMaxPacket, 4)
- self.assertEqual(c2.conn, 5)
- self.assertEqual(c2.data, 6)
- self.assertEqual(c2.avatar, 7)
-
- def test_str(self):
- """
- Test that str(SSHChannel) works gives the channel name and local and
- remote windows at a glance..
- """
- self.assertEqual(str(self.channel), '')
-
- def test_logPrefix(self):
- """
- Test that SSHChannel.logPrefix gives the name of the channel, the
- local channel ID and the underlying connection.
- """
- self.assertEqual(self.channel.logPrefix(), 'SSHChannel channel '
- '(unknown) on MockConnection')
-
- def test_addWindowBytes(self):
- """
- Test that addWindowBytes adds bytes to the window and resumes writing
- if it was paused.
- """
- cb = [False]
- def stubStartWriting():
- cb[0] = True
- self.channel.startWriting = stubStartWriting
- self.channel.write('test')
- self.channel.writeExtended(1, 'test')
- self.channel.addWindowBytes(50)
- self.assertEqual(self.channel.remoteWindowLeft, 50 - 4 - 4)
- self.assertTrue(self.channel.areWriting)
- self.assertTrue(cb[0])
- self.assertEqual(self.channel.buf, '')
- self.assertEqual(self.conn.data[self.channel], ['test'])
- self.assertEqual(self.channel.extBuf, [])
- self.assertEqual(self.conn.extData[self.channel], [(1, 'test')])
-
- cb[0] = False
- self.channel.addWindowBytes(20)
- self.assertFalse(cb[0])
-
- self.channel.write('a'*80)
- self.channel.loseConnection()
- self.channel.addWindowBytes(20)
- self.assertFalse(cb[0])
-
- def test_requestReceived(self):
- """
- Test that requestReceived handles requests by dispatching them to
- request_* methods.
- """
- self.channel.request_test_method = lambda data: data == ''
- self.assertTrue(self.channel.requestReceived('test-method', ''))
- self.assertFalse(self.channel.requestReceived('test-method', 'a'))
- self.assertFalse(self.channel.requestReceived('bad-method', ''))
-
- def test_closeReceieved(self):
- """
- Test that the default closeReceieved closes the connection.
- """
- self.assertFalse(self.channel.closing)
- self.channel.closeReceived()
- self.assertTrue(self.channel.closing)
-
- def test_write(self):
- """
- Test that write handles data correctly. Send data up to the size
- of the remote window, splitting the data into packets of length
- remoteMaxPacket.
- """
- cb = [False]
- def stubStopWriting():
- cb[0] = True
- # no window to start with
- self.channel.stopWriting = stubStopWriting
- self.channel.write('d')
- self.channel.write('a')
- self.assertFalse(self.channel.areWriting)
- self.assertTrue(cb[0])
- # regular write
- self.channel.addWindowBytes(20)
- self.channel.write('ta')
- data = self.conn.data[self.channel]
- self.assertEqual(data, ['da', 'ta'])
- self.assertEqual(self.channel.remoteWindowLeft, 16)
- # larger than max packet
- self.channel.write('12345678901')
- self.assertEqual(data, ['da', 'ta', '1234567890', '1'])
- self.assertEqual(self.channel.remoteWindowLeft, 5)
- # running out of window
- cb[0] = False
- self.channel.write('123456')
- self.assertFalse(self.channel.areWriting)
- self.assertTrue(cb[0])
- self.assertEqual(data, ['da', 'ta', '1234567890', '1', '12345'])
- self.assertEqual(self.channel.buf, '6')
- self.assertEqual(self.channel.remoteWindowLeft, 0)
-
- def test_writeExtended(self):
- """
- Test that writeExtended handles data correctly. Send extended data
- up to the size of the window, splitting the extended data into packets
- of length remoteMaxPacket.
- """
- cb = [False]
- def stubStopWriting():
- cb[0] = True
- # no window to start with
- self.channel.stopWriting = stubStopWriting
- self.channel.writeExtended(1, 'd')
- self.channel.writeExtended(1, 'a')
- self.channel.writeExtended(2, 't')
- self.assertFalse(self.channel.areWriting)
- self.assertTrue(cb[0])
- # regular write
- self.channel.addWindowBytes(20)
- self.channel.writeExtended(2, 'a')
- data = self.conn.extData[self.channel]
- self.assertEqual(data, [(1, 'da'), (2, 't'), (2, 'a')])
- self.assertEqual(self.channel.remoteWindowLeft, 16)
- # larger than max packet
- self.channel.writeExtended(3, '12345678901')
- self.assertEqual(data, [(1, 'da'), (2, 't'), (2, 'a'),
- (3, '1234567890'), (3, '1')])
- self.assertEqual(self.channel.remoteWindowLeft, 5)
- # running out of window
- cb[0] = False
- self.channel.writeExtended(4, '123456')
- self.assertFalse(self.channel.areWriting)
- self.assertTrue(cb[0])
- self.assertEqual(data, [(1, 'da'), (2, 't'), (2, 'a'),
- (3, '1234567890'), (3, '1'), (4, '12345')])
- self.assertEqual(self.channel.extBuf, [[4, '6']])
- self.assertEqual(self.channel.remoteWindowLeft, 0)
-
- def test_writeSequence(self):
- """
- Test that writeSequence is equivalent to write(''.join(sequece)).
- """
- self.channel.addWindowBytes(20)
- self.channel.writeSequence(map(str, range(10)))
- self.assertEqual(self.conn.data[self.channel], ['0123456789'])
-
- def test_loseConnection(self):
- """
- Tesyt that loseConnection() doesn't close the channel until all
- the data is sent.
- """
- self.channel.write('data')
- self.channel.writeExtended(1, 'datadata')
- self.channel.loseConnection()
- self.assertEqual(self.conn.closes.get(self.channel), None)
- self.channel.addWindowBytes(4) # send regular data
- self.assertEqual(self.conn.closes.get(self.channel), None)
- self.channel.addWindowBytes(8) # send extended data
- self.assertTrue(self.conn.closes.get(self.channel))
-
- def test_getPeer(self):
- """
- Test that getPeer() returns ('SSH', ).
- """
- self.assertEqual(self.channel.getPeer(), ('SSH', 'MockPeer'))
-
- def test_getHost(self):
- """
- Test that getHost() returns ('SSH', ).
- """
- self.assertEqual(self.channel.getHost(), ('SSH', 'MockHost'))
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_checkers.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_checkers.py
deleted file mode 100644
index 98e4e6f..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_checkers.py
+++ /dev/null
@@ -1,603 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.checkers}.
-"""
-
-try:
- import crypt
-except ImportError:
- cryptSkip = 'cannot run without crypt module'
-else:
- cryptSkip = None
-
-import os, base64
-
-from twisted.python import util
-from twisted.python.failure import Failure
-from twisted.trial.unittest import TestCase
-from twisted.python.filepath import FilePath
-from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
-from twisted.cred.credentials import UsernamePassword, IUsernamePassword, \
- SSHPrivateKey, ISSHPrivateKey
-from twisted.cred.error import UnhandledCredentials, UnauthorizedLogin
-from twisted.python.fakepwd import UserDatabase, ShadowDatabase
-from twisted.test.test_process import MockOS
-
-try:
- import Crypto.Cipher.DES3
- import pyasn1
-except ImportError:
- dependencySkip = "can't run without Crypto and PyASN1"
-else:
- dependencySkip = None
- from twisted.conch.ssh import keys
- from twisted.conch import checkers
- from twisted.conch.error import NotEnoughAuthentication, ValidPublicKey
- from twisted.conch.test import keydata
-
-if getattr(os, 'geteuid', None) is None:
- euidSkip = "Cannot run without effective UIDs (questionable)"
-else:
- euidSkip = None
-
-
-class HelperTests(TestCase):
- """
- Tests for helper functions L{verifyCryptedPassword}, L{_pwdGetByName} and
- L{_shadowGetByName}.
- """
- skip = cryptSkip or dependencySkip
-
- def setUp(self):
- self.mockos = MockOS()
-
-
- def test_verifyCryptedPassword(self):
- """
- L{verifyCryptedPassword} returns C{True} if the plaintext password
- passed to it matches the encrypted password passed to it.
- """
- password = 'secret string'
- salt = 'salty'
- crypted = crypt.crypt(password, salt)
- self.assertTrue(
- checkers.verifyCryptedPassword(crypted, password),
- '%r supposed to be valid encrypted password for %r' % (
- crypted, password))
-
-
- def test_verifyCryptedPasswordMD5(self):
- """
- L{verifyCryptedPassword} returns True if the provided cleartext password
- matches the provided MD5 password hash.
- """
- password = 'password'
- salt = '$1$salt'
- crypted = crypt.crypt(password, salt)
- self.assertTrue(
- checkers.verifyCryptedPassword(crypted, password),
- '%r supposed to be valid encrypted password for %s' % (
- crypted, password))
-
-
- def test_refuteCryptedPassword(self):
- """
- L{verifyCryptedPassword} returns C{False} if the plaintext password
- passed to it does not match the encrypted password passed to it.
- """
- password = 'string secret'
- wrong = 'secret string'
- crypted = crypt.crypt(password, password)
- self.assertFalse(
- checkers.verifyCryptedPassword(crypted, wrong),
- '%r not supposed to be valid encrypted password for %s' % (
- crypted, wrong))
-
-
- def test_pwdGetByName(self):
- """
- L{_pwdGetByName} returns a tuple of items from the UNIX /etc/passwd
- database if the L{pwd} module is present.
- """
- userdb = UserDatabase()
- userdb.addUser(
- 'alice', 'secrit', 1, 2, 'first last', '/foo', '/bin/sh')
- self.patch(checkers, 'pwd', userdb)
- self.assertEqual(
- checkers._pwdGetByName('alice'), userdb.getpwnam('alice'))
-
-
- def test_pwdGetByNameWithoutPwd(self):
- """
- If the C{pwd} module isn't present, L{_pwdGetByName} returns C{None}.
- """
- self.patch(checkers, 'pwd', None)
- self.assertIs(checkers._pwdGetByName('alice'), None)
-
-
- def test_shadowGetByName(self):
- """
- L{_shadowGetByName} returns a tuple of items from the UNIX /etc/shadow
- database if the L{spwd} is present.
- """
- userdb = ShadowDatabase()
- userdb.addUser('bob', 'passphrase', 1, 2, 3, 4, 5, 6, 7)
- self.patch(checkers, 'spwd', userdb)
-
- self.mockos.euid = 2345
- self.mockos.egid = 1234
- self.patch(util, 'os', self.mockos)
-
- self.assertEqual(
- checkers._shadowGetByName('bob'), userdb.getspnam('bob'))
- self.assertEqual(self.mockos.seteuidCalls, [0, 2345])
- self.assertEqual(self.mockos.setegidCalls, [0, 1234])
-
-
- def test_shadowGetByNameWithoutSpwd(self):
- """
- L{_shadowGetByName} uses the C{shadow} module to return a tuple of items
- from the UNIX /etc/shadow database if the C{spwd} module is not present
- and the C{shadow} module is.
- """
- userdb = ShadowDatabase()
- userdb.addUser('bob', 'passphrase', 1, 2, 3, 4, 5, 6, 7)
- self.patch(checkers, 'spwd', None)
- self.patch(checkers, 'shadow', userdb)
- self.patch(util, 'os', self.mockos)
-
- self.mockos.euid = 2345
- self.mockos.egid = 1234
-
- self.assertEqual(
- checkers._shadowGetByName('bob'), userdb.getspnam('bob'))
- self.assertEqual(self.mockos.seteuidCalls, [0, 2345])
- self.assertEqual(self.mockos.setegidCalls, [0, 1234])
-
-
- def test_shadowGetByNameWithoutEither(self):
- """
- L{_shadowGetByName} returns C{None} if neither C{spwd} nor C{shadow} is
- present.
- """
- self.patch(checkers, 'spwd', None)
- self.patch(checkers, 'shadow', None)
-
- self.assertIs(checkers._shadowGetByName('bob'), None)
- self.assertEqual(self.mockos.seteuidCalls, [])
- self.assertEqual(self.mockos.setegidCalls, [])
-
-
-
-class SSHPublicKeyDatabaseTestCase(TestCase):
- """
- Tests for L{SSHPublicKeyDatabase}.
- """
- skip = euidSkip or dependencySkip
-
- def setUp(self):
- self.checker = checkers.SSHPublicKeyDatabase()
- self.key1 = base64.encodestring("foobar")
- self.key2 = base64.encodestring("eggspam")
- self.content = "t1 %s foo\nt2 %s egg\n" % (self.key1, self.key2)
-
- self.mockos = MockOS()
- self.mockos.path = FilePath(self.mktemp())
- self.mockos.path.makedirs()
- self.patch(util, 'os', self.mockos)
- self.sshDir = self.mockos.path.child('.ssh')
- self.sshDir.makedirs()
-
- userdb = UserDatabase()
- userdb.addUser(
- 'user', 'password', 1, 2, 'first last',
- self.mockos.path.path, '/bin/shell')
- self.checker._userdb = userdb
-
-
- def _testCheckKey(self, filename):
- self.sshDir.child(filename).setContent(self.content)
- user = UsernamePassword("user", "password")
- user.blob = "foobar"
- self.assertTrue(self.checker.checkKey(user))
- user.blob = "eggspam"
- self.assertTrue(self.checker.checkKey(user))
- user.blob = "notallowed"
- self.assertFalse(self.checker.checkKey(user))
-
-
- def test_checkKey(self):
- """
- L{SSHPublicKeyDatabase.checkKey} should retrieve the content of the
- authorized_keys file and check the keys against that file.
- """
- self._testCheckKey("authorized_keys")
- self.assertEqual(self.mockos.seteuidCalls, [])
- self.assertEqual(self.mockos.setegidCalls, [])
-
-
- def test_checkKey2(self):
- """
- L{SSHPublicKeyDatabase.checkKey} should retrieve the content of the
- authorized_keys2 file and check the keys against that file.
- """
- self._testCheckKey("authorized_keys2")
- self.assertEqual(self.mockos.seteuidCalls, [])
- self.assertEqual(self.mockos.setegidCalls, [])
-
-
- def test_checkKeyAsRoot(self):
- """
- If the key file is readable, L{SSHPublicKeyDatabase.checkKey} should
- switch its uid/gid to the ones of the authenticated user.
- """
- keyFile = self.sshDir.child("authorized_keys")
- keyFile.setContent(self.content)
- # Fake permission error by changing the mode
- keyFile.chmod(0000)
- self.addCleanup(keyFile.chmod, 0777)
- # And restore the right mode when seteuid is called
- savedSeteuid = self.mockos.seteuid
- def seteuid(euid):
- keyFile.chmod(0777)
- return savedSeteuid(euid)
- self.mockos.euid = 2345
- self.mockos.egid = 1234
- self.patch(self.mockos, "seteuid", seteuid)
- self.patch(util, 'os', self.mockos)
- user = UsernamePassword("user", "password")
- user.blob = "foobar"
- self.assertTrue(self.checker.checkKey(user))
- self.assertEqual(self.mockos.seteuidCalls, [0, 1, 0, 2345])
- self.assertEqual(self.mockos.setegidCalls, [2, 1234])
-
-
- def test_requestAvatarId(self):
- """
- L{SSHPublicKeyDatabase.requestAvatarId} should return the avatar id
- passed in if its C{_checkKey} method returns True.
- """
- def _checkKey(ignored):
- return True
- self.patch(self.checker, 'checkKey', _checkKey)
- credentials = SSHPrivateKey(
- 'test', 'ssh-rsa', keydata.publicRSA_openssh, 'foo',
- keys.Key.fromString(keydata.privateRSA_openssh).sign('foo'))
- d = self.checker.requestAvatarId(credentials)
- def _verify(avatarId):
- self.assertEqual(avatarId, 'test')
- return d.addCallback(_verify)
-
-
- def test_requestAvatarIdWithoutSignature(self):
- """
- L{SSHPublicKeyDatabase.requestAvatarId} should raise L{ValidPublicKey}
- if the credentials represent a valid key without a signature. This
- tells the user that the key is valid for login, but does not actually
- allow that user to do so without a signature.
- """
- def _checkKey(ignored):
- return True
- self.patch(self.checker, 'checkKey', _checkKey)
- credentials = SSHPrivateKey(
- 'test', 'ssh-rsa', keydata.publicRSA_openssh, None, None)
- d = self.checker.requestAvatarId(credentials)
- return self.assertFailure(d, ValidPublicKey)
-
-
- def test_requestAvatarIdInvalidKey(self):
- """
- If L{SSHPublicKeyDatabase.checkKey} returns False,
- C{_cbRequestAvatarId} should raise L{UnauthorizedLogin}.
- """
- def _checkKey(ignored):
- return False
- self.patch(self.checker, 'checkKey', _checkKey)
- d = self.checker.requestAvatarId(None);
- return self.assertFailure(d, UnauthorizedLogin)
-
-
- def test_requestAvatarIdInvalidSignature(self):
- """
- Valid keys with invalid signatures should cause
- L{SSHPublicKeyDatabase.requestAvatarId} to return a {UnauthorizedLogin}
- failure
- """
- def _checkKey(ignored):
- return True
- self.patch(self.checker, 'checkKey', _checkKey)
- credentials = SSHPrivateKey(
- 'test', 'ssh-rsa', keydata.publicRSA_openssh, 'foo',
- keys.Key.fromString(keydata.privateDSA_openssh).sign('foo'))
- d = self.checker.requestAvatarId(credentials)
- return self.assertFailure(d, UnauthorizedLogin)
-
-
- def test_requestAvatarIdNormalizeException(self):
- """
- Exceptions raised while verifying the key should be normalized into an
- C{UnauthorizedLogin} failure.
- """
- def _checkKey(ignored):
- return True
- self.patch(self.checker, 'checkKey', _checkKey)
- credentials = SSHPrivateKey('test', None, 'blob', 'sigData', 'sig')
- d = self.checker.requestAvatarId(credentials)
- def _verifyLoggedException(failure):
- errors = self.flushLoggedErrors(keys.BadKeyError)
- self.assertEqual(len(errors), 1)
- return failure
- d.addErrback(_verifyLoggedException)
- return self.assertFailure(d, UnauthorizedLogin)
-
-
-
-class SSHProtocolCheckerTestCase(TestCase):
- """
- Tests for L{SSHProtocolChecker}.
- """
-
- skip = dependencySkip
-
- def test_registerChecker(self):
- """
- L{SSHProcotolChecker.registerChecker} should add the given checker to
- the list of registered checkers.
- """
- checker = checkers.SSHProtocolChecker()
- self.assertEqual(checker.credentialInterfaces, [])
- checker.registerChecker(checkers.SSHPublicKeyDatabase(), )
- self.assertEqual(checker.credentialInterfaces, [ISSHPrivateKey])
- self.assertIsInstance(checker.checkers[ISSHPrivateKey],
- checkers.SSHPublicKeyDatabase)
-
-
- def test_registerCheckerWithInterface(self):
- """
- If a apecific interface is passed into
- L{SSHProtocolChecker.registerChecker}, that interface should be
- registered instead of what the checker specifies in
- credentialIntefaces.
- """
- checker = checkers.SSHProtocolChecker()
- self.assertEqual(checker.credentialInterfaces, [])
- checker.registerChecker(checkers.SSHPublicKeyDatabase(),
- IUsernamePassword)
- self.assertEqual(checker.credentialInterfaces, [IUsernamePassword])
- self.assertIsInstance(checker.checkers[IUsernamePassword],
- checkers.SSHPublicKeyDatabase)
-
-
- def test_requestAvatarId(self):
- """
- L{SSHProtocolChecker.requestAvatarId} should defer to one if its
- registered checkers to authenticate a user.
- """
- checker = checkers.SSHProtocolChecker()
- passwordDatabase = InMemoryUsernamePasswordDatabaseDontUse()
- passwordDatabase.addUser('test', 'test')
- checker.registerChecker(passwordDatabase)
- d = checker.requestAvatarId(UsernamePassword('test', 'test'))
- def _callback(avatarId):
- self.assertEqual(avatarId, 'test')
- return d.addCallback(_callback)
-
-
- def test_requestAvatarIdWithNotEnoughAuthentication(self):
- """
- If the client indicates that it is never satisfied, by always returning
- False from _areDone, then L{SSHProtocolChecker} should raise
- L{NotEnoughAuthentication}.
- """
- checker = checkers.SSHProtocolChecker()
- def _areDone(avatarId):
- return False
- self.patch(checker, 'areDone', _areDone)
-
- passwordDatabase = InMemoryUsernamePasswordDatabaseDontUse()
- passwordDatabase.addUser('test', 'test')
- checker.registerChecker(passwordDatabase)
- d = checker.requestAvatarId(UsernamePassword('test', 'test'))
- return self.assertFailure(d, NotEnoughAuthentication)
-
-
- def test_requestAvatarIdInvalidCredential(self):
- """
- If the passed credentials aren't handled by any registered checker,
- L{SSHProtocolChecker} should raise L{UnhandledCredentials}.
- """
- checker = checkers.SSHProtocolChecker()
- d = checker.requestAvatarId(UsernamePassword('test', 'test'))
- return self.assertFailure(d, UnhandledCredentials)
-
-
- def test_areDone(self):
- """
- The default L{SSHProcotolChecker.areDone} should simply return True.
- """
- self.assertEqual(checkers.SSHProtocolChecker().areDone(None), True)
-
-
-
-class UNIXPasswordDatabaseTests(TestCase):
- """
- Tests for L{UNIXPasswordDatabase}.
- """
- skip = cryptSkip or dependencySkip
-
- def assertLoggedIn(self, d, username):
- """
- Assert that the L{Deferred} passed in is called back with the value
- 'username'. This represents a valid login for this TestCase.
-
- NOTE: To work, this method's return value must be returned from the
- test method, or otherwise hooked up to the test machinery.
-
- @param d: a L{Deferred} from an L{IChecker.requestAvatarId} method.
- @type d: L{Deferred}
- @rtype: L{Deferred}
- """
- result = []
- d.addBoth(result.append)
- self.assertEqual(len(result), 1, "login incomplete")
- if isinstance(result[0], Failure):
- result[0].raiseException()
- self.assertEqual(result[0], username)
-
-
- def test_defaultCheckers(self):
- """
- L{UNIXPasswordDatabase} with no arguments has checks the C{pwd} database
- and then the C{spwd} database.
- """
- checker = checkers.UNIXPasswordDatabase()
-
- def crypted(username, password):
- salt = crypt.crypt(password, username)
- crypted = crypt.crypt(password, '$1$' + salt)
- return crypted
-
- pwd = UserDatabase()
- pwd.addUser('alice', crypted('alice', 'password'),
- 1, 2, 'foo', '/foo', '/bin/sh')
- # x and * are convention for "look elsewhere for the password"
- pwd.addUser('bob', 'x', 1, 2, 'bar', '/bar', '/bin/sh')
- spwd = ShadowDatabase()
- spwd.addUser('alice', 'wrong', 1, 2, 3, 4, 5, 6, 7)
- spwd.addUser('bob', crypted('bob', 'password'),
- 8, 9, 10, 11, 12, 13, 14)
-
- self.patch(checkers, 'pwd', pwd)
- self.patch(checkers, 'spwd', spwd)
-
- mockos = MockOS()
- self.patch(util, 'os', mockos)
-
- mockos.euid = 2345
- mockos.egid = 1234
-
- cred = UsernamePassword("alice", "password")
- self.assertLoggedIn(checker.requestAvatarId(cred), 'alice')
- self.assertEqual(mockos.seteuidCalls, [])
- self.assertEqual(mockos.setegidCalls, [])
- cred.username = "bob"
- self.assertLoggedIn(checker.requestAvatarId(cred), 'bob')
- self.assertEqual(mockos.seteuidCalls, [0, 2345])
- self.assertEqual(mockos.setegidCalls, [0, 1234])
-
-
- def assertUnauthorizedLogin(self, d):
- """
- Asserts that the L{Deferred} passed in is erred back with an
- L{UnauthorizedLogin} L{Failure}. This reprsents an invalid login for
- this TestCase.
-
- NOTE: To work, this method's return value must be returned from the
- test method, or otherwise hooked up to the test machinery.
-
- @param d: a L{Deferred} from an L{IChecker.requestAvatarId} method.
- @type d: L{Deferred}
- @rtype: L{None}
- """
- self.assertRaises(
- checkers.UnauthorizedLogin, self.assertLoggedIn, d, 'bogus value')
-
-
- def test_passInCheckers(self):
- """
- L{UNIXPasswordDatabase} takes a list of functions to check for UNIX
- user information.
- """
- password = crypt.crypt('secret', 'secret')
- userdb = UserDatabase()
- userdb.addUser('anybody', password, 1, 2, 'foo', '/bar', '/bin/sh')
- checker = checkers.UNIXPasswordDatabase([userdb.getpwnam])
- self.assertLoggedIn(
- checker.requestAvatarId(UsernamePassword('anybody', 'secret')),
- 'anybody')
-
-
- def test_verifyPassword(self):
- """
- If the encrypted password provided by the getpwnam function is valid
- (verified by the L{verifyCryptedPassword} function), we callback the
- C{requestAvatarId} L{Deferred} with the username.
- """
- def verifyCryptedPassword(crypted, pw):
- return crypted == pw
- def getpwnam(username):
- return [username, username]
- self.patch(checkers, 'verifyCryptedPassword', verifyCryptedPassword)
- checker = checkers.UNIXPasswordDatabase([getpwnam])
- credential = UsernamePassword('username', 'username')
- self.assertLoggedIn(checker.requestAvatarId(credential), 'username')
-
-
- def test_failOnKeyError(self):
- """
- If the getpwnam function raises a KeyError, the login fails with an
- L{UnauthorizedLogin} exception.
- """
- def getpwnam(username):
- raise KeyError(username)
- checker = checkers.UNIXPasswordDatabase([getpwnam])
- credential = UsernamePassword('username', 'username')
- self.assertUnauthorizedLogin(checker.requestAvatarId(credential))
-
-
- def test_failOnBadPassword(self):
- """
- If the verifyCryptedPassword function doesn't verify the password, the
- login fails with an L{UnauthorizedLogin} exception.
- """
- def verifyCryptedPassword(crypted, pw):
- return False
- def getpwnam(username):
- return [username, username]
- self.patch(checkers, 'verifyCryptedPassword', verifyCryptedPassword)
- checker = checkers.UNIXPasswordDatabase([getpwnam])
- credential = UsernamePassword('username', 'username')
- self.assertUnauthorizedLogin(checker.requestAvatarId(credential))
-
-
- def test_loopThroughFunctions(self):
- """
- UNIXPasswordDatabase.requestAvatarId loops through each getpwnam
- function associated with it and returns a L{Deferred} which fires with
- the result of the first one which returns a value other than None.
- ones do not verify the password.
- """
- def verifyCryptedPassword(crypted, pw):
- return crypted == pw
- def getpwnam1(username):
- return [username, 'not the password']
- def getpwnam2(username):
- return [username, username]
- self.patch(checkers, 'verifyCryptedPassword', verifyCryptedPassword)
- checker = checkers.UNIXPasswordDatabase([getpwnam1, getpwnam2])
- credential = UsernamePassword('username', 'username')
- self.assertLoggedIn(checker.requestAvatarId(credential), 'username')
-
-
- def test_failOnSpecial(self):
- """
- If the password returned by any function is C{""}, C{"x"}, or C{"*"} it
- is not compared against the supplied password. Instead it is skipped.
- """
- pwd = UserDatabase()
- pwd.addUser('alice', '', 1, 2, '', 'foo', 'bar')
- pwd.addUser('bob', 'x', 1, 2, '', 'foo', 'bar')
- pwd.addUser('carol', '*', 1, 2, '', 'foo', 'bar')
- self.patch(checkers, 'pwd', pwd)
-
- checker = checkers.UNIXPasswordDatabase([checkers._pwdGetByName])
- cred = UsernamePassword('alice', '')
- self.assertUnauthorizedLogin(checker.requestAvatarId(cred))
-
- cred = UsernamePassword('bob', 'x')
- self.assertUnauthorizedLogin(checker.requestAvatarId(cred))
-
- cred = UsernamePassword('carol', '*')
- self.assertUnauthorizedLogin(checker.requestAvatarId(cred))
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_ckeygen.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_ckeygen.py
deleted file mode 100644
index 272f947..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_ckeygen.py
+++ /dev/null
@@ -1,340 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.scripts.ckeygen}.
-"""
-
-import getpass
-import sys
-from StringIO import StringIO
-
-try:
- import Crypto
- import pyasn1
-except ImportError:
- skip = "PyCrypto and pyasn1 required for twisted.conch.scripts.ckeygen."
-else:
- from twisted.conch.ssh.keys import Key, BadKeyError
- from twisted.conch.scripts.ckeygen import (
- changePassPhrase, displayPublicKey, printFingerprint, _saveKey)
-
-from twisted.python.filepath import FilePath
-from twisted.trial.unittest import TestCase
-from twisted.conch.test.keydata import (
- publicRSA_openssh, privateRSA_openssh, privateRSA_openssh_encrypted)
-
-
-
-def makeGetpass(*passphrases):
- """
- Return a callable to patch C{getpass.getpass}. Yields a passphrase each
- time called. Use case is to provide an old, then new passphrase(s) as if
- requested interactively.
-
- @param passphrases: The list of passphrases returned, one per each call.
- """
- passphrases = iter(passphrases)
-
- def fakeGetpass(_):
- return passphrases.next()
-
- return fakeGetpass
-
-
-
-class KeyGenTests(TestCase):
- """
- Tests for various functions used to implement the I{ckeygen} script.
- """
- def setUp(self):
- """
- Patch C{sys.stdout} with a L{StringIO} instance to tests can make
- assertions about what's printed.
- """
- self.stdout = StringIO()
- self.patch(sys, 'stdout', self.stdout)
-
-
- def test_printFingerprint(self):
- """
- L{printFingerprint} writes a line to standard out giving the number of
- bits of the key, its fingerprint, and the basename of the file from it
- was read.
- """
- filename = self.mktemp()
- FilePath(filename).setContent(publicRSA_openssh)
- printFingerprint({'filename': filename})
- self.assertEqual(
- self.stdout.getvalue(),
- '768 3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af temp\n')
-
-
- def test_saveKey(self):
- """
- L{_saveKey} writes the private and public parts of a key to two
- different files and writes a report of this to standard out.
- """
- base = FilePath(self.mktemp())
- base.makedirs()
- filename = base.child('id_rsa').path
- key = Key.fromString(privateRSA_openssh)
- _saveKey(
- key.keyObject,
- {'filename': filename, 'pass': 'passphrase'})
- self.assertEqual(
- self.stdout.getvalue(),
- "Your identification has been saved in %s\n"
- "Your public key has been saved in %s.pub\n"
- "The key fingerprint is:\n"
- "3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af\n" % (
- filename,
- filename))
- self.assertEqual(
- key.fromString(
- base.child('id_rsa').getContent(), None, 'passphrase'),
- key)
- self.assertEqual(
- Key.fromString(base.child('id_rsa.pub').getContent()),
- key.public())
-
-
- def test_saveKeyEmptyPassphrase(self):
- """
- L{_saveKey} will choose an empty string for the passphrase if
- no-passphrase is C{True}.
- """
- base = FilePath(self.mktemp())
- base.makedirs()
- filename = base.child('id_rsa').path
- key = Key.fromString(privateRSA_openssh)
- _saveKey(
- key.keyObject,
- {'filename': filename, 'no-passphrase': True})
- self.assertEqual(
- key.fromString(
- base.child('id_rsa').getContent(), None, b''),
- key)
-
-
- def test_displayPublicKey(self):
- """
- L{displayPublicKey} prints out the public key associated with a given
- private key.
- """
- filename = self.mktemp()
- pubKey = Key.fromString(publicRSA_openssh)
- FilePath(filename).setContent(privateRSA_openssh)
- displayPublicKey({'filename': filename})
- self.assertEqual(
- self.stdout.getvalue().strip('\n'),
- pubKey.toString('openssh'))
-
-
- def test_displayPublicKeyEncrypted(self):
- """
- L{displayPublicKey} prints out the public key associated with a given
- private key using the given passphrase when it's encrypted.
- """
- filename = self.mktemp()
- pubKey = Key.fromString(publicRSA_openssh)
- FilePath(filename).setContent(privateRSA_openssh_encrypted)
- displayPublicKey({'filename': filename, 'pass': 'encrypted'})
- self.assertEqual(
- self.stdout.getvalue().strip('\n'),
- pubKey.toString('openssh'))
-
-
- def test_displayPublicKeyEncryptedPassphrasePrompt(self):
- """
- L{displayPublicKey} prints out the public key associated with a given
- private key, asking for the passphrase when it's encrypted.
- """
- filename = self.mktemp()
- pubKey = Key.fromString(publicRSA_openssh)
- FilePath(filename).setContent(privateRSA_openssh_encrypted)
- self.patch(getpass, 'getpass', lambda x: 'encrypted')
- displayPublicKey({'filename': filename})
- self.assertEqual(
- self.stdout.getvalue().strip('\n'),
- pubKey.toString('openssh'))
-
-
- def test_displayPublicKeyWrongPassphrase(self):
- """
- L{displayPublicKey} fails with a L{BadKeyError} when trying to decrypt
- an encrypted key with the wrong password.
- """
- filename = self.mktemp()
- FilePath(filename).setContent(privateRSA_openssh_encrypted)
- self.assertRaises(
- BadKeyError, displayPublicKey,
- {'filename': filename, 'pass': 'wrong'})
-
-
- def test_changePassphrase(self):
- """
- L{changePassPhrase} allows a user to change the passphrase of a
- private key interactively.
- """
- oldNewConfirm = makeGetpass('encrypted', 'newpass', 'newpass')
- self.patch(getpass, 'getpass', oldNewConfirm)
-
- filename = self.mktemp()
- FilePath(filename).setContent(privateRSA_openssh_encrypted)
-
- changePassPhrase({'filename': filename})
- self.assertEqual(
- self.stdout.getvalue().strip('\n'),
- 'Your identification has been saved with the new passphrase.')
- self.assertNotEqual(privateRSA_openssh_encrypted,
- FilePath(filename).getContent())
-
-
- def test_changePassphraseWithOld(self):
- """
- L{changePassPhrase} allows a user to change the passphrase of a
- private key, providing the old passphrase and prompting for new one.
- """
- newConfirm = makeGetpass('newpass', 'newpass')
- self.patch(getpass, 'getpass', newConfirm)
-
- filename = self.mktemp()
- FilePath(filename).setContent(privateRSA_openssh_encrypted)
-
- changePassPhrase({'filename': filename, 'pass': 'encrypted'})
- self.assertEqual(
- self.stdout.getvalue().strip('\n'),
- 'Your identification has been saved with the new passphrase.')
- self.assertNotEqual(privateRSA_openssh_encrypted,
- FilePath(filename).getContent())
-
-
- def test_changePassphraseWithBoth(self):
- """
- L{changePassPhrase} allows a user to change the passphrase of a private
- key by providing both old and new passphrases without prompting.
- """
- filename = self.mktemp()
- FilePath(filename).setContent(privateRSA_openssh_encrypted)
-
- changePassPhrase(
- {'filename': filename, 'pass': 'encrypted',
- 'newpass': 'newencrypt'})
- self.assertEqual(
- self.stdout.getvalue().strip('\n'),
- 'Your identification has been saved with the new passphrase.')
- self.assertNotEqual(privateRSA_openssh_encrypted,
- FilePath(filename).getContent())
-
-
- def test_changePassphraseWrongPassphrase(self):
- """
- L{changePassPhrase} exits if passed an invalid old passphrase when
- trying to change the passphrase of a private key.
- """
- filename = self.mktemp()
- FilePath(filename).setContent(privateRSA_openssh_encrypted)
- error = self.assertRaises(
- SystemExit, changePassPhrase,
- {'filename': filename, 'pass': 'wrong'})
- self.assertEqual('Could not change passphrase: old passphrase error',
- str(error))
- self.assertEqual(privateRSA_openssh_encrypted,
- FilePath(filename).getContent())
-
-
- def test_changePassphraseEmptyGetPass(self):
- """
- L{changePassPhrase} exits if no passphrase is specified for the
- C{getpass} call and the key is encrypted.
- """
- self.patch(getpass, 'getpass', makeGetpass(''))
- filename = self.mktemp()
- FilePath(filename).setContent(privateRSA_openssh_encrypted)
- error = self.assertRaises(
- SystemExit, changePassPhrase, {'filename': filename})
- self.assertEqual(
- 'Could not change passphrase: Passphrase must be provided '
- 'for an encrypted key',
- str(error))
- self.assertEqual(privateRSA_openssh_encrypted,
- FilePath(filename).getContent())
-
-
- def test_changePassphraseBadKey(self):
- """
- L{changePassPhrase} exits if the file specified points to an invalid
- key.
- """
- filename = self.mktemp()
- FilePath(filename).setContent('foobar')
- error = self.assertRaises(
- SystemExit, changePassPhrase, {'filename': filename})
- self.assertEqual(
- "Could not change passphrase: cannot guess the type of 'foobar'",
- str(error))
- self.assertEqual('foobar', FilePath(filename).getContent())
-
-
- def test_changePassphraseCreateError(self):
- """
- L{changePassPhrase} doesn't modify the key file if an unexpected error
- happens when trying to create the key with the new passphrase.
- """
- filename = self.mktemp()
- FilePath(filename).setContent(privateRSA_openssh)
-
- def toString(*args, **kwargs):
- raise RuntimeError('oops')
-
- self.patch(Key, 'toString', toString)
-
- error = self.assertRaises(
- SystemExit, changePassPhrase,
- {'filename': filename,
- 'newpass': 'newencrypt'})
-
- self.assertEqual(
- 'Could not change passphrase: oops', str(error))
-
- self.assertEqual(privateRSA_openssh, FilePath(filename).getContent())
-
-
- def test_changePassphraseEmptyStringError(self):
- """
- L{changePassPhrase} doesn't modify the key file if C{toString} returns
- an empty string.
- """
- filename = self.mktemp()
- FilePath(filename).setContent(privateRSA_openssh)
-
- def toString(*args, **kwargs):
- return ''
-
- self.patch(Key, 'toString', toString)
-
- error = self.assertRaises(
- SystemExit, changePassPhrase,
- {'filename': filename, 'newpass': 'newencrypt'})
-
- self.assertEqual(
- "Could not change passphrase: "
- "cannot guess the type of ''", str(error))
-
- self.assertEqual(privateRSA_openssh, FilePath(filename).getContent())
-
-
- def test_changePassphrasePublicKey(self):
- """
- L{changePassPhrase} exits when trying to change the passphrase on a
- public key, and doesn't change the file.
- """
- filename = self.mktemp()
- FilePath(filename).setContent(publicRSA_openssh)
- error = self.assertRaises(
- SystemExit, changePassPhrase,
- {'filename': filename, 'newpass': 'pass'})
- self.assertEqual(
- 'Could not change passphrase: key not encrypted', str(error))
- self.assertEqual(publicRSA_openssh, FilePath(filename).getContent())
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_conch.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_conch.py
deleted file mode 100644
index 411d903..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_conch.py
+++ /dev/null
@@ -1,564 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_conch -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-import os, sys, socket
-from itertools import count
-
-from zope.interface import implements
-
-from twisted.cred import portal
-from twisted.internet import reactor, defer, protocol
-from twisted.internet.error import ProcessExitedAlready
-from twisted.internet.task import LoopingCall
-from twisted.python import log, runtime
-from twisted.trial import unittest
-from twisted.conch.error import ConchError
-from twisted.conch.avatar import ConchUser
-from twisted.conch.ssh.session import ISession, SSHSession, wrapProtocol
-
-try:
- from twisted.conch.scripts.conch import SSHSession as StdioInteractingSession
-except ImportError, e:
- StdioInteractingSession = None
- _reason = str(e)
- del e
-
-from twisted.conch.test.test_ssh import ConchTestRealm
-from twisted.python.procutils import which
-
-from twisted.conch.test.keydata import publicRSA_openssh, privateRSA_openssh
-from twisted.conch.test.keydata import publicDSA_openssh, privateDSA_openssh
-
-from twisted.conch.test.test_ssh import Crypto, pyasn1
-try:
- from twisted.conch.test.test_ssh import ConchTestServerFactory, \
- ConchTestPublicKeyChecker
-except ImportError:
- pass
-
-
-
-class FakeStdio(object):
- """
- A fake for testing L{twisted.conch.scripts.conch.SSHSession.eofReceived} and
- L{twisted.conch.scripts.cftp.SSHSession.eofReceived}.
-
- @ivar writeConnLost: A flag which records whether L{loserWriteConnection}
- has been called.
- """
- writeConnLost = False
-
- def loseWriteConnection(self):
- """
- Record the call to loseWriteConnection.
- """
- self.writeConnLost = True
-
-
-
-class StdioInteractingSessionTests(unittest.TestCase):
- """
- Tests for L{twisted.conch.scripts.conch.SSHSession}.
- """
- if StdioInteractingSession is None:
- skip = _reason
-
- def test_eofReceived(self):
- """
- L{twisted.conch.scripts.conch.SSHSession.eofReceived} loses the
- write half of its stdio connection.
- """
- stdio = FakeStdio()
- channel = StdioInteractingSession()
- channel.stdio = stdio
- channel.eofReceived()
- self.assertTrue(stdio.writeConnLost)
-
-
-
-class Echo(protocol.Protocol):
- def connectionMade(self):
- log.msg('ECHO CONNECTION MADE')
-
-
- def connectionLost(self, reason):
- log.msg('ECHO CONNECTION DONE')
-
-
- def dataReceived(self, data):
- self.transport.write(data)
- if '\n' in data:
- self.transport.loseConnection()
-
-
-
-class EchoFactory(protocol.Factory):
- protocol = Echo
-
-
-
-class ConchTestOpenSSHProcess(protocol.ProcessProtocol):
- """
- Test protocol for launching an OpenSSH client process.
-
- @ivar deferred: Set by whatever uses this object. Accessed using
- L{_getDeferred}, which destroys the value so the Deferred is not
- fired twice. Fires when the process is terminated.
- """
-
- deferred = None
- buf = ''
-
- def _getDeferred(self):
- d, self.deferred = self.deferred, None
- return d
-
-
- def outReceived(self, data):
- self.buf += data
-
-
- def processEnded(self, reason):
- """
- Called when the process has ended.
-
- @param reason: a Failure giving the reason for the process' end.
- """
- if reason.value.exitCode != 0:
- self._getDeferred().errback(
- ConchError("exit code was not 0: %s" %
- reason.value.exitCode))
- else:
- buf = self.buf.replace('\r\n', '\n')
- self._getDeferred().callback(buf)
-
-
-
-class ConchTestForwardingProcess(protocol.ProcessProtocol):
- """
- Manages a third-party process which launches a server.
-
- Uses L{ConchTestForwardingPort} to connect to the third-party server.
- Once L{ConchTestForwardingPort} has disconnected, kill the process and fire
- a Deferred with the data received by the L{ConchTestForwardingPort}.
-
- @ivar deferred: Set by whatever uses this object. Accessed using
- L{_getDeferred}, which destroys the value so the Deferred is not
- fired twice. Fires when the process is terminated.
- """
-
- deferred = None
-
- def __init__(self, port, data):
- """
- @type port: C{int}
- @param port: The port on which the third-party server is listening.
- (it is assumed that the server is running on localhost).
-
- @type data: C{str}
- @param data: This is sent to the third-party server. Must end with '\n'
- in order to trigger a disconnect.
- """
- self.port = port
- self.buffer = None
- self.data = data
-
-
- def _getDeferred(self):
- d, self.deferred = self.deferred, None
- return d
-
-
- def connectionMade(self):
- self._connect()
-
-
- def _connect(self):
- """
- Connect to the server, which is often a third-party process.
- Tries to reconnect if it fails because we have no way of determining
- exactly when the port becomes available for listening -- we can only
- know when the process starts.
- """
- cc = protocol.ClientCreator(reactor, ConchTestForwardingPort, self,
- self.data)
- d = cc.connectTCP('127.0.0.1', self.port)
- d.addErrback(self._ebConnect)
- return d
-
-
- def _ebConnect(self, f):
- reactor.callLater(.1, self._connect)
-
-
- def forwardingPortDisconnected(self, buffer):
- """
- The network connection has died; save the buffer of output
- from the network and attempt to quit the process gracefully,
- and then (after the reactor has spun) send it a KILL signal.
- """
- self.buffer = buffer
- self.transport.write('\x03')
- self.transport.loseConnection()
- reactor.callLater(0, self._reallyDie)
-
-
- def _reallyDie(self):
- try:
- self.transport.signalProcess('KILL')
- except ProcessExitedAlready:
- pass
-
-
- def processEnded(self, reason):
- """
- Fire the Deferred at self.deferred with the data collected
- from the L{ConchTestForwardingPort} connection, if any.
- """
- self._getDeferred().callback(self.buffer)
-
-
-
-class ConchTestForwardingPort(protocol.Protocol):
- """
- Connects to server launched by a third-party process (managed by
- L{ConchTestForwardingProcess}) sends data, then reports whatever it
- received back to the L{ConchTestForwardingProcess} once the connection
- is ended.
- """
-
-
- def __init__(self, protocol, data):
- """
- @type protocol: L{ConchTestForwardingProcess}
- @param protocol: The L{ProcessProtocol} which made this connection.
-
- @type data: str
- @param data: The data to be sent to the third-party server.
- """
- self.protocol = protocol
- self.data = data
-
-
- def connectionMade(self):
- self.buffer = ''
- self.transport.write(self.data)
-
-
- def dataReceived(self, data):
- self.buffer += data
-
-
- def connectionLost(self, reason):
- self.protocol.forwardingPortDisconnected(self.buffer)
-
-
-
-def _makeArgs(args, mod="conch"):
- start = [sys.executable, '-c'
-"""
-### Twisted Preamble
-import sys, os
-path = os.path.abspath(sys.argv[0])
-while os.path.dirname(path) != path:
- if os.path.basename(path).startswith('Twisted'):
- sys.path.insert(0, path)
- break
- path = os.path.dirname(path)
-
-from twisted.conch.scripts.%s import run
-run()""" % mod]
- return start + list(args)
-
-
-
-class ConchServerSetupMixin:
- if not Crypto:
- skip = "can't run w/o PyCrypto"
-
- if not pyasn1:
- skip = "Cannot run without PyASN1"
-
- realmFactory = staticmethod(lambda: ConchTestRealm('testuser'))
-
- def _createFiles(self):
- for f in ['rsa_test','rsa_test.pub','dsa_test','dsa_test.pub',
- 'kh_test']:
- if os.path.exists(f):
- os.remove(f)
- open('rsa_test','w').write(privateRSA_openssh)
- open('rsa_test.pub','w').write(publicRSA_openssh)
- open('dsa_test.pub','w').write(publicDSA_openssh)
- open('dsa_test','w').write(privateDSA_openssh)
- os.chmod('dsa_test', 33152)
- os.chmod('rsa_test', 33152)
- open('kh_test','w').write('127.0.0.1 '+publicRSA_openssh)
-
-
- def _getFreePort(self):
- s = socket.socket()
- s.bind(('', 0))
- port = s.getsockname()[1]
- s.close()
- return port
-
-
- def _makeConchFactory(self):
- """
- Make a L{ConchTestServerFactory}, which allows us to start a
- L{ConchTestServer} -- i.e. an actually listening conch.
- """
- realm = self.realmFactory()
- p = portal.Portal(realm)
- p.registerChecker(ConchTestPublicKeyChecker())
- factory = ConchTestServerFactory()
- factory.portal = p
- return factory
-
-
- def setUp(self):
- self._createFiles()
- self.conchFactory = self._makeConchFactory()
- self.conchFactory.expectedLoseConnection = 1
- self.conchServer = reactor.listenTCP(0, self.conchFactory,
- interface="127.0.0.1")
- self.echoServer = reactor.listenTCP(0, EchoFactory())
- self.echoPort = self.echoServer.getHost().port
-
-
- def tearDown(self):
- try:
- self.conchFactory.proto.done = 1
- except AttributeError:
- pass
- else:
- self.conchFactory.proto.transport.loseConnection()
- return defer.gatherResults([
- defer.maybeDeferred(self.conchServer.stopListening),
- defer.maybeDeferred(self.echoServer.stopListening)])
-
-
-
-class ForwardingMixin(ConchServerSetupMixin):
- """
- Template class for tests of the Conch server's ability to forward arbitrary
- protocols over SSH.
-
- These tests are integration tests, not unit tests. They launch a Conch
- server, a custom TCP server (just an L{EchoProtocol}) and then call
- L{execute}.
-
- L{execute} is implemented by subclasses of L{ForwardingMixin}. It should
- cause an SSH client to connect to the Conch server, asking it to forward
- data to the custom TCP server.
- """
-
- def test_exec(self):
- """
- Test that we can use whatever client to send the command "echo goodbye"
- to the Conch server. Make sure we receive "goodbye" back from the
- server.
- """
- d = self.execute('echo goodbye', ConchTestOpenSSHProcess())
- return d.addCallback(self.assertEqual, 'goodbye\n')
-
-
- def test_localToRemoteForwarding(self):
- """
- Test that we can use whatever client to forward a local port to a
- specified port on the server.
- """
- localPort = self._getFreePort()
- process = ConchTestForwardingProcess(localPort, 'test\n')
- d = self.execute('', process,
- sshArgs='-N -L%i:127.0.0.1:%i'
- % (localPort, self.echoPort))
- d.addCallback(self.assertEqual, 'test\n')
- return d
-
-
- def test_remoteToLocalForwarding(self):
- """
- Test that we can use whatever client to forward a port from the server
- to a port locally.
- """
- localPort = self._getFreePort()
- process = ConchTestForwardingProcess(localPort, 'test\n')
- d = self.execute('', process,
- sshArgs='-N -R %i:127.0.0.1:%i'
- % (localPort, self.echoPort))
- d.addCallback(self.assertEqual, 'test\n')
- return d
-
-
-
-class RekeyAvatar(ConchUser):
- """
- This avatar implements a shell which sends 60 numbered lines to whatever
- connects to it, then closes the session with a 0 exit status.
-
- 60 lines is selected as being enough to send more than 2kB of traffic, the
- amount the client is configured to initiate a rekey after.
- """
- # Conventionally there is a separate adapter object which provides ISession
- # for the user, but making the user provide ISession directly works too.
- # This isn't a full implementation of ISession though, just enough to make
- # these tests pass.
- implements(ISession)
-
- def __init__(self):
- ConchUser.__init__(self)
- self.channelLookup['session'] = SSHSession
-
-
- def openShell(self, transport):
- """
- Write 60 lines of data to the transport, then exit.
- """
- proto = protocol.Protocol()
- proto.makeConnection(transport)
- transport.makeConnection(wrapProtocol(proto))
-
- # Send enough bytes to the connection so that a rekey is triggered in
- # the client.
- def write(counter):
- i = counter()
- if i == 60:
- call.stop()
- transport.session.conn.sendRequest(
- transport.session, 'exit-status', '\x00\x00\x00\x00')
- transport.loseConnection()
- else:
- transport.write("line #%02d\n" % (i,))
-
- # The timing for this loop is an educated guess (and/or the result of
- # experimentation) to exercise the case where a packet is generated
- # mid-rekey. Since the other side of the connection is (so far) the
- # OpenSSH command line client, there's no easy way to determine when the
- # rekey has been initiated. If there were, then generating a packet
- # immediately at that time would be a better way to test the
- # functionality being tested here.
- call = LoopingCall(write, count().next)
- call.start(0.01)
-
-
- def closed(self):
- """
- Ignore the close of the session.
- """
-
-
-
-class RekeyRealm:
- """
- This realm gives out new L{RekeyAvatar} instances for any avatar request.
- """
- def requestAvatar(self, avatarID, mind, *interfaces):
- return interfaces[0], RekeyAvatar(), lambda: None
-
-
-
-class RekeyTestsMixin(ConchServerSetupMixin):
- """
- TestCase mixin which defines tests exercising L{SSHTransportBase}'s handling
- of rekeying messages.
- """
- realmFactory = RekeyRealm
-
- def test_clientRekey(self):
- """
- After a client-initiated rekey is completed, application data continues
- to be passed over the SSH connection.
- """
- process = ConchTestOpenSSHProcess()
- d = self.execute("", process, '-o RekeyLimit=2K')
- def finished(result):
- self.assertEqual(
- result,
- '\n'.join(['line #%02d' % (i,) for i in range(60)]) + '\n')
- d.addCallback(finished)
- return d
-
-
-
-class OpenSSHClientMixin:
- if not which('ssh'):
- skip = "no ssh command-line client available"
-
- def execute(self, remoteCommand, process, sshArgs=''):
- """
- Connects to the SSH server started in L{ConchServerSetupMixin.setUp} by
- running the 'ssh' command line tool.
-
- @type remoteCommand: str
- @param remoteCommand: The command (with arguments) to run on the
- remote end.
-
- @type process: L{ConchTestOpenSSHProcess}
-
- @type sshArgs: str
- @param sshArgs: Arguments to pass to the 'ssh' process.
-
- @return: L{defer.Deferred}
- """
- process.deferred = defer.Deferred()
- cmdline = ('ssh -2 -l testuser -p %i '
- '-oUserKnownHostsFile=kh_test '
- '-oPasswordAuthentication=no '
- # Always use the RSA key, since that's the one in kh_test.
- '-oHostKeyAlgorithms=ssh-rsa '
- '-a '
- '-i dsa_test ') + sshArgs + \
- ' 127.0.0.1 ' + remoteCommand
- port = self.conchServer.getHost().port
- cmds = (cmdline % port).split()
- reactor.spawnProcess(process, "ssh", cmds)
- return process.deferred
-
-
-
-class OpenSSHClientForwardingTestCase(ForwardingMixin, OpenSSHClientMixin,
- unittest.TestCase):
- """
- Connection forwarding tests run against the OpenSSL command line client.
- """
-
-
-
-class OpenSSHClientRekeyTestCase(RekeyTestsMixin, OpenSSHClientMixin,
- unittest.TestCase):
- """
- Rekeying tests run against the OpenSSL command line client.
- """
-
-
-
-class CmdLineClientTestCase(ForwardingMixin, unittest.TestCase):
- """
- Connection forwarding tests run against the Conch command line client.
- """
- if runtime.platformType == 'win32':
- skip = "can't run cmdline client on win32"
-
- def execute(self, remoteCommand, process, sshArgs=''):
- """
- As for L{OpenSSHClientTestCase.execute}, except it runs the 'conch'
- command line tool, not 'ssh'.
- """
- process.deferred = defer.Deferred()
- port = self.conchServer.getHost().port
- cmd = ('-p %i -l testuser '
- '--known-hosts kh_test '
- '--user-authentications publickey '
- '--host-key-algorithms ssh-rsa '
- '-a '
- '-i dsa_test '
- '-v ') % port + sshArgs + \
- ' 127.0.0.1 ' + remoteCommand
- cmds = _makeArgs(cmd.split())
- log.msg(str(cmds))
- env = os.environ.copy()
- env['PYTHONPATH'] = os.pathsep.join(sys.path)
- reactor.spawnProcess(process, sys.executable, cmds, env=env)
- return process.deferred
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_connection.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_connection.py
deleted file mode 100644
index 4038e4d..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_connection.py
+++ /dev/null
@@ -1,730 +0,0 @@
-# Copyright (c) 2007-2010 Twisted Matrix Laboratories.
-# See LICENSE for details
-
-"""
-This module tests twisted.conch.ssh.connection.
-"""
-
-import struct
-
-from twisted.conch import error
-from twisted.conch.ssh import channel, common, connection
-from twisted.trial import unittest
-from twisted.conch.test import test_userauth
-
-
-class TestChannel(channel.SSHChannel):
- """
- A mocked-up version of twisted.conch.ssh.channel.SSHChannel.
-
- @ivar gotOpen: True if channelOpen has been called.
- @type gotOpen: C{bool}
- @ivar specificData: the specific channel open data passed to channelOpen.
- @type specificData: C{str}
- @ivar openFailureReason: the reason passed to openFailed.
- @type openFailed: C{error.ConchError}
- @ivar inBuffer: a C{list} of strings received by the channel.
- @type inBuffer: C{list}
- @ivar extBuffer: a C{list} of 2-tuples (type, extended data) of received by
- the channel.
- @type extBuffer: C{list}
- @ivar numberRequests: the number of requests that have been made to this
- channel.
- @type numberRequests: C{int}
- @ivar gotEOF: True if the other side sent EOF.
- @type gotEOF: C{bool}
- @ivar gotOneClose: True if the other side closed the connection.
- @type gotOneClose: C{bool}
- @ivar gotClosed: True if the channel is closed.
- @type gotClosed: C{bool}
- """
- name = "TestChannel"
- gotOpen = False
-
- def logPrefix(self):
- return "TestChannel %i" % self.id
-
- def channelOpen(self, specificData):
- """
- The channel is open. Set up the instance variables.
- """
- self.gotOpen = True
- self.specificData = specificData
- self.inBuffer = []
- self.extBuffer = []
- self.numberRequests = 0
- self.gotEOF = False
- self.gotOneClose = False
- self.gotClosed = False
-
- def openFailed(self, reason):
- """
- Opening the channel failed. Store the reason why.
- """
- self.openFailureReason = reason
-
- def request_test(self, data):
- """
- A test request. Return True if data is 'data'.
-
- @type data: C{str}
- """
- self.numberRequests += 1
- return data == 'data'
-
- def dataReceived(self, data):
- """
- Data was received. Store it in the buffer.
- """
- self.inBuffer.append(data)
-
- def extReceived(self, code, data):
- """
- Extended data was received. Store it in the buffer.
- """
- self.extBuffer.append((code, data))
-
- def eofReceived(self):
- """
- EOF was received. Remember it.
- """
- self.gotEOF = True
-
- def closeReceived(self):
- """
- Close was received. Remember it.
- """
- self.gotOneClose = True
-
- def closed(self):
- """
- The channel is closed. Rembember it.
- """
- self.gotClosed = True
-
-class TestAvatar:
- """
- A mocked-up version of twisted.conch.avatar.ConchUser
- """
- _ARGS_ERROR_CODE = 123
-
- def lookupChannel(self, channelType, windowSize, maxPacket, data):
- """
- The server wants us to return a channel. If the requested channel is
- our TestChannel, return it, otherwise return None.
- """
- if channelType == TestChannel.name:
- return TestChannel(remoteWindow=windowSize,
- remoteMaxPacket=maxPacket,
- data=data, avatar=self)
- elif channelType == "conch-error-args":
- # Raise a ConchError with backwards arguments to make sure the
- # connection fixes it for us. This case should be deprecated and
- # deleted eventually, but only after all of Conch gets the argument
- # order right.
- raise error.ConchError(
- self._ARGS_ERROR_CODE, "error args in wrong order")
-
-
- def gotGlobalRequest(self, requestType, data):
- """
- The client has made a global request. If the global request is
- 'TestGlobal', return True. If the global request is 'TestData',
- return True and the request-specific data we received. Otherwise,
- return False.
- """
- if requestType == 'TestGlobal':
- return True
- elif requestType == 'TestData':
- return True, data
- else:
- return False
-
-
-
-class TestConnection(connection.SSHConnection):
- """
- A subclass of SSHConnection for testing.
-
- @ivar channel: the current channel.
- @type channel. C{TestChannel}
- """
-
- def logPrefix(self):
- return "TestConnection"
-
- def global_TestGlobal(self, data):
- """
- The other side made the 'TestGlobal' global request. Return True.
- """
- return True
-
- def global_Test_Data(self, data):
- """
- The other side made the 'Test-Data' global request. Return True and
- the data we received.
- """
- return True, data
-
- def channel_TestChannel(self, windowSize, maxPacket, data):
- """
- The other side is requesting the TestChannel. Create a C{TestChannel}
- instance, store it, and return it.
- """
- self.channel = TestChannel(remoteWindow=windowSize,
- remoteMaxPacket=maxPacket, data=data)
- return self.channel
-
- def channel_ErrorChannel(self, windowSize, maxPacket, data):
- """
- The other side is requesting the ErrorChannel. Raise an exception.
- """
- raise AssertionError('no such thing')
-
-
-
-class ConnectionTestCase(unittest.TestCase):
-
- if test_userauth.transport is None:
- skip = "Cannot run without both PyCrypto and pyasn1"
-
- def setUp(self):
- self.transport = test_userauth.FakeTransport(None)
- self.transport.avatar = TestAvatar()
- self.conn = TestConnection()
- self.conn.transport = self.transport
- self.conn.serviceStarted()
-
- def _openChannel(self, channel):
- """
- Open the channel with the default connection.
- """
- self.conn.openChannel(channel)
- self.transport.packets = self.transport.packets[:-1]
- self.conn.ssh_CHANNEL_OPEN_CONFIRMATION(struct.pack('>2L',
- channel.id, 255) + '\x00\x02\x00\x00\x00\x00\x80\x00')
-
- def tearDown(self):
- self.conn.serviceStopped()
-
- def test_linkAvatar(self):
- """
- Test that the connection links itself to the avatar in the
- transport.
- """
- self.assertIs(self.transport.avatar.conn, self.conn)
-
- def test_serviceStopped(self):
- """
- Test that serviceStopped() closes any open channels.
- """
- channel1 = TestChannel()
- channel2 = TestChannel()
- self.conn.openChannel(channel1)
- self.conn.openChannel(channel2)
- self.conn.ssh_CHANNEL_OPEN_CONFIRMATION('\x00\x00\x00\x00' * 4)
- self.assertTrue(channel1.gotOpen)
- self.assertFalse(channel2.gotOpen)
- self.conn.serviceStopped()
- self.assertTrue(channel1.gotClosed)
-
- def test_GLOBAL_REQUEST(self):
- """
- Test that global request packets are dispatched to the global_*
- methods and the return values are translated into success or failure
- messages.
- """
- self.conn.ssh_GLOBAL_REQUEST(common.NS('TestGlobal') + '\xff')
- self.assertEqual(self.transport.packets,
- [(connection.MSG_REQUEST_SUCCESS, '')])
- self.transport.packets = []
- self.conn.ssh_GLOBAL_REQUEST(common.NS('TestData') + '\xff' +
- 'test data')
- self.assertEqual(self.transport.packets,
- [(connection.MSG_REQUEST_SUCCESS, 'test data')])
- self.transport.packets = []
- self.conn.ssh_GLOBAL_REQUEST(common.NS('TestBad') + '\xff')
- self.assertEqual(self.transport.packets,
- [(connection.MSG_REQUEST_FAILURE, '')])
- self.transport.packets = []
- self.conn.ssh_GLOBAL_REQUEST(common.NS('TestGlobal') + '\x00')
- self.assertEqual(self.transport.packets, [])
-
- def test_REQUEST_SUCCESS(self):
- """
- Test that global request success packets cause the Deferred to be
- called back.
- """
- d = self.conn.sendGlobalRequest('request', 'data', True)
- self.conn.ssh_REQUEST_SUCCESS('data')
- def check(data):
- self.assertEqual(data, 'data')
- d.addCallback(check)
- d.addErrback(self.fail)
- return d
-
- def test_REQUEST_FAILURE(self):
- """
- Test that global request failure packets cause the Deferred to be
- erred back.
- """
- d = self.conn.sendGlobalRequest('request', 'data', True)
- self.conn.ssh_REQUEST_FAILURE('data')
- def check(f):
- self.assertEqual(f.value.data, 'data')
- d.addCallback(self.fail)
- d.addErrback(check)
- return d
-
- def test_CHANNEL_OPEN(self):
- """
- Test that open channel packets cause a channel to be created and
- opened or a failure message to be returned.
- """
- del self.transport.avatar
- self.conn.ssh_CHANNEL_OPEN(common.NS('TestChannel') +
- '\x00\x00\x00\x01' * 4)
- self.assertTrue(self.conn.channel.gotOpen)
- self.assertEqual(self.conn.channel.conn, self.conn)
- self.assertEqual(self.conn.channel.data, '\x00\x00\x00\x01')
- self.assertEqual(self.conn.channel.specificData, '\x00\x00\x00\x01')
- self.assertEqual(self.conn.channel.remoteWindowLeft, 1)
- self.assertEqual(self.conn.channel.remoteMaxPacket, 1)
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_OPEN_CONFIRMATION,
- '\x00\x00\x00\x01\x00\x00\x00\x00\x00\x02\x00\x00'
- '\x00\x00\x80\x00')])
- self.transport.packets = []
- self.conn.ssh_CHANNEL_OPEN(common.NS('BadChannel') +
- '\x00\x00\x00\x02' * 4)
- self.flushLoggedErrors()
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_OPEN_FAILURE,
- '\x00\x00\x00\x02\x00\x00\x00\x03' + common.NS(
- 'unknown channel') + common.NS(''))])
- self.transport.packets = []
- self.conn.ssh_CHANNEL_OPEN(common.NS('ErrorChannel') +
- '\x00\x00\x00\x02' * 4)
- self.flushLoggedErrors()
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_OPEN_FAILURE,
- '\x00\x00\x00\x02\x00\x00\x00\x02' + common.NS(
- 'unknown failure') + common.NS(''))])
-
-
- def _lookupChannelErrorTest(self, code):
- """
- Deliver a request for a channel open which will result in an exception
- being raised during channel lookup. Assert that an error response is
- delivered as a result.
- """
- self.transport.avatar._ARGS_ERROR_CODE = code
- self.conn.ssh_CHANNEL_OPEN(
- common.NS('conch-error-args') + '\x00\x00\x00\x01' * 4)
- errors = self.flushLoggedErrors(error.ConchError)
- self.assertEqual(
- len(errors), 1, "Expected one error, got: %r" % (errors,))
- self.assertEqual(errors[0].value.args, (123, "error args in wrong order"))
- self.assertEqual(
- self.transport.packets,
- [(connection.MSG_CHANNEL_OPEN_FAILURE,
- # The response includes some bytes which identifying the
- # associated request, as well as the error code (7b in hex) and
- # the error message.
- '\x00\x00\x00\x01\x00\x00\x00\x7b' + common.NS(
- 'error args in wrong order') + common.NS(''))])
-
-
- def test_lookupChannelError(self):
- """
- If a C{lookupChannel} implementation raises L{error.ConchError} with the
- arguments in the wrong order, a C{MSG_CHANNEL_OPEN} failure is still
- sent in response to the message.
-
- This is a temporary work-around until L{error.ConchError} is given
- better attributes and all of the Conch code starts constructing
- instances of it properly. Eventually this functionality should be
- deprecated and then removed.
- """
- self._lookupChannelErrorTest(123)
-
-
- def test_lookupChannelErrorLongCode(self):
- """
- Like L{test_lookupChannelError}, but for the case where the failure code
- is represented as a C{long} instead of a C{int}.
- """
- self._lookupChannelErrorTest(123L)
-
-
- def test_CHANNEL_OPEN_CONFIRMATION(self):
- """
- Test that channel open confirmation packets cause the channel to be
- notified that it's open.
- """
- channel = TestChannel()
- self.conn.openChannel(channel)
- self.conn.ssh_CHANNEL_OPEN_CONFIRMATION('\x00\x00\x00\x00'*5)
- self.assertEqual(channel.remoteWindowLeft, 0)
- self.assertEqual(channel.remoteMaxPacket, 0)
- self.assertEqual(channel.specificData, '\x00\x00\x00\x00')
- self.assertEqual(self.conn.channelsToRemoteChannel[channel],
- 0)
- self.assertEqual(self.conn.localToRemoteChannel[0], 0)
-
- def test_CHANNEL_OPEN_FAILURE(self):
- """
- Test that channel open failure packets cause the channel to be
- notified that its opening failed.
- """
- channel = TestChannel()
- self.conn.openChannel(channel)
- self.conn.ssh_CHANNEL_OPEN_FAILURE('\x00\x00\x00\x00\x00\x00\x00'
- '\x01' + common.NS('failure!'))
- self.assertEqual(channel.openFailureReason.args, ('failure!', 1))
- self.assertEqual(self.conn.channels.get(channel), None)
-
-
- def test_CHANNEL_WINDOW_ADJUST(self):
- """
- Test that channel window adjust messages add bytes to the channel
- window.
- """
- channel = TestChannel()
- self._openChannel(channel)
- oldWindowSize = channel.remoteWindowLeft
- self.conn.ssh_CHANNEL_WINDOW_ADJUST('\x00\x00\x00\x00\x00\x00\x00'
- '\x01')
- self.assertEqual(channel.remoteWindowLeft, oldWindowSize + 1)
-
- def test_CHANNEL_DATA(self):
- """
- Test that channel data messages are passed up to the channel, or
- cause the channel to be closed if the data is too large.
- """
- channel = TestChannel(localWindow=6, localMaxPacket=5)
- self._openChannel(channel)
- self.conn.ssh_CHANNEL_DATA('\x00\x00\x00\x00' + common.NS('data'))
- self.assertEqual(channel.inBuffer, ['data'])
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_WINDOW_ADJUST, '\x00\x00\x00\xff'
- '\x00\x00\x00\x04')])
- self.transport.packets = []
- longData = 'a' * (channel.localWindowLeft + 1)
- self.conn.ssh_CHANNEL_DATA('\x00\x00\x00\x00' + common.NS(longData))
- self.assertEqual(channel.inBuffer, ['data'])
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_CLOSE, '\x00\x00\x00\xff')])
- channel = TestChannel()
- self._openChannel(channel)
- bigData = 'a' * (channel.localMaxPacket + 1)
- self.transport.packets = []
- self.conn.ssh_CHANNEL_DATA('\x00\x00\x00\x01' + common.NS(bigData))
- self.assertEqual(channel.inBuffer, [])
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_CLOSE, '\x00\x00\x00\xff')])
-
- def test_CHANNEL_EXTENDED_DATA(self):
- """
- Test that channel extended data messages are passed up to the channel,
- or cause the channel to be closed if they're too big.
- """
- channel = TestChannel(localWindow=6, localMaxPacket=5)
- self._openChannel(channel)
- self.conn.ssh_CHANNEL_EXTENDED_DATA('\x00\x00\x00\x00\x00\x00\x00'
- '\x00' + common.NS('data'))
- self.assertEqual(channel.extBuffer, [(0, 'data')])
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_WINDOW_ADJUST, '\x00\x00\x00\xff'
- '\x00\x00\x00\x04')])
- self.transport.packets = []
- longData = 'a' * (channel.localWindowLeft + 1)
- self.conn.ssh_CHANNEL_EXTENDED_DATA('\x00\x00\x00\x00\x00\x00\x00'
- '\x00' + common.NS(longData))
- self.assertEqual(channel.extBuffer, [(0, 'data')])
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_CLOSE, '\x00\x00\x00\xff')])
- channel = TestChannel()
- self._openChannel(channel)
- bigData = 'a' * (channel.localMaxPacket + 1)
- self.transport.packets = []
- self.conn.ssh_CHANNEL_EXTENDED_DATA('\x00\x00\x00\x01\x00\x00\x00'
- '\x00' + common.NS(bigData))
- self.assertEqual(channel.extBuffer, [])
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_CLOSE, '\x00\x00\x00\xff')])
-
- def test_CHANNEL_EOF(self):
- """
- Test that channel eof messages are passed up to the channel.
- """
- channel = TestChannel()
- self._openChannel(channel)
- self.conn.ssh_CHANNEL_EOF('\x00\x00\x00\x00')
- self.assertTrue(channel.gotEOF)
-
- def test_CHANNEL_CLOSE(self):
- """
- Test that channel close messages are passed up to the channel. Also,
- test that channel.close() is called if both sides are closed when this
- message is received.
- """
- channel = TestChannel()
- self._openChannel(channel)
- self.conn.sendClose(channel)
- self.conn.ssh_CHANNEL_CLOSE('\x00\x00\x00\x00')
- self.assertTrue(channel.gotOneClose)
- self.assertTrue(channel.gotClosed)
-
- def test_CHANNEL_REQUEST_success(self):
- """
- Test that channel requests that succeed send MSG_CHANNEL_SUCCESS.
- """
- channel = TestChannel()
- self._openChannel(channel)
- self.conn.ssh_CHANNEL_REQUEST('\x00\x00\x00\x00' + common.NS('test')
- + '\x00')
- self.assertEqual(channel.numberRequests, 1)
- d = self.conn.ssh_CHANNEL_REQUEST('\x00\x00\x00\x00' + common.NS(
- 'test') + '\xff' + 'data')
- def check(result):
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_SUCCESS, '\x00\x00\x00\xff')])
- d.addCallback(check)
- return d
-
- def test_CHANNEL_REQUEST_failure(self):
- """
- Test that channel requests that fail send MSG_CHANNEL_FAILURE.
- """
- channel = TestChannel()
- self._openChannel(channel)
- d = self.conn.ssh_CHANNEL_REQUEST('\x00\x00\x00\x00' + common.NS(
- 'test') + '\xff')
- def check(result):
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_FAILURE, '\x00\x00\x00\xff'
- )])
- d.addCallback(self.fail)
- d.addErrback(check)
- return d
-
- def test_CHANNEL_REQUEST_SUCCESS(self):
- """
- Test that channel request success messages cause the Deferred to be
- called back.
- """
- channel = TestChannel()
- self._openChannel(channel)
- d = self.conn.sendRequest(channel, 'test', 'data', True)
- self.conn.ssh_CHANNEL_SUCCESS('\x00\x00\x00\x00')
- def check(result):
- self.assertTrue(result)
- return d
-
- def test_CHANNEL_REQUEST_FAILURE(self):
- """
- Test that channel request failure messages cause the Deferred to be
- erred back.
- """
- channel = TestChannel()
- self._openChannel(channel)
- d = self.conn.sendRequest(channel, 'test', '', True)
- self.conn.ssh_CHANNEL_FAILURE('\x00\x00\x00\x00')
- def check(result):
- self.assertEqual(result.value.value, 'channel request failed')
- d.addCallback(self.fail)
- d.addErrback(check)
- return d
-
- def test_sendGlobalRequest(self):
- """
- Test that global request messages are sent in the right format.
- """
- d = self.conn.sendGlobalRequest('wantReply', 'data', True)
- # must be added to prevent errbacking during teardown
- d.addErrback(lambda failure: None)
- self.conn.sendGlobalRequest('noReply', '', False)
- self.assertEqual(self.transport.packets,
- [(connection.MSG_GLOBAL_REQUEST, common.NS('wantReply') +
- '\xffdata'),
- (connection.MSG_GLOBAL_REQUEST, common.NS('noReply') +
- '\x00')])
- self.assertEqual(self.conn.deferreds, {'global':[d]})
-
- def test_openChannel(self):
- """
- Test that open channel messages are sent in the right format.
- """
- channel = TestChannel()
- self.conn.openChannel(channel, 'aaaa')
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_OPEN, common.NS('TestChannel') +
- '\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x80\x00aaaa')])
- self.assertEqual(channel.id, 0)
- self.assertEqual(self.conn.localChannelID, 1)
-
- def test_sendRequest(self):
- """
- Test that channel request messages are sent in the right format.
- """
- channel = TestChannel()
- self._openChannel(channel)
- d = self.conn.sendRequest(channel, 'test', 'test', True)
- # needed to prevent errbacks during teardown.
- d.addErrback(lambda failure: None)
- self.conn.sendRequest(channel, 'test2', '', False)
- channel.localClosed = True # emulate sending a close message
- self.conn.sendRequest(channel, 'test3', '', True)
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_REQUEST, '\x00\x00\x00\xff' +
- common.NS('test') + '\x01test'),
- (connection.MSG_CHANNEL_REQUEST, '\x00\x00\x00\xff' +
- common.NS('test2') + '\x00')])
- self.assertEqual(self.conn.deferreds[0], [d])
-
- def test_adjustWindow(self):
- """
- Test that channel window adjust messages cause bytes to be added
- to the window.
- """
- channel = TestChannel(localWindow=5)
- self._openChannel(channel)
- channel.localWindowLeft = 0
- self.conn.adjustWindow(channel, 1)
- self.assertEqual(channel.localWindowLeft, 1)
- channel.localClosed = True
- self.conn.adjustWindow(channel, 2)
- self.assertEqual(channel.localWindowLeft, 1)
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_WINDOW_ADJUST, '\x00\x00\x00\xff'
- '\x00\x00\x00\x01')])
-
- def test_sendData(self):
- """
- Test that channel data messages are sent in the right format.
- """
- channel = TestChannel()
- self._openChannel(channel)
- self.conn.sendData(channel, 'a')
- channel.localClosed = True
- self.conn.sendData(channel, 'b')
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_DATA, '\x00\x00\x00\xff' +
- common.NS('a'))])
-
- def test_sendExtendedData(self):
- """
- Test that channel extended data messages are sent in the right format.
- """
- channel = TestChannel()
- self._openChannel(channel)
- self.conn.sendExtendedData(channel, 1, 'test')
- channel.localClosed = True
- self.conn.sendExtendedData(channel, 2, 'test2')
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_EXTENDED_DATA, '\x00\x00\x00\xff' +
- '\x00\x00\x00\x01' + common.NS('test'))])
-
- def test_sendEOF(self):
- """
- Test that channel EOF messages are sent in the right format.
- """
- channel = TestChannel()
- self._openChannel(channel)
- self.conn.sendEOF(channel)
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_EOF, '\x00\x00\x00\xff')])
- channel.localClosed = True
- self.conn.sendEOF(channel)
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_EOF, '\x00\x00\x00\xff')])
-
- def test_sendClose(self):
- """
- Test that channel close messages are sent in the right format.
- """
- channel = TestChannel()
- self._openChannel(channel)
- self.conn.sendClose(channel)
- self.assertTrue(channel.localClosed)
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_CLOSE, '\x00\x00\x00\xff')])
- self.conn.sendClose(channel)
- self.assertEqual(self.transport.packets,
- [(connection.MSG_CHANNEL_CLOSE, '\x00\x00\x00\xff')])
-
- channel2 = TestChannel()
- self._openChannel(channel2)
- channel2.remoteClosed = True
- self.conn.sendClose(channel2)
- self.assertTrue(channel2.gotClosed)
-
- def test_getChannelWithAvatar(self):
- """
- Test that getChannel dispatches to the avatar when an avatar is
- present. Correct functioning without the avatar is verified in
- test_CHANNEL_OPEN.
- """
- channel = self.conn.getChannel('TestChannel', 50, 30, 'data')
- self.assertEqual(channel.data, 'data')
- self.assertEqual(channel.remoteWindowLeft, 50)
- self.assertEqual(channel.remoteMaxPacket, 30)
- self.assertRaises(error.ConchError, self.conn.getChannel,
- 'BadChannel', 50, 30, 'data')
-
- def test_gotGlobalRequestWithoutAvatar(self):
- """
- Test that gotGlobalRequests dispatches to global_* without an avatar.
- """
- del self.transport.avatar
- self.assertTrue(self.conn.gotGlobalRequest('TestGlobal', 'data'))
- self.assertEqual(self.conn.gotGlobalRequest('Test-Data', 'data'),
- (True, 'data'))
- self.assertFalse(self.conn.gotGlobalRequest('BadGlobal', 'data'))
-
-
- def test_channelClosedCausesLeftoverChannelDeferredsToErrback(self):
- """
- Whenever an SSH channel gets closed any Deferred that was returned by a
- sendRequest() on its parent connection must be errbacked.
- """
- channel = TestChannel()
- self._openChannel(channel)
-
- d = self.conn.sendRequest(
- channel, "dummyrequest", "dummydata", wantReply=1)
- d = self.assertFailure(d, error.ConchError)
- self.conn.channelClosed(channel)
- return d
-
-
-
-class TestCleanConnectionShutdown(unittest.TestCase):
- """
- Check whether correct cleanup is performed on connection shutdown.
- """
- if test_userauth.transport is None:
- skip = "Cannot run without both PyCrypto and pyasn1"
-
- def setUp(self):
- self.transport = test_userauth.FakeTransport(None)
- self.transport.avatar = TestAvatar()
- self.conn = TestConnection()
- self.conn.transport = self.transport
-
-
- def test_serviceStoppedCausesLeftoverGlobalDeferredsToErrback(self):
- """
- Once the service is stopped any leftover global deferred returned by
- a sendGlobalRequest() call must be errbacked.
- """
- self.conn.serviceStarted()
-
- d = self.conn.sendGlobalRequest(
- "dummyrequest", "dummydata", wantReply=1)
- d = self.assertFailure(d, error.ConchError)
- self.conn.serviceStopped()
- return d
-
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_default.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_default.py
deleted file mode 100644
index 109f23d..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_default.py
+++ /dev/null
@@ -1,171 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.client.default}.
-"""
-try:
- import Crypto.Cipher.DES3
- import pyasn1
-except ImportError:
- skip = "PyCrypto and PyASN1 required for twisted.conch.client.default."
-else:
- from twisted.conch.client.agent import SSHAgentClient
- from twisted.conch.client.default import SSHUserAuthClient
- from twisted.conch.client.options import ConchOptions
- from twisted.conch.ssh.keys import Key
-
-
-from twisted.trial.unittest import TestCase
-from twisted.python.filepath import FilePath
-from twisted.conch.test import keydata
-from twisted.test.proto_helpers import StringTransport
-
-
-
-class SSHUserAuthClientTest(TestCase):
- """
- Tests for L{SSHUserAuthClient}.
-
- @type rsaPublic: L{Key}
- @ivar rsaPublic: A public RSA key.
- """
-
- def setUp(self):
- self.rsaPublic = Key.fromString(keydata.publicRSA_openssh)
- self.tmpdir = FilePath(self.mktemp())
- self.tmpdir.makedirs()
- self.rsaFile = self.tmpdir.child('id_rsa')
- self.rsaFile.setContent(keydata.privateRSA_openssh)
- self.tmpdir.child('id_rsa.pub').setContent(keydata.publicRSA_openssh)
-
-
- def test_signDataWithAgent(self):
- """
- When connected to an agent, L{SSHUserAuthClient} can use it to
- request signatures of particular data with a particular L{Key}.
- """
- client = SSHUserAuthClient("user", ConchOptions(), None)
- agent = SSHAgentClient()
- transport = StringTransport()
- agent.makeConnection(transport)
- client.keyAgent = agent
- cleartext = "Sign here"
- client.signData(self.rsaPublic, cleartext)
- self.assertEqual(
- transport.value(),
- "\x00\x00\x00\x8b\r\x00\x00\x00u" + self.rsaPublic.blob() +
- "\x00\x00\x00\t" + cleartext +
- "\x00\x00\x00\x00")
-
-
- def test_agentGetPublicKey(self):
- """
- L{SSHUserAuthClient} looks up public keys from the agent using the
- L{SSHAgentClient} class. That L{SSHAgentClient.getPublicKey} returns a
- L{Key} object with one of the public keys in the agent. If no more
- keys are present, it returns C{None}.
- """
- agent = SSHAgentClient()
- agent.blobs = [self.rsaPublic.blob()]
- key = agent.getPublicKey()
- self.assertEqual(key.isPublic(), True)
- self.assertEqual(key, self.rsaPublic)
- self.assertEqual(agent.getPublicKey(), None)
-
-
- def test_getPublicKeyFromFile(self):
- """
- L{SSHUserAuthClient.getPublicKey()} is able to get a public key from
- the first file described by its options' C{identitys} list, and return
- the corresponding public L{Key} object.
- """
- options = ConchOptions()
- options.identitys = [self.rsaFile.path]
- client = SSHUserAuthClient("user", options, None)
- key = client.getPublicKey()
- self.assertEqual(key.isPublic(), True)
- self.assertEqual(key, self.rsaPublic)
-
-
- def test_getPublicKeyAgentFallback(self):
- """
- If an agent is present, but doesn't return a key,
- L{SSHUserAuthClient.getPublicKey} continue with the normal key lookup.
- """
- options = ConchOptions()
- options.identitys = [self.rsaFile.path]
- agent = SSHAgentClient()
- client = SSHUserAuthClient("user", options, None)
- client.keyAgent = agent
- key = client.getPublicKey()
- self.assertEqual(key.isPublic(), True)
- self.assertEqual(key, self.rsaPublic)
-
-
- def test_getPublicKeyBadKeyError(self):
- """
- If L{keys.Key.fromFile} raises a L{keys.BadKeyError}, the
- L{SSHUserAuthClient.getPublicKey} tries again to get a public key by
- calling itself recursively.
- """
- options = ConchOptions()
- self.tmpdir.child('id_dsa.pub').setContent(keydata.publicDSA_openssh)
- dsaFile = self.tmpdir.child('id_dsa')
- dsaFile.setContent(keydata.privateDSA_openssh)
- options.identitys = [self.rsaFile.path, dsaFile.path]
- self.tmpdir.child('id_rsa.pub').setContent('not a key!')
- client = SSHUserAuthClient("user", options, None)
- key = client.getPublicKey()
- self.assertEqual(key.isPublic(), True)
- self.assertEqual(key, Key.fromString(keydata.publicDSA_openssh))
- self.assertEqual(client.usedFiles, [self.rsaFile.path, dsaFile.path])
-
-
- def test_getPrivateKey(self):
- """
- L{SSHUserAuthClient.getPrivateKey} will load a private key from the
- last used file populated by L{SSHUserAuthClient.getPublicKey}, and
- return a L{Deferred} which fires with the corresponding private L{Key}.
- """
- rsaPrivate = Key.fromString(keydata.privateRSA_openssh)
- options = ConchOptions()
- options.identitys = [self.rsaFile.path]
- client = SSHUserAuthClient("user", options, None)
- # Populate the list of used files
- client.getPublicKey()
-
- def _cbGetPrivateKey(key):
- self.assertEqual(key.isPublic(), False)
- self.assertEqual(key, rsaPrivate)
-
- return client.getPrivateKey().addCallback(_cbGetPrivateKey)
-
-
- def test_getPrivateKeyPassphrase(self):
- """
- L{SSHUserAuthClient} can get a private key from a file, and return a
- Deferred called back with a private L{Key} object, even if the key is
- encrypted.
- """
- rsaPrivate = Key.fromString(keydata.privateRSA_openssh)
- passphrase = 'this is the passphrase'
- self.rsaFile.setContent(rsaPrivate.toString('openssh', passphrase))
- options = ConchOptions()
- options.identitys = [self.rsaFile.path]
- client = SSHUserAuthClient("user", options, None)
- # Populate the list of used files
- client.getPublicKey()
-
- def _getPassword(prompt):
- self.assertEqual(prompt,
- "Enter passphrase for key '%s': " % (
- self.rsaFile.path,))
- return passphrase
-
- def _cbGetPrivateKey(key):
- self.assertEqual(key.isPublic(), False)
- self.assertEqual(key, rsaPrivate)
-
- self.patch(client, '_getPassword', _getPassword)
- return client.getPrivateKey().addCallback(_cbGetPrivateKey)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_endpoints.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_endpoints.py
deleted file mode 100644
index 8597061..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_endpoints.py
+++ /dev/null
@@ -1,1492 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.endpoints}.
-"""
-
-import os.path
-from struct import pack
-from errno import ENOSYS
-
-from zope.interface.verify import verifyObject, verifyClass
-from zope.interface import implementer
-
-from twisted.python.log import msg
-from twisted.python.filepath import FilePath
-from twisted.python.failure import Failure
-from twisted.internet.interfaces import IAddress, IStreamClientEndpoint
-from twisted.internet.protocol import Factory, Protocol
-from twisted.internet.defer import CancelledError, Deferred, succeed, fail
-from twisted.internet.error import ConnectionDone, ConnectionRefusedError
-from twisted.internet.address import IPv4Address
-from twisted.trial.unittest import TestCase
-from twisted.test.proto_helpers import MemoryReactorClock
-from twisted.internet.error import ProcessTerminated, ConnectingCancelledError
-
-from twisted.cred.portal import Portal
-from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
-
-from twisted.conch.interfaces import IConchUser
-from twisted.conch.error import ConchError, UserRejectedKey, HostKeyChanged
-
-try:
- from Crypto.Cipher import AES
- from pyasn1 import type
-except ImportError as e:
- skip = "can't run w/o PyCrypto and pyasn1 (%s)" % (e,)
- SSHFactory = SSHUserAuthServer = SSHConnection = Key = SSHChannel = \
- SSHAgentServer = KnownHostsFile = SSHPublicKeyDatabase = ConchUser = \
- object
-else:
- from twisted.conch.ssh.factory import SSHFactory
- from twisted.conch.ssh.userauth import SSHUserAuthServer
- from twisted.conch.ssh.connection import SSHConnection
- from twisted.conch.ssh.keys import Key
- from twisted.conch.ssh.channel import SSHChannel
- from twisted.conch.ssh.agent import SSHAgentServer
- from twisted.conch.client.knownhosts import KnownHostsFile, ConsoleUI
- from twisted.conch.checkers import SSHPublicKeyDatabase
- from twisted.conch.avatar import ConchUser
-
- from twisted.conch.test.keydata import (
- publicRSA_openssh, privateRSA_openssh, privateDSA_openssh)
-
- from twisted.conch.endpoints import (
- _ISSHConnectionCreator, AuthenticationFailed, SSHCommandAddress,
- SSHCommandClientEndpoint, _ReadFile, _NewConnectionHelper,
- _ExistingConnectionHelper)
-
- from twisted.conch.ssh.transport import SSHClientTransport
-
-from twisted.python.fakepwd import UserDatabase
-from twisted.test.proto_helpers import StringTransport
-from twisted.test.iosim import FakeTransport, connect
-
-
-class AbortableFakeTransport(FakeTransport):
- """
- A L{FakeTransport} with added C{abortConnection} support.
- """
- aborted = False
-
-
- def abortConnection(self):
- """
- Abort the connection in a fake manner.
-
- This should really be implemented in the underlying module.
- """
- self.aborted = True
-
-
-
-class BrokenExecSession(SSHChannel):
- """
- L{BrokenExecSession} is a session on which exec requests always fail.
- """
- def request_exec(self, data):
- """
- Fail all exec requests.
-
- @param data: Information about what is being executed.
- @type data: L{bytes}
-
- @return: C{0} to indicate failure
- @rtype: L{int}
- """
- return 0
-
-
-
-class WorkingExecSession(SSHChannel):
- """
- L{WorkingExecSession} is a session on which exec requests always succeed.
- """
- def request_exec(self, data):
- """
- Succeed all exec requests.
-
- @param data: Information about what is being executed.
- @type data: L{bytes}
-
- @return: C{1} to indicate success
- @rtype: L{int}
- """
- return 1
-
-
-
-class UnsatisfiedExecSession(SSHChannel):
- """
- L{UnsatisfiedExecSession} is a session on which exec requests are always
- delayed indefinitely, never succeeding or failing.
- """
- def request_exec(self, data):
- """
- Delay all exec requests indefinitely.
-
- @param data: Information about what is being executed.
- @type data: L{bytes}
-
- @return: A L{Deferred} which will never fire.
- @rtype: L{Deferred}
- """
- return Deferred()
-
-
-
-class TrivialRealm(object):
- def __init__(self):
- self.channelLookup = {}
-
-
- def requestAvatar(self, avatarId, mind, *interfaces):
- avatar = ConchUser()
- avatar.channelLookup = self.channelLookup
- return (IConchUser, avatar, lambda: None)
-
-
-
-class AddressSpyFactory(Factory):
- address = None
-
- def buildProtocol(self, address):
- self.address = address
- return Factory.buildProtocol(self, address)
-
-
-
-class FixedResponseUI(object):
- def __init__(self, result):
- self.result = result
-
-
- def prompt(self, text):
- return succeed(self.result)
-
-
- def warn(self, text):
- pass
-
-
-
-class FakeClockSSHUserAuthServer(SSHUserAuthServer):
-
- # Delegate this setting to the factory to simplify tweaking it
- @property
- def attemptsBeforeDisconnect(self):
- """
- Use the C{attemptsBeforeDisconnect} value defined by the factory to make
- it easier to override.
- """
- return self.transport.factory.attemptsBeforeDisconnect
-
-
- @property
- def clock(self):
- """
- Use the reactor defined by the factory, rather than the default global
- reactor, to simplify testing (by allowing an alternate implementation
- to be supplied by tests).
- """
- return self.transport.factory.reactor
-
-
-
-class CommandFactory(SSHFactory):
- @property
- def publicKeys(self):
- return {
- 'ssh-rsa': Key.fromString(data=publicRSA_openssh)
- }
-
- @property
- def privateKeys(self):
- return {
- 'ssh-rsa': Key.fromString(data=privateRSA_openssh)
- }
-
- services = {
- 'ssh-userauth': FakeClockSSHUserAuthServer,
- 'ssh-connection': SSHConnection
- }
-
- # Simplify the tests by disconnecting after the first authentication
- # failure. One attempt should be sufficient to test authentication success
- # and failure. There is an off-by-one in the implementation of this
- # feature in Conch, so set it to 0 in order to allow 1 attempt.
- attemptsBeforeDisconnect = 0
-
-
-@implementer(IAddress)
-class MemoryAddress(object):
- pass
-
-
-
-@implementer(IStreamClientEndpoint)
-class SingleUseMemoryEndpoint(object):
- """
- L{SingleUseMemoryEndpoint} is a client endpoint which allows one connection
- to be set up and then exposes an API for moving around bytes related to
- that connection.
-
- @ivar pump: L{None} until a connection is attempted, then a L{IOPump}
- instance associated with the protocol which is connected.
- @type pump: L{IOPump}
- """
- def __init__(self, server):
- """
- @param server: An L{IProtocol} provider to which the client will be
- connected.
- @type server: L{IProtocol} provider
- """
- self.pump = None
- self._server = server
-
-
- def connect(self, factory):
- if self.pump is not None:
- raise Exception("SingleUseMemoryEndpoint was already used")
-
- try:
- protocol = factory.buildProtocol(MemoryAddress())
- except:
- return fail()
- else:
- self.pump = connect(
- self._server, AbortableFakeTransport(
- self._server, isServer=True),
- protocol, AbortableFakeTransport(protocol, isServer=False))
- return succeed(protocol)
-
-
-
-class MemorySSHPublicKeyDatabase(SSHPublicKeyDatabase):
- def __init__(self, users):
- self._users = users
- self._userdb = UserDatabase()
- for i, username in enumerate(self._users):
- self._userdb.addUser(
- username, b"garbage", 123 + i, 456, None, None, None)
-
-
- def getAuthorizedKeysFiles(self, credentials):
- try:
- return self._users[credentials.username]
- except KeyError:
- return []
-
-
-
-class SSHCommandClientEndpointTestsMixin(object):
- """
- Tests for L{SSHCommandClientEndpoint}, an L{IStreamClientEndpoint}
- implementations which connects a protocol with the stdin and stdout of a
- command running in an SSH session.
-
- These tests apply to L{SSHCommandClientEndpoint} whether it is constructed
- using L{SSHCommandClientEndpoint.existingConnection} or
- L{SSHCommandClientEndpoint.newConnection}.
-
- Subclasses must override L{create}, L{assertClientTransportState}, and
- L{finishConnection}.
- """
- def setUp(self):
- self.hostname = b"ssh.example.com"
- self.port = 42022
- self.user = b"user"
- self.password = b"password"
- self.reactor = MemoryReactorClock()
- self.realm = TrivialRealm()
- self.portal = Portal(self.realm)
- self.passwdDB = InMemoryUsernamePasswordDatabaseDontUse()
- self.passwdDB.addUser(self.user, self.password)
- self.portal.registerChecker(self.passwdDB)
- self.factory = CommandFactory()
- self.factory.reactor = self.reactor
- self.factory.portal = self.portal
- self.factory.doStart()
- self.addCleanup(self.factory.doStop)
-
- self.clientAddress = IPv4Address("TCP", "10.0.0.1", 12345)
- self.serverAddress = IPv4Address("TCP", "192.168.100.200", 54321)
-
-
- def create(self):
- """
- Create and return a new L{SSHCommandClientEndpoint} to be tested.
- Override this to implement creation in an interesting way the endpoint.
- """
- raise NotImplementedError(
- "%r did not implement create" % (self.__class__.__name__,))
-
-
- def assertClientTransportState(self, client, immediateClose):
- """
- Make an assertion about the connectedness of the given protocol's
- transport. Override this to implement either a check for the
- connection still being open or having been closed as appropriate.
-
- @param client: The client whose state is being checked.
-
- @param immediateClose: Boolean indicating whether the connection was
- closed immediately or not.
- """
- raise NotImplementedError(
- "%r did not implement assertClientTransportState" % (
- self.__class__.__name__,))
-
-
- def finishConnection(self):
- """
- Do any remaining work necessary to complete an in-memory connection
- attempted initiated using C{self.reactor}.
- """
- raise NotImplementedError(
- "%r did not implement finishConnection" % (
- self.__class__.__name__,))
-
-
- def connectedServerAndClient(self, serverFactory, clientFactory):
- """
- Set up an in-memory connection between protocols created by
- C{serverFactory} and C{clientFactory}.
-
- @return: A three-tuple. The first element is the protocol created by
- C{serverFactory}. The second element is the protocol created by
- C{clientFactory}. The third element is the L{IOPump} connecting
- them.
- """
- clientProtocol = clientFactory.buildProtocol(None)
- serverProtocol = serverFactory.buildProtocol(None)
-
- clientTransport = AbortableFakeTransport(
- clientProtocol, isServer=False, hostAddress=self.clientAddress,
- peerAddress=self.serverAddress)
- serverTransport = AbortableFakeTransport(
- serverProtocol, isServer=True, hostAddress=self.serverAddress,
- peerAddress=self.clientAddress)
-
- pump = connect(
- serverProtocol, serverTransport, clientProtocol, clientTransport)
- return serverProtocol, clientProtocol, pump
-
-
- def test_channelOpenFailure(self):
- """
- If a channel cannot be opened on the authenticated SSH connection, the
- L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with
- a L{Failure} wrapping the reason given by the server.
- """
- endpoint = self.create()
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.finishConnection()
-
- # The server logs the channel open failure - this is expected.
- errors = self.flushLoggedErrors(ConchError)
- self.assertIn(
- 'unknown channel', (errors[0].value.data, errors[0].value.value))
- self.assertEqual(1, len(errors))
-
- # Now deal with the results on the endpoint side.
- f = self.failureResultOf(connected)
- f.trap(ConchError)
- self.assertEqual('unknown channel', f.value.value)
-
- self.assertClientTransportState(client, False)
-
-
- def test_execFailure(self):
- """
- If execution of the command fails, the L{Deferred} returned by
- L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
- the reason given by the server.
- """
- self.realm.channelLookup[b'session'] = BrokenExecSession
- endpoint = self.create()
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.finishConnection()
-
- f = self.failureResultOf(connected)
- f.trap(ConchError)
- self.assertEqual('channel request failed', f.value.value)
-
- self.assertClientTransportState(client, False)
-
-
- def test_execCancelled(self):
- """
- If execution of the command is cancelled via the L{Deferred} returned
- by L{SSHCommandClientEndpoint.connect}, the connection is closed
- immediately.
- """
- self.realm.channelLookup[b'session'] = UnsatisfiedExecSession
- endpoint = self.create()
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
- server, client, pump = self.finishConnection()
-
- connected.cancel()
-
- f = self.failureResultOf(connected)
- f.trap(CancelledError)
-
- self.assertClientTransportState(client, True)
-
-
- def test_buildProtocol(self):
- """
- Once the necessary SSH actions have completed successfully,
- L{SSHCommandClientEndpoint.connect} uses the factory passed to it to
- construct a protocol instance by calling its C{buildProtocol} method
- with an address object representing the SSH connection and command
- executed.
- """
- self.realm.channelLookup[b'session'] = WorkingExecSession
- endpoint = self.create()
-
- factory = AddressSpyFactory()
- factory.protocol = Protocol
-
- endpoint.connect(factory)
-
- server, client, pump = self.finishConnection()
-
- self.assertIsInstance(factory.address, SSHCommandAddress)
- self.assertEqual(server.transport.getHost(), factory.address.server)
- self.assertEqual(self.user, factory.address.username)
- self.assertEqual(b"/bin/ls -l", factory.address.command)
-
-
- def test_makeConnection(self):
- """
- L{SSHCommandClientEndpoint} establishes an SSH connection, creates a
- channel in it, runs a command in that channel, and uses the protocol's
- C{makeConnection} to associate it with a protocol representing that
- command's stdin and stdout.
- """
- self.realm.channelLookup[b'session'] = WorkingExecSession
- endpoint = self.create()
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.finishConnection()
-
- protocol = self.successResultOf(connected)
- self.assertIsNot(None, protocol.transport)
-
-
- def test_dataReceived(self):
- """
- After establishing the connection, when the command on the SSH server
- produces output, it is delivered to the protocol's C{dataReceived}
- method.
- """
- self.realm.channelLookup[b'session'] = WorkingExecSession
- endpoint = self.create()
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.finishConnection()
-
- protocol = self.successResultOf(connected)
- dataReceived = []
- protocol.dataReceived = dataReceived.append
-
- # Figure out which channel on the connection this protocol is
- # associated with so the test can do a write on it.
- channelId = protocol.transport.id
-
- server.service.channels[channelId].write(b"hello, world")
- pump.pump()
- self.assertEqual(b"hello, world", b"".join(dataReceived))
-
-
- def test_connectionLost(self):
- """
- When the command closes the channel, the protocol's C{connectionLost}
- method is called.
- """
- self.realm.channelLookup[b'session'] = WorkingExecSession
- endpoint = self.create()
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.finishConnection()
-
- protocol = self.successResultOf(connected)
- connectionLost = []
- protocol.connectionLost = connectionLost.append
-
- # Figure out which channel on the connection this protocol is associated
- # with so the test can do a write on it.
- channelId = protocol.transport.id
- server.service.channels[channelId].loseConnection()
-
- pump.pump()
- connectionLost[0].trap(ConnectionDone)
-
- self.assertClientTransportState(client, False)
-
-
- def _exitStatusTest(self, request, requestArg):
- """
- Test handling of non-zero exit statuses or exit signals.
- """
- self.realm.channelLookup[b'session'] = WorkingExecSession
- endpoint = self.create()
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.finishConnection()
-
- protocol = self.successResultOf(connected)
- connectionLost = []
- protocol.connectionLost = connectionLost.append
-
- # Figure out which channel on the connection this protocol is associated
- # with so the test can simulate command exit and channel close.
- channelId = protocol.transport.id
- channel = server.service.channels[channelId]
-
- server.service.sendRequest(channel, request, requestArg)
- channel.loseConnection()
- pump.pump()
- self.assertClientTransportState(client, False)
- return connectionLost[0]
-
-
- def test_zeroExitCode(self):
- """
- When the command exits with a non-zero status, the protocol's
- C{connectionLost} method is called with a L{Failure} wrapping an
- exception which encapsulates that status.
- """
- exitCode = 0
- exc = self._exitStatusTest('exit-status', pack('>L', exitCode))
- exc.trap(ConnectionDone)
-
-
- def test_nonZeroExitStatus(self):
- """
- When the command exits with a non-zero status, the protocol's
- C{connectionLost} method is called with a L{Failure} wrapping an
- exception which encapsulates that status.
- """
- exitCode = 123
- signal = None
- exc = self._exitStatusTest('exit-status', pack('>L', exitCode))
- exc.trap(ProcessTerminated)
- self.assertEqual(exitCode, exc.value.exitCode)
- self.assertEqual(signal, exc.value.signal)
-
-
- def test_nonZeroExitSignal(self):
- """
- When the command exits with a non-zero signal, the protocol's
- C{connectionLost} method is called with a L{Failure} wrapping an
- exception which encapsulates that status.
- """
- exitCode = None
- signal = 123
- exc = self._exitStatusTest('exit-signal', pack('>L', signal))
- exc.trap(ProcessTerminated)
- self.assertEqual(exitCode, exc.value.exitCode)
- self.assertEqual(signal, exc.value.signal)
-
-
- def record(self, server, protocol, event, noArgs=False):
- """
- Hook into and record events which happen to C{protocol}.
-
- @param server: The SSH server protocol over which C{protocol} is
- running.
- @type server: L{IProtocol} provider
-
- @param protocol:
-
- @param event:
-
- @param noArgs:
- """
- # Figure out which channel the test is going to send data over so we can
- # look for it to arrive at the right place on the server.
- channelId = protocol.transport.id
-
- recorder = []
- if noArgs:
- f = lambda: recorder.append(None)
- else:
- f = recorder.append
-
- setattr(server.service.channels[channelId], event, f)
- return recorder
-
-
- def test_write(self):
- """
- The transport connected to the protocol has a C{write} method which
- sends bytes to the input of the command executing on the SSH server.
- """
- self.realm.channelLookup[b'session'] = WorkingExecSession
- endpoint = self.create()
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.finishConnection()
-
- protocol = self.successResultOf(connected)
-
- dataReceived = self.record(server, protocol, 'dataReceived')
- protocol.transport.write(b"hello, world")
- pump.pump()
- self.assertEqual(b"hello, world", b"".join(dataReceived))
-
-
- def test_writeSequence(self):
- """
- The transport connected to the protocol has a C{writeSequence} method which
- sends bytes to the input of the command executing on the SSH server.
- """
- self.realm.channelLookup[b'session'] = WorkingExecSession
- endpoint = self.create()
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.finishConnection()
-
- protocol = self.successResultOf(connected)
-
- dataReceived = self.record(server, protocol, 'dataReceived')
- protocol.transport.writeSequence(list(b"hello, world"))
- pump.pump()
- self.assertEqual(b"hello, world", b"".join(dataReceived))
-
-
-
-class NewConnectionTests(TestCase, SSHCommandClientEndpointTestsMixin):
- """
- Tests for L{SSHCommandClientEndpoint} when using the C{newConnection}
- constructor.
- """
- def setUp(self):
- """
- Configure an SSH server with password authentication enabled for a
- well-known (to the tests) account.
- """
- SSHCommandClientEndpointTestsMixin.setUp(self)
- # Make the server's host key available to be verified by the client.
- self.hostKeyPath = FilePath(self.mktemp())
- self.knownHosts = KnownHostsFile(self.hostKeyPath)
- self.knownHosts.addHostKey(
- self.hostname, self.factory.publicKeys['ssh-rsa'])
- self.knownHosts.addHostKey(
- self.serverAddress.host, self.factory.publicKeys['ssh-rsa'])
- self.knownHosts.save()
-
-
- def create(self):
- """
- Create and return a new L{SSHCommandClientEndpoint} using the
- C{newConnection} constructor.
- """
- return SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
- password=self.password, knownHosts=self.knownHosts,
- ui=FixedResponseUI(False))
-
-
- def finishConnection(self):
- """
- Establish the first attempted TCP connection using the SSH server which
- C{self.factory} can create.
- """
- return self.connectedServerAndClient(
- self.factory, self.reactor.tcpClients[0][2])
-
-
- def assertClientTransportState(self, client, immediateClose):
- """
- Assert that the transport for the given protocol has been disconnected.
- L{SSHCommandClientEndpoint.newConnection} creates a new dedicated SSH
- connection and cleans it up after the command exits.
- """
- # Nothing useful can be done with the connection at this point, so the
- # endpoint should close it.
- if immediateClose:
- self.assertTrue(client.transport.aborted)
- else:
- self.assertTrue(client.transport.disconnecting)
-
-
- def test_interface(self):
- """
- L{SSHCommandClientEndpoint} instances provide L{IStreamClientEndpoint}.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"dummy command", b"dummy user",
- self.hostname, self.port)
- self.assertTrue(verifyObject(IStreamClientEndpoint, endpoint))
-
-
- def test_defaultPort(self):
- """
- L{SSHCommandClientEndpoint} uses the default port number for SSH when
- the C{port} argument is not specified.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"dummy command", b"dummy user", self.hostname)
- self.assertEqual(22, endpoint._creator.port)
-
-
- def test_specifiedPort(self):
- """
- L{SSHCommandClientEndpoint} uses the C{port} argument if specified.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"dummy command", b"dummy user",
- self.hostname, port=2222)
- self.assertEqual(2222, endpoint._creator.port)
-
-
- def test_destination(self):
- """
- L{SSHCommandClientEndpoint} uses the L{IReactorTCP} passed to it to
- attempt a connection to the host/port address also passed to it.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
- password=self.password, knownHosts=self.knownHosts,
- ui=FixedResponseUI(False))
- factory = Factory()
- factory.protocol = Protocol
- endpoint.connect(factory)
-
- host, port, factory, timeout, bindAddress = self.reactor.tcpClients[0]
- self.assertEqual(self.hostname, host)
- self.assertEqual(self.port, port)
- self.assertEqual(1, len(self.reactor.tcpClients))
-
-
- def test_connectionFailed(self):
- """
- If a connection cannot be established, the L{Deferred} returned by
- L{SSHCommandClientEndpoint.connect} fires with a L{Failure}
- representing the reason for the connection setup failure.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", b"dummy user",
- self.hostname, self.port, knownHosts=self.knownHosts,
- ui=FixedResponseUI(False))
- factory = Factory()
- factory.protocol = Protocol
- d = endpoint.connect(factory)
-
- factory = self.reactor.tcpClients[0][2]
- factory.clientConnectionFailed(None, Failure(ConnectionRefusedError()))
-
- self.failureResultOf(d).trap(ConnectionRefusedError)
-
-
- def test_userRejectedHostKey(self):
- """
- If the L{KnownHostsFile} instance used to construct
- L{SSHCommandClientEndpoint} rejects the SSH public key presented by the
- server, the L{Deferred} returned by L{SSHCommandClientEndpoint.connect}
- fires with a L{Failure} wrapping L{UserRejectedKey}.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", b"dummy user",
- self.hostname, self.port, knownHosts=KnownHostsFile(self.mktemp()),
- ui=FixedResponseUI(False))
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.connectedServerAndClient(
- self.factory, self.reactor.tcpClients[0][2])
-
- f = self.failureResultOf(connected)
- f.trap(UserRejectedKey)
-
-
- def test_mismatchedHostKey(self):
- """
- If the SSH public key presented by the SSH server does not match the
- previously remembered key, as reported by the L{KnownHostsFile}
- instance use to construct the endpoint, for that server, the
- L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with
- a L{Failure} wrapping L{HostKeyChanged}.
- """
- differentKey = Key.fromString(privateDSA_openssh).public()
- knownHosts = KnownHostsFile(self.mktemp())
- knownHosts.addHostKey(self.serverAddress.host, differentKey)
- knownHosts.addHostKey(self.hostname, differentKey)
-
- # The UI may answer true to any questions asked of it; they should
- # make no difference, since a *mismatched* key is not even optionally
- # allowed to complete a connection.
- ui = FixedResponseUI(True)
-
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", b"dummy user",
- self.hostname, self.port, password=b"dummy password",
- knownHosts=knownHosts, ui=ui)
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.connectedServerAndClient(
- self.factory, self.reactor.tcpClients[0][2])
-
- f = self.failureResultOf(connected)
- f.trap(HostKeyChanged)
-
-
- def test_connectionClosedBeforeSecure(self):
- """
- If the connection closes at any point before the SSH transport layer
- has finished key exchange (ie, gotten to the point where we may attempt
- to authenticate), the L{Deferred} returned by
- L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
- the reason for the lost connection.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", b"dummy user",
- self.hostname, self.port, knownHosts=self.knownHosts,
- ui=FixedResponseUI(False))
-
- factory = Factory()
- factory.protocol = Protocol
- d = endpoint.connect(factory)
-
- transport = StringTransport()
- factory = self.reactor.tcpClients[0][2]
- client = factory.buildProtocol(None)
- client.makeConnection(transport)
-
- client.connectionLost(Failure(ConnectionDone()))
- self.failureResultOf(d).trap(ConnectionDone)
-
-
- def test_connectionCancelledBeforeSecure(self):
- """
- If the connection is cancelled before the SSH transport layer has
- finished key exchange (ie, gotten to the point where we may attempt to
- authenticate), the L{Deferred} returned by
- L{SSHCommandClientEndpoint.connect} fires with a L{Failure} wrapping
- L{CancelledError} and the connection is aborted.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", b"dummy user",
- self.hostname, self.port, knownHosts=self.knownHosts,
- ui=FixedResponseUI(False))
-
- factory = Factory()
- factory.protocol = Protocol
- d = endpoint.connect(factory)
-
- transport = AbortableFakeTransport(None, isServer=False)
- factory = self.reactor.tcpClients[0][2]
- client = factory.buildProtocol(None)
- client.makeConnection(transport)
- d.cancel()
-
- self.failureResultOf(d).trap(CancelledError)
- self.assertTrue(transport.aborted)
- # Make sure the connection closing doesn't result in unexpected
- # behavior when due to cancellation:
- client.connectionLost(Failure(ConnectionDone()))
-
-
- def test_connectionCancelledBeforeConnected(self):
- """
- If the connection is cancelled before it finishes connecting, the
- connection attempt is stopped.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", b"dummy user",
- self.hostname, self.port, knownHosts=self.knownHosts,
- ui=FixedResponseUI(False))
-
- factory = Factory()
- factory.protocol = Protocol
- d = endpoint.connect(factory)
- d.cancel()
- self.failureResultOf(d).trap(ConnectingCancelledError)
- self.assertTrue(self.reactor.connectors[0].stoppedConnecting)
-
-
- def test_passwordAuthenticationFailure(self):
- """
- If the SSH server rejects the password presented during authentication,
- the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires
- with a L{Failure} wrapping L{AuthenticationFailed}.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", b"dummy user",
- self.hostname, self.port, password=b"dummy password",
- knownHosts=self.knownHosts, ui=FixedResponseUI(False))
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.connectedServerAndClient(
- self.factory, self.reactor.tcpClients[0][2])
-
- # For security, the server delays password authentication failure
- # response. Advance the simulation clock so the client sees the
- # failure.
- self.reactor.advance(server.service.passwordDelay)
-
- # Let the failure response traverse the "network"
- pump.flush()
-
- f = self.failureResultOf(connected)
- f.trap(AuthenticationFailed)
- # XXX Should assert something specific about the arguments of the
- # exception
-
- self.assertClientTransportState(client, False)
-
-
- def setupKeyChecker(self, portal, users):
- """
- Create an L{ISSHPrivateKey} checker which recognizes C{users} and add it
- to C{portal}.
-
- @param portal: A L{Portal} to which to add the checker.
- @type portal: L{Portal}
-
- @param users: The users and their keys the checker will recognize. Keys
- are byte strings giving user names. Values are byte strings giving
- OpenSSH-formatted private keys.
- @type users: C{dict}
- """
- credentials = {}
- for username, keyString in users.iteritems():
- goodKey = Key.fromString(keyString)
- authorizedKeys = FilePath(self.mktemp())
- authorizedKeys.setContent(goodKey.public().toString("OPENSSH"))
- credentials[username] = [authorizedKeys]
- checker = MemorySSHPublicKeyDatabase(credentials)
- portal.registerChecker(checker)
-
-
- def test_publicKeyAuthenticationFailure(self):
- """
- If the SSH server rejects the key pair presented during authentication,
- the L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires
- with a L{Failure} wrapping L{AuthenticationFailed}.
- """
- badKey = Key.fromString(privateRSA_openssh)
- self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh})
-
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", self.user,
- self.hostname, self.port, keys=[badKey],
- knownHosts=self.knownHosts, ui=FixedResponseUI(False))
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.connectedServerAndClient(
- self.factory, self.reactor.tcpClients[0][2])
-
- f = self.failureResultOf(connected)
- f.trap(AuthenticationFailed)
- # XXX Should assert something specific about the arguments of the
- # exception
-
- # Nothing useful can be done with the connection at this point, so the
- # endpoint should close it.
- self.assertTrue(client.transport.disconnecting)
-
-
- def test_authenticationFallback(self):
- """
- If the SSH server does not accept any of the specified SSH keys, the
- specified password is tried.
- """
- badKey = Key.fromString(privateRSA_openssh)
- self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh})
-
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
- keys=[badKey], password=self.password, knownHosts=self.knownHosts,
- ui=FixedResponseUI(False))
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- # Exercising fallback requires a failed authentication attempt. Allow
- # one.
- self.factory.attemptsBeforeDisconnect += 1
-
- server, client, pump = self.connectedServerAndClient(
- self.factory, self.reactor.tcpClients[0][2])
-
- pump.pump()
-
- # The server logs the channel open failure - this is expected.
- errors = self.flushLoggedErrors(ConchError)
- self.assertIn(
- 'unknown channel', (errors[0].value.data, errors[0].value.value))
- self.assertEqual(1, len(errors))
-
- # Now deal with the results on the endpoint side.
- f = self.failureResultOf(connected)
- f.trap(ConchError)
- self.assertEqual('unknown channel', f.value.value)
-
- # Nothing useful can be done with the connection at this point, so the
- # endpoint should close it.
- self.assertTrue(client.transport.disconnecting)
-
-
- def test_publicKeyAuthentication(self):
- """
- If L{SSHCommandClientEndpoint} is initialized with any private keys, it
- will try to use them to authenticate with the SSH server.
- """
- key = Key.fromString(privateDSA_openssh)
- self.setupKeyChecker(self.portal, {self.user: privateDSA_openssh})
-
- self.realm.channelLookup[b'session'] = WorkingExecSession
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
- keys=[key], knownHosts=self.knownHosts, ui=FixedResponseUI(False))
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.connectedServerAndClient(
- self.factory, self.reactor.tcpClients[0][2])
-
- protocol = self.successResultOf(connected)
- self.assertIsNot(None, protocol.transport)
-
-
- def test_skipPasswordAuthentication(self):
- """
- If the password is not specified, L{SSHCommandClientEndpoint} doesn't
- try it as an authentication mechanism.
- """
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
- knownHosts=self.knownHosts, ui=FixedResponseUI(False))
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.connectedServerAndClient(
- self.factory, self.reactor.tcpClients[0][2])
-
- pump.pump()
-
- # Now deal with the results on the endpoint side.
- f = self.failureResultOf(connected)
- f.trap(AuthenticationFailed)
-
- # Nothing useful can be done with the connection at this point, so the
- # endpoint should close it.
- self.assertTrue(client.transport.disconnecting)
-
-
- def test_agentAuthentication(self):
- """
- If L{SSHCommandClientEndpoint} is initialized with an
- L{SSHAgentClient}, the agent is used to authenticate with the SSH
- server.
- """
- key = Key.fromString(privateRSA_openssh)
- agentServer = SSHAgentServer()
- agentServer.factory = Factory()
- agentServer.factory.keys = {key.blob(): (key, "")}
-
- self.setupKeyChecker(self.portal, {self.user: privateRSA_openssh})
-
- agentEndpoint = SingleUseMemoryEndpoint(agentServer)
- endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
- knownHosts=self.knownHosts, ui=FixedResponseUI(False),
- agentEndpoint=agentEndpoint)
-
- self.realm.channelLookup[b'session'] = WorkingExecSession
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.connectedServerAndClient(
- self.factory, self.reactor.tcpClients[0][2])
-
- # Let the agent client talk with the agent server and the ssh client
- # talk with the ssh server.
- for i in range(14):
- agentEndpoint.pump.pump()
- pump.pump()
-
- protocol = self.successResultOf(connected)
- self.assertIsNot(None, protocol.transport)
-
-
- def test_loseConnection(self):
- """
- The transport connected to the protocol has a C{loseConnection} method
- which causes the channel in which the command is running to close and
- the overall connection to be closed.
- """
- self.realm.channelLookup[b'session'] = WorkingExecSession
- endpoint = self.create()
-
- factory = Factory()
- factory.protocol = Protocol
- connected = endpoint.connect(factory)
-
- server, client, pump = self.finishConnection()
-
- protocol = self.successResultOf(connected)
- closed = self.record(server, protocol, 'closed', noArgs=True)
- protocol.transport.loseConnection()
- pump.pump()
- self.assertEqual([None], closed)
-
- # Let the last bit of network traffic flow. This lets the server's
- # close acknowledgement through, at which point the client can close
- # the overall SSH connection.
- pump.pump()
-
- # Nothing useful can be done with the connection at this point, so the
- # endpoint should close it.
- self.assertTrue(client.transport.disconnecting)
-
-
-
-class ExistingConnectionTests(TestCase, SSHCommandClientEndpointTestsMixin):
- """
- Tests for L{SSHCommandClientEndpoint} when using the C{existingConnection}
- constructor.
- """
- def setUp(self):
- """
- Configure an SSH server with password authentication enabled for a
- well-known (to the tests) account.
- """
- SSHCommandClientEndpointTestsMixin.setUp(self)
-
- knownHosts = KnownHostsFile(FilePath(self.mktemp()))
- knownHosts.addHostKey(
- self.hostname, self.factory.publicKeys['ssh-rsa'])
- knownHosts.addHostKey(
- self.serverAddress.host, self.factory.publicKeys['ssh-rsa'])
-
- self.endpoint = SSHCommandClientEndpoint.newConnection(
- self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
- password=self.password, knownHosts=knownHosts,
- ui=FixedResponseUI(False))
-
-
- def create(self):
- """
- Create and return a new L{SSHCommandClientEndpoint} using the
- C{existingConnection} constructor.
- """
- factory = Factory()
- factory.protocol = Protocol
- connected = self.endpoint.connect(factory)
-
- # Please, let me in. This kinda sucks.
- channelLookup = self.realm.channelLookup.copy()
- try:
- self.realm.channelLookup[b'session'] = WorkingExecSession
-
- server, client, pump = self.connectedServerAndClient(
- self.factory, self.reactor.tcpClients[0][2])
-
- finally:
- self.realm.channelLookup.clear()
- self.realm.channelLookup.update(channelLookup)
-
- self._server = server
- self._client = client
- self._pump = pump
-
- protocol = self.successResultOf(connected)
- connection = protocol.transport.conn
- return SSHCommandClientEndpoint.existingConnection(
- connection, b"/bin/ls -l")
-
-
- def finishConnection(self):
- """
- Give back the connection established in L{create} over which the new
- command channel being tested will exchange data.
- """
- # The connection was set up and the first command channel set up, but
- # some more I/O needs to happen for the second command channel to be
- # ready. Make that I/O happen before giving back the objects.
- self._pump.pump()
- self._pump.pump()
- self._pump.pump()
- self._pump.pump()
- return self._server, self._client, self._pump
-
-
- def assertClientTransportState(self, client, immediateClose):
- """
- Assert that the transport for the given protocol is still connected.
- L{SSHCommandClientEndpoint.existingConnection} re-uses an SSH connected
- created by some other code, so other code is responsible for cleaning
- it up.
- """
- self.assertFalse(client.transport.disconnecting)
- self.assertFalse(client.transport.aborted)
-
-
-
-class ExistingConnectionHelperTests(TestCase):
- """
- Tests for L{_ExistingConnectionHelper}.
- """
- def test_interface(self):
- """
- L{_ExistingConnectionHelper} implements L{_ISSHConnectionCreator}.
- """
- self.assertTrue(
- verifyClass(_ISSHConnectionCreator, _ExistingConnectionHelper))
-
-
- def test_secureConnection(self):
- """
- L{_ExistingConnectionHelper.secureConnection} returns a L{Deferred}
- which fires with whatever object was fed to
- L{_ExistingConnectionHelper.__init__}.
- """
- result = object()
- helper = _ExistingConnectionHelper(result)
- self.assertIs(
- result, self.successResultOf(helper.secureConnection()))
-
-
- def test_cleanupConnectionNotImmediately(self):
- """
- L{_ExistingConnectionHelper.cleanupConnection} does nothing to the
- existing connection if called with C{immediate} set to C{False}.
- """
- helper = _ExistingConnectionHelper(object())
- # Bit hard to test nothing happens. However, since object() has no
- # relevant methods or attributes, if the code is incorrect we can
- # expect an AttributeError.
- helper.cleanupConnection(object(), False)
-
-
- def test_cleanupConnectionImmediately(self):
- """
- L{_ExistingConnectionHelper.cleanupConnection} does nothing to the
- existing connection if called with C{immediate} set to C{True}.
- """
- helper = _ExistingConnectionHelper(object())
- # Bit hard to test nothing happens. However, since object() has no
- # relevant methods or attributes, if the code is incorrect we can
- # expect an AttributeError.
- helper.cleanupConnection(object(), True)
-
-
-
-class _PTYPath(object):
- """
- A L{FilePath}-like object which can be opened to create a L{_ReadFile} with
- certain contents.
- """
- def __init__(self, contents):
- """
- @param contents: L{bytes} which will be the contents of the
- L{_ReadFile} this path can open.
- """
- self.contents = contents
-
-
- def open(self, mode):
- """
- If the mode is r+, return a L{_ReadFile} with the contents given to
- this path's initializer.
-
- @raise OSError: If the mode is unsupported.
-
- @return: A L{_ReadFile} instance
- """
- if mode == "r+":
- return _ReadFile(self.contents)
- raise OSError(ENOSYS, "Function not implemented")
-
-
-
-class NewConnectionHelperTests(TestCase):
- """
- Tests for L{_NewConnectionHelper}.
- """
- def test_interface(self):
- """
- L{_NewConnectionHelper} implements L{_ISSHConnectionCreator}.
- """
- self.assertTrue(
- verifyClass(_ISSHConnectionCreator, _NewConnectionHelper))
-
-
- def test_defaultPath(self):
- """
- The default I{known_hosts} path is I{~/.ssh/known_hosts}.
- """
- self.assertEqual(
- "~/.ssh/known_hosts", _NewConnectionHelper._KNOWN_HOSTS)
-
-
- def test_defaultKnownHosts(self):
- """
- L{_NewConnectionHelper._knownHosts} is used to create a
- L{KnownHostsFile} if one is not passed to the initializer.
- """
- result = object()
- self.patch(_NewConnectionHelper, '_knownHosts', lambda cls: result)
-
- helper = _NewConnectionHelper(
- None, None, None, None, None, None, None, None, None, None)
-
- self.assertIs(result, helper.knownHosts)
-
-
- def test_readExisting(self):
- """
- Existing entries in the I{known_hosts} file are reflected by the
- L{KnownHostsFile} created by L{_NewConnectionHelper} when none is
- supplied to it.
- """
- key = CommandFactory().publicKeys['ssh-rsa']
- path = FilePath(self.mktemp())
- knownHosts = KnownHostsFile(path)
- knownHosts.addHostKey("127.0.0.1", key)
- knownHosts.save()
-
- msg("Created known_hosts file at %r" % (path.path,))
-
- # Unexpand ${HOME} to make sure ~ syntax is respected.
- home = os.path.expanduser("~/")
- default = path.path.replace(home, "~/")
- self.patch(_NewConnectionHelper, "_KNOWN_HOSTS", default)
- msg("Patched _KNOWN_HOSTS with %r" % (default,))
-
- loaded = _NewConnectionHelper._knownHosts()
- self.assertTrue(loaded.hasHostKey("127.0.0.1", key))
-
-
- def test_defaultConsoleUI(self):
- """
- If C{None} is passed for the C{ui} parameter to
- L{_NewConnectionHelper}, a L{ConsoleUI} is used.
- """
- helper = _NewConnectionHelper(
- None, None, None, None, None, None, None, None, None, None)
- self.assertIsInstance(helper.ui, ConsoleUI)
-
-
- def test_ttyConsoleUI(self):
- """
- If C{None} is passed for the C{ui} parameter to L{_NewConnectionHelper}
- and /dev/tty is available, the L{ConsoleUI} used is associated with
- /dev/tty.
- """
- tty = _PTYPath(b"yes")
- helper = _NewConnectionHelper(
- None, None, None, None, None, None, None, None, None, None, tty)
- result = self.successResultOf(helper.ui.prompt(b"does this work?"))
- self.assertTrue(result)
-
-
- def test_nottyUI(self):
- """
- If C{None} is passed for the C{ui} parameter to L{_NewConnectionHelper}
- and /dev/tty is not available, the L{ConsoleUI} used is associated with
- some file which always produces a C{b"no"} response.
- """
- tty = FilePath(self.mktemp())
- helper = _NewConnectionHelper(
- None, None, None, None, None, None, None, None, None, None, tty)
- result = self.successResultOf(helper.ui.prompt(b"did this break?"))
- self.assertFalse(result)
-
-
- def test_defaultTTYFilename(self):
- """
- If not passed the name of a tty in the filesystem,
- L{_NewConnectionHelper} uses C{b"/dev/tty"}.
- """
- helper = _NewConnectionHelper(
- None, None, None, None, None, None, None, None, None, None)
- self.assertEqual(FilePath(b"/dev/tty"), helper.tty)
-
-
- def test_cleanupConnectionNotImmediately(self):
- """
- L{_NewConnectionHelper.cleanupConnection} closes the transport cleanly
- if called with C{immediate} set to C{False}.
- """
- helper = _NewConnectionHelper(
- None, None, None, None, None, None, None, None, None, None)
- connection = SSHConnection()
- connection.transport = StringTransport()
- helper.cleanupConnection(connection, False)
- self.assertTrue(connection.transport.disconnecting)
-
-
- def test_cleanupConnectionImmediately(self):
- """
- L{_NewConnectionHelper.cleanupConnection} closes the transport with
- C{abortConnection} if called with C{immediate} set to C{True}.
- """
- class Abortable:
- aborted = False
- def abortConnection(self):
- """
- Abort the connection.
- """
- self.aborted = True
-
- helper = _NewConnectionHelper(
- None, None, None, None, None, None, None, None, None, None)
- connection = SSHConnection()
- connection.transport = SSHClientTransport()
- connection.transport.transport = Abortable()
- helper.cleanupConnection(connection, True)
- self.assertTrue(connection.transport.transport.aborted)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_filetransfer.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_filetransfer.py
deleted file mode 100644
index 8216602..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_filetransfer.py
+++ /dev/null
@@ -1,771 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_filetransfer -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE file for details.
-
-"""
-Tests for L{twisted.conch.ssh.filetransfer}.
-"""
-
-import os
-import re
-import struct
-import sys
-
-from twisted.trial import unittest
-try:
- from twisted.conch import unix
- unix # shut up pyflakes
-except ImportError:
- unix = None
-
-from twisted.conch import avatar
-from twisted.conch.ssh import common, connection, filetransfer, session
-from twisted.internet import defer
-from twisted.protocols import loopback
-from twisted.python import components
-
-
-class TestAvatar(avatar.ConchUser):
- def __init__(self):
- avatar.ConchUser.__init__(self)
- self.channelLookup['session'] = session.SSHSession
- self.subsystemLookup['sftp'] = filetransfer.FileTransferServer
-
- def _runAsUser(self, f, *args, **kw):
- try:
- f = iter(f)
- except TypeError:
- f = [(f, args, kw)]
- for i in f:
- func = i[0]
- args = len(i)>1 and i[1] or ()
- kw = len(i)>2 and i[2] or {}
- r = func(*args, **kw)
- return r
-
-
-class FileTransferTestAvatar(TestAvatar):
-
- def __init__(self, homeDir):
- TestAvatar.__init__(self)
- self.homeDir = homeDir
-
- def getHomeDir(self):
- return os.path.join(os.getcwd(), self.homeDir)
-
-
-class ConchSessionForTestAvatar:
-
- def __init__(self, avatar):
- self.avatar = avatar
-
-if unix:
- if not hasattr(unix, 'SFTPServerForUnixConchUser'):
- # unix should either be a fully working module, or None. I'm not sure
- # how this happens, but on win32 it does. Try to cope. --spiv.
- import warnings
- warnings.warn(("twisted.conch.unix imported %r, "
- "but doesn't define SFTPServerForUnixConchUser'")
- % (unix,))
- unix = None
- else:
- class FileTransferForTestAvatar(unix.SFTPServerForUnixConchUser):
-
- def gotVersion(self, version, otherExt):
- return {'conchTest' : 'ext data'}
-
- def extendedRequest(self, extName, extData):
- if extName == 'testExtendedRequest':
- return 'bar'
- raise NotImplementedError
-
- components.registerAdapter(FileTransferForTestAvatar,
- TestAvatar,
- filetransfer.ISFTPServer)
-
-class SFTPTestBase(unittest.TestCase):
-
- def setUp(self):
- self.testDir = self.mktemp()
- # Give the testDir another level so we can safely "cd .." from it in
- # tests.
- self.testDir = os.path.join(self.testDir, 'extra')
- os.makedirs(os.path.join(self.testDir, 'testDirectory'))
-
- f = file(os.path.join(self.testDir, 'testfile1'),'w')
- f.write('a'*10+'b'*10)
- f.write(file('/dev/urandom').read(1024*64)) # random data
- os.chmod(os.path.join(self.testDir, 'testfile1'), 0644)
- file(os.path.join(self.testDir, 'testRemoveFile'), 'w').write('a')
- file(os.path.join(self.testDir, 'testRenameFile'), 'w').write('a')
- file(os.path.join(self.testDir, '.testHiddenFile'), 'w').write('a')
-
-
-class TestOurServerOurClient(SFTPTestBase):
-
- if not unix:
- skip = "can't run on non-posix computers"
-
- def setUp(self):
- SFTPTestBase.setUp(self)
-
- self.avatar = FileTransferTestAvatar(self.testDir)
- self.server = filetransfer.FileTransferServer(avatar=self.avatar)
- clientTransport = loopback.LoopbackRelay(self.server)
-
- self.client = filetransfer.FileTransferClient()
- self._serverVersion = None
- self._extData = None
- def _(serverVersion, extData):
- self._serverVersion = serverVersion
- self._extData = extData
- self.client.gotServerVersion = _
- serverTransport = loopback.LoopbackRelay(self.client)
- self.client.makeConnection(clientTransport)
- self.server.makeConnection(serverTransport)
-
- self.clientTransport = clientTransport
- self.serverTransport = serverTransport
-
- self._emptyBuffers()
-
-
- def _emptyBuffers(self):
- while self.serverTransport.buffer or self.clientTransport.buffer:
- self.serverTransport.clearBuffer()
- self.clientTransport.clearBuffer()
-
-
- def tearDown(self):
- self.serverTransport.loseConnection()
- self.clientTransport.loseConnection()
- self.serverTransport.clearBuffer()
- self.clientTransport.clearBuffer()
-
-
- def testServerVersion(self):
- self.assertEqual(self._serverVersion, 3)
- self.assertEqual(self._extData, {'conchTest' : 'ext data'})
-
-
- def test_interface_implementation(self):
- """
- It implements the ISFTPServer interface.
- """
- self.assertTrue(
- filetransfer.ISFTPServer.providedBy(self.server.client),
- "ISFTPServer not provided by %r" % (self.server.client,))
-
-
- def test_openedFileClosedWithConnection(self):
- """
- A file opened with C{openFile} is close when the connection is lost.
- """
- d = self.client.openFile("testfile1", filetransfer.FXF_READ |
- filetransfer.FXF_WRITE, {})
- self._emptyBuffers()
-
- oldClose = os.close
- closed = []
- def close(fd):
- closed.append(fd)
- oldClose(fd)
-
- self.patch(os, "close", close)
-
- def _fileOpened(openFile):
- fd = self.server.openFiles[openFile.handle[4:]].fd
- self.serverTransport.loseConnection()
- self.clientTransport.loseConnection()
- self.serverTransport.clearBuffer()
- self.clientTransport.clearBuffer()
- self.assertEqual(self.server.openFiles, {})
- self.assertIn(fd, closed)
-
- d.addCallback(_fileOpened)
- return d
-
-
- def test_openedDirectoryClosedWithConnection(self):
- """
- A directory opened with C{openDirectory} is close when the connection
- is lost.
- """
- d = self.client.openDirectory('')
- self._emptyBuffers()
-
- def _getFiles(openDir):
- self.serverTransport.loseConnection()
- self.clientTransport.loseConnection()
- self.serverTransport.clearBuffer()
- self.clientTransport.clearBuffer()
- self.assertEqual(self.server.openDirs, {})
-
- d.addCallback(_getFiles)
- return d
-
-
- def testOpenFileIO(self):
- d = self.client.openFile("testfile1", filetransfer.FXF_READ |
- filetransfer.FXF_WRITE, {})
- self._emptyBuffers()
-
- def _fileOpened(openFile):
- self.assertEqual(openFile, filetransfer.ISFTPFile(openFile))
- d = _readChunk(openFile)
- d.addCallback(_writeChunk, openFile)
- return d
-
- def _readChunk(openFile):
- d = openFile.readChunk(0, 20)
- self._emptyBuffers()
- d.addCallback(self.assertEqual, 'a'*10 + 'b'*10)
- return d
-
- def _writeChunk(_, openFile):
- d = openFile.writeChunk(20, 'c'*10)
- self._emptyBuffers()
- d.addCallback(_readChunk2, openFile)
- return d
-
- def _readChunk2(_, openFile):
- d = openFile.readChunk(0, 30)
- self._emptyBuffers()
- d.addCallback(self.assertEqual, 'a'*10 + 'b'*10 + 'c'*10)
- return d
-
- d.addCallback(_fileOpened)
- return d
-
- def testClosedFileGetAttrs(self):
- d = self.client.openFile("testfile1", filetransfer.FXF_READ |
- filetransfer.FXF_WRITE, {})
- self._emptyBuffers()
-
- def _getAttrs(_, openFile):
- d = openFile.getAttrs()
- self._emptyBuffers()
- return d
-
- def _err(f):
- self.flushLoggedErrors()
- return f
-
- def _close(openFile):
- d = openFile.close()
- self._emptyBuffers()
- d.addCallback(_getAttrs, openFile)
- d.addErrback(_err)
- return self.assertFailure(d, filetransfer.SFTPError)
-
- d.addCallback(_close)
- return d
-
- def testOpenFileAttributes(self):
- d = self.client.openFile("testfile1", filetransfer.FXF_READ |
- filetransfer.FXF_WRITE, {})
- self._emptyBuffers()
-
- def _getAttrs(openFile):
- d = openFile.getAttrs()
- self._emptyBuffers()
- d.addCallback(_getAttrs2)
- return d
-
- def _getAttrs2(attrs1):
- d = self.client.getAttrs('testfile1')
- self._emptyBuffers()
- d.addCallback(self.assertEqual, attrs1)
- return d
-
- return d.addCallback(_getAttrs)
-
-
- def testOpenFileSetAttrs(self):
- # XXX test setAttrs
- # Ok, how about this for a start? It caught a bug :) -- spiv.
- d = self.client.openFile("testfile1", filetransfer.FXF_READ |
- filetransfer.FXF_WRITE, {})
- self._emptyBuffers()
-
- def _getAttrs(openFile):
- d = openFile.getAttrs()
- self._emptyBuffers()
- d.addCallback(_setAttrs)
- return d
-
- def _setAttrs(attrs):
- attrs['atime'] = 0
- d = self.client.setAttrs('testfile1', attrs)
- self._emptyBuffers()
- d.addCallback(_getAttrs2)
- d.addCallback(self.assertEqual, attrs)
- return d
-
- def _getAttrs2(_):
- d = self.client.getAttrs('testfile1')
- self._emptyBuffers()
- return d
-
- d.addCallback(_getAttrs)
- return d
-
-
- def test_openFileExtendedAttributes(self):
- """
- Check that L{filetransfer.FileTransferClient.openFile} can send
- extended attributes, that should be extracted server side. By default,
- they are ignored, so we just verify they are correctly parsed.
- """
- savedAttributes = {}
- oldOpenFile = self.server.client.openFile
- def openFile(filename, flags, attrs):
- savedAttributes.update(attrs)
- return oldOpenFile(filename, flags, attrs)
- self.server.client.openFile = openFile
-
- d = self.client.openFile("testfile1", filetransfer.FXF_READ |
- filetransfer.FXF_WRITE, {"ext_foo": "bar"})
- self._emptyBuffers()
-
- def check(ign):
- self.assertEqual(savedAttributes, {"ext_foo": "bar"})
-
- return d.addCallback(check)
-
-
- def testRemoveFile(self):
- d = self.client.getAttrs("testRemoveFile")
- self._emptyBuffers()
- def _removeFile(ignored):
- d = self.client.removeFile("testRemoveFile")
- self._emptyBuffers()
- return d
- d.addCallback(_removeFile)
- d.addCallback(_removeFile)
- return self.assertFailure(d, filetransfer.SFTPError)
-
- def testRenameFile(self):
- d = self.client.getAttrs("testRenameFile")
- self._emptyBuffers()
- def _rename(attrs):
- d = self.client.renameFile("testRenameFile", "testRenamedFile")
- self._emptyBuffers()
- d.addCallback(_testRenamed, attrs)
- return d
- def _testRenamed(_, attrs):
- d = self.client.getAttrs("testRenamedFile")
- self._emptyBuffers()
- d.addCallback(self.assertEqual, attrs)
- return d.addCallback(_rename)
-
- def testDirectoryBad(self):
- d = self.client.getAttrs("testMakeDirectory")
- self._emptyBuffers()
- return self.assertFailure(d, filetransfer.SFTPError)
-
- def testDirectoryCreation(self):
- d = self.client.makeDirectory("testMakeDirectory", {})
- self._emptyBuffers()
-
- def _getAttrs(_):
- d = self.client.getAttrs("testMakeDirectory")
- self._emptyBuffers()
- return d
-
- # XXX not until version 4/5
- # self.assertEqual(filetransfer.FILEXFER_TYPE_DIRECTORY&attrs['type'],
- # filetransfer.FILEXFER_TYPE_DIRECTORY)
-
- def _removeDirectory(_):
- d = self.client.removeDirectory("testMakeDirectory")
- self._emptyBuffers()
- return d
-
- d.addCallback(_getAttrs)
- d.addCallback(_removeDirectory)
- d.addCallback(_getAttrs)
- return self.assertFailure(d, filetransfer.SFTPError)
-
- def testOpenDirectory(self):
- d = self.client.openDirectory('')
- self._emptyBuffers()
- files = []
-
- def _getFiles(openDir):
- def append(f):
- files.append(f)
- return openDir
- d = defer.maybeDeferred(openDir.next)
- self._emptyBuffers()
- d.addCallback(append)
- d.addCallback(_getFiles)
- d.addErrback(_close, openDir)
- return d
-
- def _checkFiles(ignored):
- fs = list(zip(*files)[0])
- fs.sort()
- self.assertEqual(fs,
- ['.testHiddenFile', 'testDirectory',
- 'testRemoveFile', 'testRenameFile',
- 'testfile1'])
-
- def _close(_, openDir):
- d = openDir.close()
- self._emptyBuffers()
- return d
-
- d.addCallback(_getFiles)
- d.addCallback(_checkFiles)
- return d
-
- def testLinkDoesntExist(self):
- d = self.client.getAttrs('testLink')
- self._emptyBuffers()
- return self.assertFailure(d, filetransfer.SFTPError)
-
- def testLinkSharesAttrs(self):
- d = self.client.makeLink('testLink', 'testfile1')
- self._emptyBuffers()
- def _getFirstAttrs(_):
- d = self.client.getAttrs('testLink', 1)
- self._emptyBuffers()
- return d
- def _getSecondAttrs(firstAttrs):
- d = self.client.getAttrs('testfile1')
- self._emptyBuffers()
- d.addCallback(self.assertEqual, firstAttrs)
- return d
- d.addCallback(_getFirstAttrs)
- return d.addCallback(_getSecondAttrs)
-
- def testLinkPath(self):
- d = self.client.makeLink('testLink', 'testfile1')
- self._emptyBuffers()
- def _readLink(_):
- d = self.client.readLink('testLink')
- self._emptyBuffers()
- d.addCallback(self.assertEqual,
- os.path.join(os.getcwd(), self.testDir, 'testfile1'))
- return d
- def _realPath(_):
- d = self.client.realPath('testLink')
- self._emptyBuffers()
- d.addCallback(self.assertEqual,
- os.path.join(os.getcwd(), self.testDir, 'testfile1'))
- return d
- d.addCallback(_readLink)
- d.addCallback(_realPath)
- return d
-
- def testExtendedRequest(self):
- d = self.client.extendedRequest('testExtendedRequest', 'foo')
- self._emptyBuffers()
- d.addCallback(self.assertEqual, 'bar')
- d.addCallback(self._cbTestExtendedRequest)
- return d
-
- def _cbTestExtendedRequest(self, ignored):
- d = self.client.extendedRequest('testBadRequest', '')
- self._emptyBuffers()
- return self.assertFailure(d, NotImplementedError)
-
-
-class FakeConn:
- def sendClose(self, channel):
- pass
-
-
-class TestFileTransferClose(unittest.TestCase):
-
- if not unix:
- skip = "can't run on non-posix computers"
-
- def setUp(self):
- self.avatar = TestAvatar()
-
- def buildServerConnection(self):
- # make a server connection
- conn = connection.SSHConnection()
- # server connections have a 'self.transport.avatar'.
- class DummyTransport:
- def __init__(self):
- self.transport = self
- def sendPacket(self, kind, data):
- pass
- def logPrefix(self):
- return 'dummy transport'
- conn.transport = DummyTransport()
- conn.transport.avatar = self.avatar
- return conn
-
- def interceptConnectionLost(self, sftpServer):
- self.connectionLostFired = False
- origConnectionLost = sftpServer.connectionLost
- def connectionLost(reason):
- self.connectionLostFired = True
- origConnectionLost(reason)
- sftpServer.connectionLost = connectionLost
-
- def assertSFTPConnectionLost(self):
- self.assertTrue(self.connectionLostFired,
- "sftpServer's connectionLost was not called")
-
- def test_sessionClose(self):
- """
- Closing a session should notify an SFTP subsystem launched by that
- session.
- """
- # make a session
- testSession = session.SSHSession(conn=FakeConn(), avatar=self.avatar)
-
- # start an SFTP subsystem on the session
- testSession.request_subsystem(common.NS('sftp'))
- sftpServer = testSession.client.transport.proto
-
- # intercept connectionLost so we can check that it's called
- self.interceptConnectionLost(sftpServer)
-
- # close session
- testSession.closeReceived()
-
- self.assertSFTPConnectionLost()
-
- def test_clientClosesChannelOnConnnection(self):
- """
- A client sending CHANNEL_CLOSE should trigger closeReceived on the
- associated channel instance.
- """
- conn = self.buildServerConnection()
-
- # somehow get a session
- packet = common.NS('session') + struct.pack('>L', 0) * 3
- conn.ssh_CHANNEL_OPEN(packet)
- sessionChannel = conn.channels[0]
-
- sessionChannel.request_subsystem(common.NS('sftp'))
- sftpServer = sessionChannel.client.transport.proto
- self.interceptConnectionLost(sftpServer)
-
- # intercept closeReceived
- self.interceptConnectionLost(sftpServer)
-
- # close the connection
- conn.ssh_CHANNEL_CLOSE(struct.pack('>L', 0))
-
- self.assertSFTPConnectionLost()
-
-
- def test_stopConnectionServiceClosesChannel(self):
- """
- Closing an SSH connection should close all sessions within it.
- """
- conn = self.buildServerConnection()
-
- # somehow get a session
- packet = common.NS('session') + struct.pack('>L', 0) * 3
- conn.ssh_CHANNEL_OPEN(packet)
- sessionChannel = conn.channels[0]
-
- sessionChannel.request_subsystem(common.NS('sftp'))
- sftpServer = sessionChannel.client.transport.proto
- self.interceptConnectionLost(sftpServer)
-
- # close the connection
- conn.serviceStopped()
-
- self.assertSFTPConnectionLost()
-
-
-
-class TestConstants(unittest.TestCase):
- """
- Tests for the constants used by the SFTP protocol implementation.
-
- @ivar filexferSpecExcerpts: Excerpts from the
- draft-ietf-secsh-filexfer-02.txt (draft) specification of the SFTP
- protocol. There are more recent drafts of the specification, but this
- one describes version 3, which is what conch (and OpenSSH) implements.
- """
-
-
- filexferSpecExcerpts = [
- """
- The following values are defined for packet types.
-
- #define SSH_FXP_INIT 1
- #define SSH_FXP_VERSION 2
- #define SSH_FXP_OPEN 3
- #define SSH_FXP_CLOSE 4
- #define SSH_FXP_READ 5
- #define SSH_FXP_WRITE 6
- #define SSH_FXP_LSTAT 7
- #define SSH_FXP_FSTAT 8
- #define SSH_FXP_SETSTAT 9
- #define SSH_FXP_FSETSTAT 10
- #define SSH_FXP_OPENDIR 11
- #define SSH_FXP_READDIR 12
- #define SSH_FXP_REMOVE 13
- #define SSH_FXP_MKDIR 14
- #define SSH_FXP_RMDIR 15
- #define SSH_FXP_REALPATH 16
- #define SSH_FXP_STAT 17
- #define SSH_FXP_RENAME 18
- #define SSH_FXP_READLINK 19
- #define SSH_FXP_SYMLINK 20
- #define SSH_FXP_STATUS 101
- #define SSH_FXP_HANDLE 102
- #define SSH_FXP_DATA 103
- #define SSH_FXP_NAME 104
- #define SSH_FXP_ATTRS 105
- #define SSH_FXP_EXTENDED 200
- #define SSH_FXP_EXTENDED_REPLY 201
-
- Additional packet types should only be defined if the protocol
- version number (see Section ``Protocol Initialization'') is
- incremented, and their use MUST be negotiated using the version
- number. However, the SSH_FXP_EXTENDED and SSH_FXP_EXTENDED_REPLY
- packets can be used to implement vendor-specific extensions. See
- Section ``Vendor-Specific-Extensions'' for more details.
- """,
- """
- The flags bits are defined to have the following values:
-
- #define SSH_FILEXFER_ATTR_SIZE 0x00000001
- #define SSH_FILEXFER_ATTR_UIDGID 0x00000002
- #define SSH_FILEXFER_ATTR_PERMISSIONS 0x00000004
- #define SSH_FILEXFER_ATTR_ACMODTIME 0x00000008
- #define SSH_FILEXFER_ATTR_EXTENDED 0x80000000
-
- """,
- """
- The `pflags' field is a bitmask. The following bits have been
- defined.
-
- #define SSH_FXF_READ 0x00000001
- #define SSH_FXF_WRITE 0x00000002
- #define SSH_FXF_APPEND 0x00000004
- #define SSH_FXF_CREAT 0x00000008
- #define SSH_FXF_TRUNC 0x00000010
- #define SSH_FXF_EXCL 0x00000020
- """,
- """
- Currently, the following values are defined (other values may be
- defined by future versions of this protocol):
-
- #define SSH_FX_OK 0
- #define SSH_FX_EOF 1
- #define SSH_FX_NO_SUCH_FILE 2
- #define SSH_FX_PERMISSION_DENIED 3
- #define SSH_FX_FAILURE 4
- #define SSH_FX_BAD_MESSAGE 5
- #define SSH_FX_NO_CONNECTION 6
- #define SSH_FX_CONNECTION_LOST 7
- #define SSH_FX_OP_UNSUPPORTED 8
- """]
-
-
- def test_constantsAgainstSpec(self):
- """
- The constants used by the SFTP protocol implementation match those
- found by searching through the spec.
- """
- constants = {}
- for excerpt in self.filexferSpecExcerpts:
- for line in excerpt.splitlines():
- m = re.match('^\s*#define SSH_([A-Z_]+)\s+([0-9x]*)\s*$', line)
- if m:
- constants[m.group(1)] = long(m.group(2), 0)
- self.assertTrue(
- len(constants) > 0, "No constants found (the test must be buggy).")
- for k, v in constants.items():
- self.assertEqual(v, getattr(filetransfer, k))
-
-
-
-class TestRawPacketData(unittest.TestCase):
- """
- Tests for L{filetransfer.FileTransferClient} which explicitly craft certain
- less common protocol messages to exercise their handling.
- """
- def setUp(self):
- self.ftc = filetransfer.FileTransferClient()
-
-
- def test_packetSTATUS(self):
- """
- A STATUS packet containing a result code, a message, and a language is
- parsed to produce the result of an outstanding request L{Deferred}.
-
- @see: U{section 9.1}
- of the SFTP Internet-Draft.
- """
- d = defer.Deferred()
- d.addCallback(self._cbTestPacketSTATUS)
- self.ftc.openRequests[1] = d
- data = struct.pack('!LL', 1, filetransfer.FX_OK) + common.NS('msg') + common.NS('lang')
- self.ftc.packet_STATUS(data)
- return d
-
-
- def _cbTestPacketSTATUS(self, result):
- """
- Assert that the result is a two-tuple containing the message and
- language from the STATUS packet.
- """
- self.assertEqual(result[0], 'msg')
- self.assertEqual(result[1], 'lang')
-
-
- def test_packetSTATUSShort(self):
- """
- A STATUS packet containing only a result code can also be parsed to
- produce the result of an outstanding request L{Deferred}. Such packets
- are sent by some SFTP implementations, though not strictly legal.
-
- @see: U{section 9.1}
- of the SFTP Internet-Draft.
- """
- d = defer.Deferred()
- d.addCallback(self._cbTestPacketSTATUSShort)
- self.ftc.openRequests[1] = d
- data = struct.pack('!LL', 1, filetransfer.FX_OK)
- self.ftc.packet_STATUS(data)
- return d
-
-
- def _cbTestPacketSTATUSShort(self, result):
- """
- Assert that the result is a two-tuple containing empty strings, since
- the STATUS packet had neither a message nor a language.
- """
- self.assertEqual(result[0], '')
- self.assertEqual(result[1], '')
-
-
- def test_packetSTATUSWithoutLang(self):
- """
- A STATUS packet containing a result code and a message but no language
- can also be parsed to produce the result of an outstanding request
- L{Deferred}. Such packets are sent by some SFTP implementations, though
- not strictly legal.
-
- @see: U{section 9.1}
- of the SFTP Internet-Draft.
- """
- d = defer.Deferred()
- d.addCallback(self._cbTestPacketSTATUSWithoutLang)
- self.ftc.openRequests[1] = d
- data = struct.pack('!LL', 1, filetransfer.FX_OK) + common.NS('msg')
- self.ftc.packet_STATUS(data)
- return d
-
-
- def _cbTestPacketSTATUSWithoutLang(self, result):
- """
- Assert that the result is a two-tuple containing the message from the
- STATUS packet and an empty string, since the language was missing.
- """
- self.assertEqual(result[0], 'msg')
- self.assertEqual(result[1], '')
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_helper.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_helper.py
deleted file mode 100644
index 39aac48..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_helper.py
+++ /dev/null
@@ -1,614 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_helper -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-from twisted.conch.insults import helper
-from twisted.conch.insults.insults import G0, G1, G2, G3
-from twisted.conch.insults.insults import modes, privateModes
-from twisted.conch.insults.insults import (
- NORMAL, BOLD, UNDERLINE, BLINK, REVERSE_VIDEO)
-
-from twisted.trial import unittest
-
-WIDTH = 80
-HEIGHT = 24
-
-class BufferTestCase(unittest.TestCase):
- def setUp(self):
- self.term = helper.TerminalBuffer()
- self.term.connectionMade()
-
- def testInitialState(self):
- self.assertEqual(self.term.width, WIDTH)
- self.assertEqual(self.term.height, HEIGHT)
- self.assertEqual(str(self.term),
- '\n' * (HEIGHT - 1))
- self.assertEqual(self.term.reportCursorPosition(), (0, 0))
-
-
- def test_initialPrivateModes(self):
- """
- Verify that only DEC Auto Wrap Mode (DECAWM) and DEC Text Cursor Enable
- Mode (DECTCEM) are initially in the Set Mode (SM) state.
- """
- self.assertEqual(
- {privateModes.AUTO_WRAP: True,
- privateModes.CURSOR_MODE: True},
- self.term.privateModes)
-
-
- def test_carriageReturn(self):
- """
- C{"\r"} moves the cursor to the first column in the current row.
- """
- self.term.cursorForward(5)
- self.term.cursorDown(3)
- self.assertEqual(self.term.reportCursorPosition(), (5, 3))
- self.term.insertAtCursor("\r")
- self.assertEqual(self.term.reportCursorPosition(), (0, 3))
-
-
- def test_linefeed(self):
- """
- C{"\n"} moves the cursor to the next row without changing the column.
- """
- self.term.cursorForward(5)
- self.assertEqual(self.term.reportCursorPosition(), (5, 0))
- self.term.insertAtCursor("\n")
- self.assertEqual(self.term.reportCursorPosition(), (5, 1))
-
-
- def test_newline(self):
- """
- C{write} transforms C{"\n"} into C{"\r\n"}.
- """
- self.term.cursorForward(5)
- self.term.cursorDown(3)
- self.assertEqual(self.term.reportCursorPosition(), (5, 3))
- self.term.write("\n")
- self.assertEqual(self.term.reportCursorPosition(), (0, 4))
-
-
- def test_setPrivateModes(self):
- """
- Verify that L{helper.TerminalBuffer.setPrivateModes} changes the Set
- Mode (SM) state to "set" for the private modes it is passed.
- """
- expected = self.term.privateModes.copy()
- self.term.setPrivateModes([privateModes.SCROLL, privateModes.SCREEN])
- expected[privateModes.SCROLL] = True
- expected[privateModes.SCREEN] = True
- self.assertEqual(expected, self.term.privateModes)
-
-
- def test_resetPrivateModes(self):
- """
- Verify that L{helper.TerminalBuffer.resetPrivateModes} changes the Set
- Mode (SM) state to "reset" for the private modes it is passed.
- """
- expected = self.term.privateModes.copy()
- self.term.resetPrivateModes([privateModes.AUTO_WRAP, privateModes.CURSOR_MODE])
- del expected[privateModes.AUTO_WRAP]
- del expected[privateModes.CURSOR_MODE]
- self.assertEqual(expected, self.term.privateModes)
-
-
- def testCursorDown(self):
- self.term.cursorDown(3)
- self.assertEqual(self.term.reportCursorPosition(), (0, 3))
- self.term.cursorDown()
- self.assertEqual(self.term.reportCursorPosition(), (0, 4))
- self.term.cursorDown(HEIGHT)
- self.assertEqual(self.term.reportCursorPosition(), (0, HEIGHT - 1))
-
- def testCursorUp(self):
- self.term.cursorUp(5)
- self.assertEqual(self.term.reportCursorPosition(), (0, 0))
-
- self.term.cursorDown(20)
- self.term.cursorUp(1)
- self.assertEqual(self.term.reportCursorPosition(), (0, 19))
-
- self.term.cursorUp(19)
- self.assertEqual(self.term.reportCursorPosition(), (0, 0))
-
- def testCursorForward(self):
- self.term.cursorForward(2)
- self.assertEqual(self.term.reportCursorPosition(), (2, 0))
- self.term.cursorForward(2)
- self.assertEqual(self.term.reportCursorPosition(), (4, 0))
- self.term.cursorForward(WIDTH)
- self.assertEqual(self.term.reportCursorPosition(), (WIDTH, 0))
-
- def testCursorBackward(self):
- self.term.cursorForward(10)
- self.term.cursorBackward(2)
- self.assertEqual(self.term.reportCursorPosition(), (8, 0))
- self.term.cursorBackward(7)
- self.assertEqual(self.term.reportCursorPosition(), (1, 0))
- self.term.cursorBackward(1)
- self.assertEqual(self.term.reportCursorPosition(), (0, 0))
- self.term.cursorBackward(1)
- self.assertEqual(self.term.reportCursorPosition(), (0, 0))
-
- def testCursorPositioning(self):
- self.term.cursorPosition(3, 9)
- self.assertEqual(self.term.reportCursorPosition(), (3, 9))
-
- def testSimpleWriting(self):
- s = "Hello, world."
- self.term.write(s)
- self.assertEqual(
- str(self.term),
- s + '\n' +
- '\n' * (HEIGHT - 2))
-
- def testOvertype(self):
- s = "hello, world."
- self.term.write(s)
- self.term.cursorBackward(len(s))
- self.term.resetModes([modes.IRM])
- self.term.write("H")
- self.assertEqual(
- str(self.term),
- ("H" + s[1:]) + '\n' +
- '\n' * (HEIGHT - 2))
-
- def testInsert(self):
- s = "ello, world."
- self.term.write(s)
- self.term.cursorBackward(len(s))
- self.term.setModes([modes.IRM])
- self.term.write("H")
- self.assertEqual(
- str(self.term),
- ("H" + s) + '\n' +
- '\n' * (HEIGHT - 2))
-
- def testWritingInTheMiddle(self):
- s = "Hello, world."
- self.term.cursorDown(5)
- self.term.cursorForward(5)
- self.term.write(s)
- self.assertEqual(
- str(self.term),
- '\n' * 5 +
- (self.term.fill * 5) + s + '\n' +
- '\n' * (HEIGHT - 7))
-
- def testWritingWrappedAtEndOfLine(self):
- s = "Hello, world."
- self.term.cursorForward(WIDTH - 5)
- self.term.write(s)
- self.assertEqual(
- str(self.term),
- s[:5].rjust(WIDTH) + '\n' +
- s[5:] + '\n' +
- '\n' * (HEIGHT - 3))
-
- def testIndex(self):
- self.term.index()
- self.assertEqual(self.term.reportCursorPosition(), (0, 1))
- self.term.cursorDown(HEIGHT)
- self.assertEqual(self.term.reportCursorPosition(), (0, HEIGHT - 1))
- self.term.index()
- self.assertEqual(self.term.reportCursorPosition(), (0, HEIGHT - 1))
-
- def testReverseIndex(self):
- self.term.reverseIndex()
- self.assertEqual(self.term.reportCursorPosition(), (0, 0))
- self.term.cursorDown(2)
- self.assertEqual(self.term.reportCursorPosition(), (0, 2))
- self.term.reverseIndex()
- self.assertEqual(self.term.reportCursorPosition(), (0, 1))
-
- def test_nextLine(self):
- """
- C{nextLine} positions the cursor at the beginning of the row below the
- current row.
- """
- self.term.nextLine()
- self.assertEqual(self.term.reportCursorPosition(), (0, 1))
- self.term.cursorForward(5)
- self.assertEqual(self.term.reportCursorPosition(), (5, 1))
- self.term.nextLine()
- self.assertEqual(self.term.reportCursorPosition(), (0, 2))
-
- def testSaveCursor(self):
- self.term.cursorDown(5)
- self.term.cursorForward(7)
- self.assertEqual(self.term.reportCursorPosition(), (7, 5))
- self.term.saveCursor()
- self.term.cursorDown(7)
- self.term.cursorBackward(3)
- self.assertEqual(self.term.reportCursorPosition(), (4, 12))
- self.term.restoreCursor()
- self.assertEqual(self.term.reportCursorPosition(), (7, 5))
-
- def testSingleShifts(self):
- self.term.singleShift2()
- self.term.write('Hi')
-
- ch = self.term.getCharacter(0, 0)
- self.assertEqual(ch[0], 'H')
- self.assertEqual(ch[1].charset, G2)
-
- ch = self.term.getCharacter(1, 0)
- self.assertEqual(ch[0], 'i')
- self.assertEqual(ch[1].charset, G0)
-
- self.term.singleShift3()
- self.term.write('!!')
-
- ch = self.term.getCharacter(2, 0)
- self.assertEqual(ch[0], '!')
- self.assertEqual(ch[1].charset, G3)
-
- ch = self.term.getCharacter(3, 0)
- self.assertEqual(ch[0], '!')
- self.assertEqual(ch[1].charset, G0)
-
- def testShifting(self):
- s1 = "Hello"
- s2 = "World"
- s3 = "Bye!"
- self.term.write("Hello\n")
- self.term.shiftOut()
- self.term.write("World\n")
- self.term.shiftIn()
- self.term.write("Bye!\n")
-
- g = G0
- h = 0
- for s in (s1, s2, s3):
- for i in range(len(s)):
- ch = self.term.getCharacter(i, h)
- self.assertEqual(ch[0], s[i])
- self.assertEqual(ch[1].charset, g)
- g = g == G0 and G1 or G0
- h += 1
-
- def testGraphicRendition(self):
- self.term.selectGraphicRendition(BOLD, UNDERLINE, BLINK, REVERSE_VIDEO)
- self.term.write('W')
- self.term.selectGraphicRendition(NORMAL)
- self.term.write('X')
- self.term.selectGraphicRendition(BLINK)
- self.term.write('Y')
- self.term.selectGraphicRendition(BOLD)
- self.term.write('Z')
-
- ch = self.term.getCharacter(0, 0)
- self.assertEqual(ch[0], 'W')
- self.assertTrue(ch[1].bold)
- self.assertTrue(ch[1].underline)
- self.assertTrue(ch[1].blink)
- self.assertTrue(ch[1].reverseVideo)
-
- ch = self.term.getCharacter(1, 0)
- self.assertEqual(ch[0], 'X')
- self.assertFalse(ch[1].bold)
- self.assertFalse(ch[1].underline)
- self.assertFalse(ch[1].blink)
- self.assertFalse(ch[1].reverseVideo)
-
- ch = self.term.getCharacter(2, 0)
- self.assertEqual(ch[0], 'Y')
- self.assertTrue(ch[1].blink)
- self.assertFalse(ch[1].bold)
- self.assertFalse(ch[1].underline)
- self.assertFalse(ch[1].reverseVideo)
-
- ch = self.term.getCharacter(3, 0)
- self.assertEqual(ch[0], 'Z')
- self.assertTrue(ch[1].blink)
- self.assertTrue(ch[1].bold)
- self.assertFalse(ch[1].underline)
- self.assertFalse(ch[1].reverseVideo)
-
- def testColorAttributes(self):
- s1 = "Merry xmas"
- s2 = "Just kidding"
- self.term.selectGraphicRendition(helper.FOREGROUND + helper.RED,
- helper.BACKGROUND + helper.GREEN)
- self.term.write(s1 + "\n")
- self.term.selectGraphicRendition(NORMAL)
- self.term.write(s2 + "\n")
-
- for i in range(len(s1)):
- ch = self.term.getCharacter(i, 0)
- self.assertEqual(ch[0], s1[i])
- self.assertEqual(ch[1].charset, G0)
- self.assertEqual(ch[1].bold, False)
- self.assertEqual(ch[1].underline, False)
- self.assertEqual(ch[1].blink, False)
- self.assertEqual(ch[1].reverseVideo, False)
- self.assertEqual(ch[1].foreground, helper.RED)
- self.assertEqual(ch[1].background, helper.GREEN)
-
- for i in range(len(s2)):
- ch = self.term.getCharacter(i, 1)
- self.assertEqual(ch[0], s2[i])
- self.assertEqual(ch[1].charset, G0)
- self.assertEqual(ch[1].bold, False)
- self.assertEqual(ch[1].underline, False)
- self.assertEqual(ch[1].blink, False)
- self.assertEqual(ch[1].reverseVideo, False)
- self.assertEqual(ch[1].foreground, helper.WHITE)
- self.assertEqual(ch[1].background, helper.BLACK)
-
- def testEraseLine(self):
- s1 = 'line 1'
- s2 = 'line 2'
- s3 = 'line 3'
- self.term.write('\n'.join((s1, s2, s3)) + '\n')
- self.term.cursorPosition(1, 1)
- self.term.eraseLine()
-
- self.assertEqual(
- str(self.term),
- s1 + '\n' +
- '\n' +
- s3 + '\n' +
- '\n' * (HEIGHT - 4))
-
- def testEraseToLineEnd(self):
- s = 'Hello, world.'
- self.term.write(s)
- self.term.cursorBackward(5)
- self.term.eraseToLineEnd()
- self.assertEqual(
- str(self.term),
- s[:-5] + '\n' +
- '\n' * (HEIGHT - 2))
-
- def testEraseToLineBeginning(self):
- s = 'Hello, world.'
- self.term.write(s)
- self.term.cursorBackward(5)
- self.term.eraseToLineBeginning()
- self.assertEqual(
- str(self.term),
- s[-4:].rjust(len(s)) + '\n' +
- '\n' * (HEIGHT - 2))
-
- def testEraseDisplay(self):
- self.term.write('Hello world\n')
- self.term.write('Goodbye world\n')
- self.term.eraseDisplay()
-
- self.assertEqual(
- str(self.term),
- '\n' * (HEIGHT - 1))
-
- def testEraseToDisplayEnd(self):
- s1 = "Hello world"
- s2 = "Goodbye world"
- self.term.write('\n'.join((s1, s2, '')))
- self.term.cursorPosition(5, 1)
- self.term.eraseToDisplayEnd()
-
- self.assertEqual(
- str(self.term),
- s1 + '\n' +
- s2[:5] + '\n' +
- '\n' * (HEIGHT - 3))
-
- def testEraseToDisplayBeginning(self):
- s1 = "Hello world"
- s2 = "Goodbye world"
- self.term.write('\n'.join((s1, s2)))
- self.term.cursorPosition(5, 1)
- self.term.eraseToDisplayBeginning()
-
- self.assertEqual(
- str(self.term),
- '\n' +
- s2[6:].rjust(len(s2)) + '\n' +
- '\n' * (HEIGHT - 3))
-
- def testLineInsertion(self):
- s1 = "Hello world"
- s2 = "Goodbye world"
- self.term.write('\n'.join((s1, s2)))
- self.term.cursorPosition(7, 1)
- self.term.insertLine()
-
- self.assertEqual(
- str(self.term),
- s1 + '\n' +
- '\n' +
- s2 + '\n' +
- '\n' * (HEIGHT - 4))
-
- def testLineDeletion(self):
- s1 = "Hello world"
- s2 = "Middle words"
- s3 = "Goodbye world"
- self.term.write('\n'.join((s1, s2, s3)))
- self.term.cursorPosition(9, 1)
- self.term.deleteLine()
-
- self.assertEqual(
- str(self.term),
- s1 + '\n' +
- s3 + '\n' +
- '\n' * (HEIGHT - 3))
-
-class FakeDelayedCall:
- called = False
- cancelled = False
- def __init__(self, fs, timeout, f, a, kw):
- self.fs = fs
- self.timeout = timeout
- self.f = f
- self.a = a
- self.kw = kw
-
- def active(self):
- return not (self.cancelled or self.called)
-
- def cancel(self):
- self.cancelled = True
-# self.fs.calls.remove(self)
-
- def call(self):
- self.called = True
- self.f(*self.a, **self.kw)
-
-class FakeScheduler:
- def __init__(self):
- self.calls = []
-
- def callLater(self, timeout, f, *a, **kw):
- self.calls.append(FakeDelayedCall(self, timeout, f, a, kw))
- return self.calls[-1]
-
-class ExpectTestCase(unittest.TestCase):
- def setUp(self):
- self.term = helper.ExpectableBuffer()
- self.term.connectionMade()
- self.fs = FakeScheduler()
-
- def testSimpleString(self):
- result = []
- d = self.term.expect("hello world", timeout=1, scheduler=self.fs)
- d.addCallback(result.append)
-
- self.term.write("greeting puny earthlings\n")
- self.assertFalse(result)
- self.term.write("hello world\n")
- self.assertTrue(result)
- self.assertEqual(result[0].group(), "hello world")
- self.assertEqual(len(self.fs.calls), 1)
- self.assertFalse(self.fs.calls[0].active())
-
- def testBrokenUpString(self):
- result = []
- d = self.term.expect("hello world")
- d.addCallback(result.append)
-
- self.assertFalse(result)
- self.term.write("hello ")
- self.assertFalse(result)
- self.term.write("worl")
- self.assertFalse(result)
- self.term.write("d")
- self.assertTrue(result)
- self.assertEqual(result[0].group(), "hello world")
-
-
- def testMultiple(self):
- result = []
- d1 = self.term.expect("hello ")
- d1.addCallback(result.append)
- d2 = self.term.expect("world")
- d2.addCallback(result.append)
-
- self.assertFalse(result)
- self.term.write("hello")
- self.assertFalse(result)
- self.term.write(" ")
- self.assertEqual(len(result), 1)
- self.term.write("world")
- self.assertEqual(len(result), 2)
- self.assertEqual(result[0].group(), "hello ")
- self.assertEqual(result[1].group(), "world")
-
- def testSynchronous(self):
- self.term.write("hello world")
-
- result = []
- d = self.term.expect("hello world")
- d.addCallback(result.append)
- self.assertTrue(result)
- self.assertEqual(result[0].group(), "hello world")
-
- def testMultipleSynchronous(self):
- self.term.write("goodbye world")
-
- result = []
- d1 = self.term.expect("bye")
- d1.addCallback(result.append)
- d2 = self.term.expect("world")
- d2.addCallback(result.append)
-
- self.assertEqual(len(result), 2)
- self.assertEqual(result[0].group(), "bye")
- self.assertEqual(result[1].group(), "world")
-
- def _cbTestTimeoutFailure(self, res):
- self.assertTrue(hasattr(res, 'type'))
- self.assertEqual(res.type, helper.ExpectationTimeout)
-
- def testTimeoutFailure(self):
- d = self.term.expect("hello world", timeout=1, scheduler=self.fs)
- d.addBoth(self._cbTestTimeoutFailure)
- self.fs.calls[0].call()
-
- def testOverlappingTimeout(self):
- self.term.write("not zoomtastic")
-
- result = []
- d1 = self.term.expect("hello world", timeout=1, scheduler=self.fs)
- d1.addBoth(self._cbTestTimeoutFailure)
- d2 = self.term.expect("zoom")
- d2.addCallback(result.append)
-
- self.fs.calls[0].call()
-
- self.assertEqual(len(result), 1)
- self.assertEqual(result[0].group(), "zoom")
-
-
-
-class CharacterAttributeTests(unittest.TestCase):
- """
- Tests for L{twisted.conch.insults.helper.CharacterAttribute}.
- """
- def test_equality(self):
- """
- L{CharacterAttribute}s must have matching character attribute values
- (bold, blink, underline, etc) with the same values to be considered
- equal.
- """
- self.assertEqual(
- helper.CharacterAttribute(),
- helper.CharacterAttribute())
-
- self.assertEqual(
- helper.CharacterAttribute(),
- helper.CharacterAttribute(charset=G0))
-
- self.assertEqual(
- helper.CharacterAttribute(
- bold=True, underline=True, blink=False, reverseVideo=True,
- foreground=helper.BLUE),
- helper.CharacterAttribute(
- bold=True, underline=True, blink=False, reverseVideo=True,
- foreground=helper.BLUE))
-
- self.assertNotEqual(
- helper.CharacterAttribute(),
- helper.CharacterAttribute(charset=G1))
-
- self.assertNotEqual(
- helper.CharacterAttribute(bold=True),
- helper.CharacterAttribute(bold=False))
-
-
- def test_wantOneDeprecated(self):
- """
- L{twisted.conch.insults.helper.CharacterAttribute.wantOne} emits
- a deprecation warning when invoked.
- """
- # Trigger the deprecation warning.
- helper._FormattingState().wantOne(bold=True)
-
- warningsShown = self.flushWarnings([self.test_wantOneDeprecated])
- self.assertEqual(len(warningsShown), 1)
- self.assertEqual(warningsShown[0]['category'], DeprecationWarning)
- self.assertEqual(
- warningsShown[0]['message'],
- 'twisted.conch.insults.helper.wantOne was deprecated in '
- 'Twisted 13.1.0')
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_insults.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_insults.py
deleted file mode 100644
index b3b0dfa..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_insults.py
+++ /dev/null
@@ -1,496 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_insults -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-from twisted.trial import unittest
-from twisted.test.proto_helpers import StringTransport
-
-from twisted.conch.insults.insults import ServerProtocol, ClientProtocol
-from twisted.conch.insults.insults import CS_UK, CS_US, CS_DRAWING, CS_ALTERNATE, CS_ALTERNATE_SPECIAL
-from twisted.conch.insults.insults import G0, G1
-from twisted.conch.insults.insults import modes
-
-def _getattr(mock, name):
- return super(Mock, mock).__getattribute__(name)
-
-def occurrences(mock):
- return _getattr(mock, 'occurrences')
-
-def methods(mock):
- return _getattr(mock, 'methods')
-
-def _append(mock, obj):
- occurrences(mock).append(obj)
-
-default = object()
-
-class Mock(object):
- callReturnValue = default
-
- def __init__(self, methods=None, callReturnValue=default):
- """
- @param methods: Mapping of names to return values
- @param callReturnValue: object __call__ should return
- """
- self.occurrences = []
- if methods is None:
- methods = {}
- self.methods = methods
- if callReturnValue is not default:
- self.callReturnValue = callReturnValue
-
- def __call__(self, *a, **kw):
- returnValue = _getattr(self, 'callReturnValue')
- if returnValue is default:
- returnValue = Mock()
- # _getattr(self, 'occurrences').append(('__call__', returnValue, a, kw))
- _append(self, ('__call__', returnValue, a, kw))
- return returnValue
-
- def __getattribute__(self, name):
- methods = _getattr(self, 'methods')
- if name in methods:
- attrValue = Mock(callReturnValue=methods[name])
- else:
- attrValue = Mock()
- # _getattr(self, 'occurrences').append((name, attrValue))
- _append(self, (name, attrValue))
- return attrValue
-
-class MockMixin:
- def assertCall(self, occurrence, methodName, expectedPositionalArgs=(),
- expectedKeywordArgs={}):
- attr, mock = occurrence
- self.assertEqual(attr, methodName)
- self.assertEqual(len(occurrences(mock)), 1)
- [(call, result, args, kw)] = occurrences(mock)
- self.assertEqual(call, "__call__")
- self.assertEqual(args, expectedPositionalArgs)
- self.assertEqual(kw, expectedKeywordArgs)
- return result
-
-
-_byteGroupingTestTemplate = """\
-def testByte%(groupName)s(self):
- transport = StringTransport()
- proto = Mock()
- parser = self.protocolFactory(lambda: proto)
- parser.factory = self
- parser.makeConnection(transport)
-
- bytes = self.TEST_BYTES
- while bytes:
- chunk = bytes[:%(bytesPer)d]
- bytes = bytes[%(bytesPer)d:]
- parser.dataReceived(chunk)
-
- self.verifyResults(transport, proto, parser)
-"""
-class ByteGroupingsMixin(MockMixin):
- protocolFactory = None
-
- for word, n in [('Pairs', 2), ('Triples', 3), ('Quads', 4), ('Quints', 5), ('Sexes', 6)]:
- exec _byteGroupingTestTemplate % {'groupName': word, 'bytesPer': n}
- del word, n
-
- def verifyResults(self, transport, proto, parser):
- result = self.assertCall(occurrences(proto).pop(0), "makeConnection", (parser,))
- self.assertEqual(occurrences(result), [])
-
-del _byteGroupingTestTemplate
-
-class ServerArrowKeys(ByteGroupingsMixin, unittest.TestCase):
- protocolFactory = ServerProtocol
-
- # All the arrow keys once
- TEST_BYTES = '\x1b[A\x1b[B\x1b[C\x1b[D'
-
- def verifyResults(self, transport, proto, parser):
- ByteGroupingsMixin.verifyResults(self, transport, proto, parser)
-
- for arrow in (parser.UP_ARROW, parser.DOWN_ARROW,
- parser.RIGHT_ARROW, parser.LEFT_ARROW):
- result = self.assertCall(occurrences(proto).pop(0), "keystrokeReceived", (arrow, None))
- self.assertEqual(occurrences(result), [])
- self.assertFalse(occurrences(proto))
-
-
-class PrintableCharacters(ByteGroupingsMixin, unittest.TestCase):
- protocolFactory = ServerProtocol
-
- # Some letters and digits, first on their own, then capitalized,
- # then modified with alt
-
- TEST_BYTES = 'abc123ABC!@#\x1ba\x1bb\x1bc\x1b1\x1b2\x1b3'
-
- def verifyResults(self, transport, proto, parser):
- ByteGroupingsMixin.verifyResults(self, transport, proto, parser)
-
- for char in 'abc123ABC!@#':
- result = self.assertCall(occurrences(proto).pop(0), "keystrokeReceived", (char, None))
- self.assertEqual(occurrences(result), [])
-
- for char in 'abc123':
- result = self.assertCall(occurrences(proto).pop(0), "keystrokeReceived", (char, parser.ALT))
- self.assertEqual(occurrences(result), [])
-
- occs = occurrences(proto)
- self.assertFalse(occs, "%r should have been []" % (occs,))
-
-class ServerFunctionKeys(ByteGroupingsMixin, unittest.TestCase):
- """Test for parsing and dispatching function keys (F1 - F12)
- """
- protocolFactory = ServerProtocol
-
- byteList = []
- for bytes in ('OP', 'OQ', 'OR', 'OS', # F1 - F4
- '15~', '17~', '18~', '19~', # F5 - F8
- '20~', '21~', '23~', '24~'): # F9 - F12
- byteList.append('\x1b[' + bytes)
- TEST_BYTES = ''.join(byteList)
- del byteList, bytes
-
- def verifyResults(self, transport, proto, parser):
- ByteGroupingsMixin.verifyResults(self, transport, proto, parser)
- for funcNum in range(1, 13):
- funcArg = getattr(parser, 'F%d' % (funcNum,))
- result = self.assertCall(occurrences(proto).pop(0), "keystrokeReceived", (funcArg, None))
- self.assertEqual(occurrences(result), [])
- self.assertFalse(occurrences(proto))
-
-class ClientCursorMovement(ByteGroupingsMixin, unittest.TestCase):
- protocolFactory = ClientProtocol
-
- d2 = "\x1b[2B"
- r4 = "\x1b[4C"
- u1 = "\x1b[A"
- l2 = "\x1b[2D"
- # Move the cursor down two, right four, up one, left two, up one, left two
- TEST_BYTES = d2 + r4 + u1 + l2 + u1 + l2
- del d2, r4, u1, l2
-
- def verifyResults(self, transport, proto, parser):
- ByteGroupingsMixin.verifyResults(self, transport, proto, parser)
-
- for (method, count) in [('Down', 2), ('Forward', 4), ('Up', 1),
- ('Backward', 2), ('Up', 1), ('Backward', 2)]:
- result = self.assertCall(occurrences(proto).pop(0), "cursor" + method, (count,))
- self.assertEqual(occurrences(result), [])
- self.assertFalse(occurrences(proto))
-
-class ClientControlSequences(unittest.TestCase, MockMixin):
- def setUp(self):
- self.transport = StringTransport()
- self.proto = Mock()
- self.parser = ClientProtocol(lambda: self.proto)
- self.parser.factory = self
- self.parser.makeConnection(self.transport)
- result = self.assertCall(occurrences(self.proto).pop(0), "makeConnection", (self.parser,))
- self.assertFalse(occurrences(result))
-
- def testSimpleCardinals(self):
- self.parser.dataReceived(
- ''.join([''.join(['\x1b[' + str(n) + ch for n in ('', 2, 20, 200)]) for ch in 'BACD']))
- occs = occurrences(self.proto)
-
- for meth in ("Down", "Up", "Forward", "Backward"):
- for count in (1, 2, 20, 200):
- result = self.assertCall(occs.pop(0), "cursor" + meth, (count,))
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testScrollRegion(self):
- self.parser.dataReceived('\x1b[5;22r\x1b[r')
- occs = occurrences(self.proto)
-
- result = self.assertCall(occs.pop(0), "setScrollRegion", (5, 22))
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "setScrollRegion", (None, None))
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testHeightAndWidth(self):
- self.parser.dataReceived("\x1b#3\x1b#4\x1b#5\x1b#6")
- occs = occurrences(self.proto)
-
- result = self.assertCall(occs.pop(0), "doubleHeightLine", (True,))
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "doubleHeightLine", (False,))
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "singleWidthLine")
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "doubleWidthLine")
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testCharacterSet(self):
- self.parser.dataReceived(
- ''.join([''.join(['\x1b' + g + n for n in 'AB012']) for g in '()']))
- occs = occurrences(self.proto)
-
- for which in (G0, G1):
- for charset in (CS_UK, CS_US, CS_DRAWING, CS_ALTERNATE, CS_ALTERNATE_SPECIAL):
- result = self.assertCall(occs.pop(0), "selectCharacterSet", (charset, which))
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testShifting(self):
- self.parser.dataReceived("\x15\x14")
- occs = occurrences(self.proto)
-
- result = self.assertCall(occs.pop(0), "shiftIn")
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "shiftOut")
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testSingleShifts(self):
- self.parser.dataReceived("\x1bN\x1bO")
- occs = occurrences(self.proto)
-
- result = self.assertCall(occs.pop(0), "singleShift2")
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "singleShift3")
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testKeypadMode(self):
- self.parser.dataReceived("\x1b=\x1b>")
- occs = occurrences(self.proto)
-
- result = self.assertCall(occs.pop(0), "applicationKeypadMode")
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "numericKeypadMode")
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testCursor(self):
- self.parser.dataReceived("\x1b7\x1b8")
- occs = occurrences(self.proto)
-
- result = self.assertCall(occs.pop(0), "saveCursor")
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "restoreCursor")
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testReset(self):
- self.parser.dataReceived("\x1bc")
- occs = occurrences(self.proto)
-
- result = self.assertCall(occs.pop(0), "reset")
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testIndex(self):
- self.parser.dataReceived("\x1bD\x1bM\x1bE")
- occs = occurrences(self.proto)
-
- result = self.assertCall(occs.pop(0), "index")
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "reverseIndex")
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "nextLine")
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testModes(self):
- self.parser.dataReceived(
- "\x1b[" + ';'.join(map(str, [modes.KAM, modes.IRM, modes.LNM])) + "h")
- self.parser.dataReceived(
- "\x1b[" + ';'.join(map(str, [modes.KAM, modes.IRM, modes.LNM])) + "l")
- occs = occurrences(self.proto)
-
- result = self.assertCall(occs.pop(0), "setModes", ([modes.KAM, modes.IRM, modes.LNM],))
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "resetModes", ([modes.KAM, modes.IRM, modes.LNM],))
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testErasure(self):
- self.parser.dataReceived(
- "\x1b[K\x1b[1K\x1b[2K\x1b[J\x1b[1J\x1b[2J\x1b[3P")
- occs = occurrences(self.proto)
-
- for meth in ("eraseToLineEnd", "eraseToLineBeginning", "eraseLine",
- "eraseToDisplayEnd", "eraseToDisplayBeginning",
- "eraseDisplay"):
- result = self.assertCall(occs.pop(0), meth)
- self.assertFalse(occurrences(result))
-
- result = self.assertCall(occs.pop(0), "deleteCharacter", (3,))
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testLineDeletion(self):
- self.parser.dataReceived("\x1b[M\x1b[3M")
- occs = occurrences(self.proto)
-
- for arg in (1, 3):
- result = self.assertCall(occs.pop(0), "deleteLine", (arg,))
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testLineInsertion(self):
- self.parser.dataReceived("\x1b[L\x1b[3L")
- occs = occurrences(self.proto)
-
- for arg in (1, 3):
- result = self.assertCall(occs.pop(0), "insertLine", (arg,))
- self.assertFalse(occurrences(result))
- self.assertFalse(occs)
-
- def testCursorPosition(self):
- methods(self.proto)['reportCursorPosition'] = (6, 7)
- self.parser.dataReceived("\x1b[6n")
- self.assertEqual(self.transport.value(), "\x1b[7;8R")
- occs = occurrences(self.proto)
-
- result = self.assertCall(occs.pop(0), "reportCursorPosition")
- # This isn't really an interesting assert, since it only tests that
- # our mock setup is working right, but I'll include it anyway.
- self.assertEqual(result, (6, 7))
-
-
- def test_applicationDataBytes(self):
- """
- Contiguous non-control bytes are passed to a single call to the
- C{write} method of the terminal to which the L{ClientProtocol} is
- connected.
- """
- occs = occurrences(self.proto)
- self.parser.dataReceived('a')
- self.assertCall(occs.pop(0), "write", ("a",))
- self.parser.dataReceived('bc')
- self.assertCall(occs.pop(0), "write", ("bc",))
-
-
- def _applicationDataTest(self, data, calls):
- occs = occurrences(self.proto)
- self.parser.dataReceived(data)
- while calls:
- self.assertCall(occs.pop(0), *calls.pop(0))
- self.assertFalse(occs, "No other calls should happen: %r" % (occs,))
-
-
- def test_shiftInAfterApplicationData(self):
- """
- Application data bytes followed by a shift-in command are passed to a
- call to C{write} before the terminal's C{shiftIn} method is called.
- """
- self._applicationDataTest(
- 'ab\x15', [
- ("write", ("ab",)),
- ("shiftIn",)])
-
-
- def test_shiftOutAfterApplicationData(self):
- """
- Application data bytes followed by a shift-out command are passed to a
- call to C{write} before the terminal's C{shiftOut} method is called.
- """
- self._applicationDataTest(
- 'ab\x14', [
- ("write", ("ab",)),
- ("shiftOut",)])
-
-
- def test_cursorBackwardAfterApplicationData(self):
- """
- Application data bytes followed by a cursor-backward command are passed
- to a call to C{write} before the terminal's C{cursorBackward} method is
- called.
- """
- self._applicationDataTest(
- 'ab\x08', [
- ("write", ("ab",)),
- ("cursorBackward",)])
-
-
- def test_escapeAfterApplicationData(self):
- """
- Application data bytes followed by an escape character are passed to a
- call to C{write} before the terminal's handler method for the escape is
- called.
- """
- # Test a short escape
- self._applicationDataTest(
- 'ab\x1bD', [
- ("write", ("ab",)),
- ("index",)])
-
- # And a long escape
- self._applicationDataTest(
- 'ab\x1b[4h', [
- ("write", ("ab",)),
- ("setModes", ([4],))])
-
- # There's some other cases too, but they're all handled by the same
- # codepaths as above.
-
-
-
-class ServerProtocolOutputTests(unittest.TestCase):
- """
- Tests for the bytes L{ServerProtocol} writes to its transport when its
- methods are called.
- """
- def test_nextLine(self):
- """
- L{ServerProtocol.nextLine} writes C{"\r\n"} to its transport.
- """
- # Why doesn't it write ESC E? Because ESC E is poorly supported. For
- # example, gnome-terminal (many different versions) fails to scroll if
- # it receives ESC E and the cursor is already on the last row.
- protocol = ServerProtocol()
- transport = StringTransport()
- protocol.makeConnection(transport)
- protocol.nextLine()
- self.assertEqual(transport.value(), "\r\n")
-
-
-
-class Deprecations(unittest.TestCase):
- """
- Tests to ensure deprecation of L{insults.colors} and L{insults.client}
- """
-
- def ensureDeprecated(self, message):
- """
- Ensures that the correct deprecation warning was issued.
- """
- warnings = self.flushWarnings()
- self.assertIs(warnings[0]['category'], DeprecationWarning)
- self.assertEqual(warnings[0]['message'], message)
- self.assertEqual(len(warnings), 1)
-
-
- def test_colors(self):
- """
- The L{insults.colors} module is deprecated
- """
- from twisted.conch.insults import colors
- self.ensureDeprecated("twisted.conch.insults.colors was deprecated "
- "in Twisted 10.1.0: Please use "
- "twisted.conch.insults.helper instead.")
-
-
- def test_client(self):
- """
- The L{insults.client} module is deprecated
- """
- from twisted.conch.insults import client
- self.ensureDeprecated("twisted.conch.insults.client was deprecated "
- "in Twisted 10.1.0: Please use "
- "twisted.conch.insults.insults instead.")
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_keys.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_keys.py
deleted file mode 100644
index 0923974..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_keys.py
+++ /dev/null
@@ -1,644 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.ssh.keys}.
-"""
-
-try:
- import Crypto.Cipher.DES3
-except ImportError:
- # we'll have to skip these tests without PyCypto and pyasn1
- Crypto = None
-
-try:
- import pyasn1
-except ImportError:
- pyasn1 = None
-
-if Crypto and pyasn1:
- from twisted.conch.ssh import keys, common, sexpy
-
-import os, base64
-from hashlib import sha1
-from twisted.conch.test import keydata
-from twisted.python import randbytes
-from twisted.trial import unittest
-
-
-class HelpersTestCase(unittest.TestCase):
-
- if Crypto is None:
- skip = "cannot run w/o PyCrypto"
- if pyasn1 is None:
- skip = "Cannot run without PyASN1"
-
- def setUp(self):
- self._secureRandom = randbytes.secureRandom
- randbytes.secureRandom = lambda x: '\x55' * x
-
- def tearDown(self):
- randbytes.secureRandom = self._secureRandom
- self._secureRandom = None
-
- def test_pkcs1(self):
- """
- Test Public Key Cryptographic Standard #1 functions.
- """
- data = 'ABC'
- messageSize = 6
- self.assertEqual(keys.pkcs1Pad(data, messageSize),
- '\x01\xff\x00ABC')
- hash = sha1().digest()
- messageSize = 40
- self.assertEqual(keys.pkcs1Digest('', messageSize),
- '\x01\xff\xff\xff\x00' + keys.ID_SHA1 + hash)
-
- def _signRSA(self, data):
- key = keys.Key.fromString(keydata.privateRSA_openssh)
- sig = key.sign(data)
- return key.keyObject, sig
-
- def _signDSA(self, data):
- key = keys.Key.fromString(keydata.privateDSA_openssh)
- sig = key.sign(data)
- return key.keyObject, sig
-
- def test_signRSA(self):
- """
- Test that RSA keys return appropriate signatures.
- """
- data = 'data'
- key, sig = self._signRSA(data)
- sigData = keys.pkcs1Digest(data, keys.lenSig(key))
- v = key.sign(sigData, '')[0]
- self.assertEqual(sig, common.NS('ssh-rsa') + common.MP(v))
- return key, sig
-
- def test_signDSA(self):
- """
- Test that DSA keys return appropriate signatures.
- """
- data = 'data'
- key, sig = self._signDSA(data)
- sigData = sha1(data).digest()
- v = key.sign(sigData, '\x55' * 19)
- self.assertEqual(sig, common.NS('ssh-dss') + common.NS(
- Crypto.Util.number.long_to_bytes(v[0], 20) +
- Crypto.Util.number.long_to_bytes(v[1], 20)))
- return key, sig
-
-
- def test_objectType(self):
- """
- Test that objectType, returns the correct type for objects.
- """
- self.assertEqual(keys.objectType(keys.Key.fromString(
- keydata.privateRSA_openssh).keyObject), 'ssh-rsa')
- self.assertEqual(keys.objectType(keys.Key.fromString(
- keydata.privateDSA_openssh).keyObject), 'ssh-dss')
- self.assertRaises(keys.BadKeyError, keys.objectType, None)
-
-
-class KeyTestCase(unittest.TestCase):
-
- if Crypto is None:
- skip = "cannot run w/o PyCrypto"
- if pyasn1 is None:
- skip = "Cannot run without PyASN1"
-
- def setUp(self):
- self.rsaObj = Crypto.PublicKey.RSA.construct((1L, 2L, 3L, 4L, 5L))
- self.dsaObj = Crypto.PublicKey.DSA.construct((1L, 2L, 3L, 4L, 5L))
- self.rsaSignature = ('\x00\x00\x00\x07ssh-rsa\x00'
- '\x00\x00`N\xac\xb4@qK\xa0(\xc3\xf2h \xd3\xdd\xee6Np\x9d_'
- '\xb0>\xe3\x0c(L\x9d{\txUd|!\xf6m\x9c\xd3\x93\x842\x7fU'
- '\x05\xf4\xf7\xfaD\xda\xce\x81\x8ea\x7f=Y\xed*\xb7\xba\x81'
- '\xf2\xad\xda\xeb(\x97\x03S\x08\x81\xc7\xb1\xb7\xe6\xe3'
- '\xcd*\xd4\xbd\xc0wt\xf7y\xcd\xf0\xb7\x7f\xfb\x1e>\xf9r'
- '\x8c\xba')
- self.dsaSignature = ('\x00\x00\x00\x07ssh-dss\x00\x00'
- '\x00(\x18z)H\x8a\x1b\xc6\r\xbbq\xa2\xd7f\x7f$\xa7\xbf'
- '\xe8\x87\x8c\x88\xef\xd9k\x1a\x98\xdd{=\xdec\x18\t\xe3'
- '\x87\xa9\xc72h\x95')
- self.oldSecureRandom = randbytes.secureRandom
- randbytes.secureRandom = lambda x: '\xff' * x
- self.keyFile = self.mktemp()
- file(self.keyFile, 'wb').write(keydata.privateRSA_lsh)
-
- def tearDown(self):
- randbytes.secureRandom = self.oldSecureRandom
- del self.oldSecureRandom
- os.unlink(self.keyFile)
-
- def test__guessStringType(self):
- """
- Test that the _guessStringType method guesses string types
- correctly.
- """
- self.assertEqual(keys.Key._guessStringType(keydata.publicRSA_openssh),
- 'public_openssh')
- self.assertEqual(keys.Key._guessStringType(keydata.publicDSA_openssh),
- 'public_openssh')
- self.assertEqual(keys.Key._guessStringType(
- keydata.privateRSA_openssh), 'private_openssh')
- self.assertEqual(keys.Key._guessStringType(
- keydata.privateDSA_openssh), 'private_openssh')
- self.assertEqual(keys.Key._guessStringType(keydata.publicRSA_lsh),
- 'public_lsh')
- self.assertEqual(keys.Key._guessStringType(keydata.publicDSA_lsh),
- 'public_lsh')
- self.assertEqual(keys.Key._guessStringType(keydata.privateRSA_lsh),
- 'private_lsh')
- self.assertEqual(keys.Key._guessStringType(keydata.privateDSA_lsh),
- 'private_lsh')
- self.assertEqual(keys.Key._guessStringType(
- keydata.privateRSA_agentv3), 'agentv3')
- self.assertEqual(keys.Key._guessStringType(
- keydata.privateDSA_agentv3), 'agentv3')
- self.assertEqual(keys.Key._guessStringType(
- '\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x01\x01'),
- 'blob')
- self.assertEqual(keys.Key._guessStringType(
- '\x00\x00\x00\x07ssh-dss\x00\x00\x00\x01\x01'),
- 'blob')
- self.assertEqual(keys.Key._guessStringType('not a key'),
- None)
-
- def _testPublicPrivateFromString(self, public, private, type, data):
- self._testPublicFromString(public, type, data)
- self._testPrivateFromString(private, type, data)
-
- def _testPublicFromString(self, public, type, data):
- publicKey = keys.Key.fromString(public)
- self.assertTrue(publicKey.isPublic())
- self.assertEqual(publicKey.type(), type)
- for k, v in publicKey.data().items():
- self.assertEqual(data[k], v)
-
- def _testPrivateFromString(self, private, type, data):
- privateKey = keys.Key.fromString(private)
- self.assertFalse(privateKey.isPublic())
- self.assertEqual(privateKey.type(), type)
- for k, v in data.items():
- self.assertEqual(privateKey.data()[k], v)
-
- def test_fromOpenSSH(self):
- """
- Test that keys are correctly generated from OpenSSH strings.
- """
- self._testPublicPrivateFromString(keydata.publicRSA_openssh,
- keydata.privateRSA_openssh, 'RSA', keydata.RSAData)
- self.assertEqual(keys.Key.fromString(
- keydata.privateRSA_openssh_encrypted,
- passphrase='encrypted'),
- keys.Key.fromString(keydata.privateRSA_openssh))
- self.assertEqual(keys.Key.fromString(
- keydata.privateRSA_openssh_alternate),
- keys.Key.fromString(keydata.privateRSA_openssh))
- self._testPublicPrivateFromString(keydata.publicDSA_openssh,
- keydata.privateDSA_openssh, 'DSA', keydata.DSAData)
-
- def test_fromOpenSSH_with_whitespace(self):
- """
- If key strings have trailing whitespace, it should be ignored.
- """
- # from bug #3391, since our test key data doesn't have
- # an issue with appended newlines
- privateDSAData = """-----BEGIN DSA PRIVATE KEY-----
-MIIBuwIBAAKBgQDylESNuc61jq2yatCzZbenlr9llG+p9LhIpOLUbXhhHcwC6hrh
-EZIdCKqTO0USLrGoP5uS9UHAUoeN62Z0KXXWTwOWGEQn/syyPzNJtnBorHpNUT9D
-Qzwl1yUa53NNgEctpo4NoEFOx8PuU6iFLyvgHCjNn2MsuGuzkZm7sI9ZpQIVAJiR
-9dPc08KLdpJyRxz8T74b4FQRAoGAGBc4Z5Y6R/HZi7AYM/iNOM8su6hrk8ypkBwR
-a3Dbhzk97fuV3SF1SDrcQu4zF7c4CtH609N5nfZs2SUjLLGPWln83Ysb8qhh55Em
-AcHXuROrHS/sDsnqu8FQp86MaudrqMExCOYyVPE7jaBWW+/JWFbKCxmgOCSdViUJ
-esJpBFsCgYEA7+jtVvSt9yrwsS/YU1QGP5wRAiDYB+T5cK4HytzAqJKRdC5qS4zf
-C7R0eKcDHHLMYO39aPnCwXjscisnInEhYGNblTDyPyiyNxAOXuC8x7luTmwzMbNJ
-/ow0IqSj0VF72VJN9uSoPpFd4lLT0zN8v42RWja0M8ohWNf+YNJluPgCFE0PT4Vm
-SUrCyZXsNh6VXwjs3gKQ
------END DSA PRIVATE KEY-----"""
- self.assertEqual(keys.Key.fromString(privateDSAData),
- keys.Key.fromString(privateDSAData + '\n'))
-
- def test_fromNewerOpenSSH(self):
- """
- Newer versions of OpenSSH generate encrypted keys which have a longer
- IV than the older versions. These newer keys are also loaded.
- """
- key = keys.Key.fromString(keydata.privateRSA_openssh_encrypted_aes,
- passphrase='testxp')
- self.assertEqual(key.type(), 'RSA')
- key2 = keys.Key.fromString(
- keydata.privateRSA_openssh_encrypted_aes + '\n',
- passphrase='testxp')
- self.assertEqual(key, key2)
-
-
- def test_fromLSH(self):
- """
- Test that keys are correctly generated from LSH strings.
- """
- self._testPublicPrivateFromString(keydata.publicRSA_lsh,
- keydata.privateRSA_lsh, 'RSA', keydata.RSAData)
- self._testPublicPrivateFromString(keydata.publicDSA_lsh,
- keydata.privateDSA_lsh, 'DSA', keydata.DSAData)
- sexp = sexpy.pack([['public-key', ['bad-key', ['p', '2']]]])
- self.assertRaises(keys.BadKeyError, keys.Key.fromString,
- data='{'+base64.encodestring(sexp)+'}')
- sexp = sexpy.pack([['private-key', ['bad-key', ['p', '2']]]])
- self.assertRaises(keys.BadKeyError, keys.Key.fromString,
- sexp)
-
- def test_fromAgentv3(self):
- """
- Test that keys are correctly generated from Agent v3 strings.
- """
- self._testPrivateFromString(keydata.privateRSA_agentv3, 'RSA',
- keydata.RSAData)
- self._testPrivateFromString(keydata.privateDSA_agentv3, 'DSA',
- keydata.DSAData)
- self.assertRaises(keys.BadKeyError, keys.Key.fromString,
- '\x00\x00\x00\x07ssh-foo'+'\x00\x00\x00\x01\x01'*5)
-
- def test_fromStringErrors(self):
- """
- keys.Key.fromString should raise BadKeyError when the key is invalid.
- """
- self.assertRaises(keys.BadKeyError, keys.Key.fromString, '')
- # no key data with a bad key type
- self.assertRaises(keys.BadKeyError, keys.Key.fromString, '',
- 'bad_type')
- # trying to decrypt a key which doesn't support encryption
- self.assertRaises(keys.BadKeyError, keys.Key.fromString,
- keydata.publicRSA_lsh, passphrase = 'unencrypted')
- # trying to decrypt a key with the wrong passphrase
- self.assertRaises(keys.EncryptedKeyError, keys.Key.fromString,
- keys.Key(self.rsaObj).toString('openssh', 'encrypted'))
- # key with no key data
- self.assertRaises(keys.BadKeyError, keys.Key.fromString,
- '-----BEGIN RSA KEY-----\nwA==\n')
- # key with invalid DEK Info
- self.assertRaises(
- keys.BadKeyError, keys.Key.fromString,
- """-----BEGIN ENCRYPTED RSA KEY-----
-Proc-Type: 4,ENCRYPTED
-DEK-Info: weird type
-
-4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n
-T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H
-g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB
-sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5
-9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV
-gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW
-0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE
-vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS
-hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC+OEKP+/s6HSKuqk
-2bzcl3/TcZXNSM815hnFRpz0anuyAsvwPNRyvxG2/DacJHL1f6luV4B0o6W410yf
-qXQx01DLo7nuyhJqoH3UGCyyXB+/QUs0mbG2PAEn3f5dVs31JMdbt+PrxURXXjKk
-4cexpUcIpqqlfpIRe3RD0sDVbH4OXsGhi2kiTfPZu7mgyFxKopRbn1KwU1qKinfY
-EU9O4PoTak/tPT+5jFNhaP+HrURoi/pU8EAUNSktl7xAkHYwkN/9Cm7DeBghgf3n
-8+tyCGYDsB5utPD0/Xe9yx0Qhc/kMm4xIyQDyA937dk3mUvLC9vulnAP8I+Izim0
-fZ182+D1bWwykoD0997mUHG/AUChWR01V1OLwRyPv2wUtiS8VNG76Y2aqKlgqP1P
-V+IvIEqR4ERvSBVFzXNF8Y6j/sVxo8+aZw+d0L1Ns/R55deErGg3B8i/2EqGd3r+
-0jps9BqFHHWW87n3VyEB3jWCMj8Vi2EJIfa/7pSaViFIQn8LiBLf+zxG5LTOToK5
-xkN42fReDcqi3UNfKNGnv4dsplyTR2hyx65lsj4bRKDGLKOuB1y7iB0AGb0LtcAI
-dcsVlcCeUquDXtqKvRnwfIMg+ZunyjqHBhj3qgRgbXbT6zjaSdNnih569aTg0Vup
-VykzZ7+n/KVcGLmvX0NesdoI7TKbq4TnEIOynuG5Sf+2GpARO5bjcWKSZeN/Ybgk
-gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c
-8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw
-SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7
-CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE
-xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P
------END RSA PRIVATE KEY-----""", passphrase='encrypted')
- # key with invalid encryption type
- self.assertRaises(
- keys.BadKeyError, keys.Key.fromString,
- """-----BEGIN ENCRYPTED RSA KEY-----
-Proc-Type: 4,ENCRYPTED
-DEK-Info: FOO-123-BAR,01234567
-
-4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n
-T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H
-g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB
-sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5
-9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV
-gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW
-0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE
-vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS
-hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC+OEKP+/s6HSKuqk
-2bzcl3/TcZXNSM815hnFRpz0anuyAsvwPNRyvxG2/DacJHL1f6luV4B0o6W410yf
-qXQx01DLo7nuyhJqoH3UGCyyXB+/QUs0mbG2PAEn3f5dVs31JMdbt+PrxURXXjKk
-4cexpUcIpqqlfpIRe3RD0sDVbH4OXsGhi2kiTfPZu7mgyFxKopRbn1KwU1qKinfY
-EU9O4PoTak/tPT+5jFNhaP+HrURoi/pU8EAUNSktl7xAkHYwkN/9Cm7DeBghgf3n
-8+tyCGYDsB5utPD0/Xe9yx0Qhc/kMm4xIyQDyA937dk3mUvLC9vulnAP8I+Izim0
-fZ182+D1bWwykoD0997mUHG/AUChWR01V1OLwRyPv2wUtiS8VNG76Y2aqKlgqP1P
-V+IvIEqR4ERvSBVFzXNF8Y6j/sVxo8+aZw+d0L1Ns/R55deErGg3B8i/2EqGd3r+
-0jps9BqFHHWW87n3VyEB3jWCMj8Vi2EJIfa/7pSaViFIQn8LiBLf+zxG5LTOToK5
-xkN42fReDcqi3UNfKNGnv4dsplyTR2hyx65lsj4bRKDGLKOuB1y7iB0AGb0LtcAI
-dcsVlcCeUquDXtqKvRnwfIMg+ZunyjqHBhj3qgRgbXbT6zjaSdNnih569aTg0Vup
-VykzZ7+n/KVcGLmvX0NesdoI7TKbq4TnEIOynuG5Sf+2GpARO5bjcWKSZeN/Ybgk
-gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c
-8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw
-SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7
-CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE
-xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P
------END RSA PRIVATE KEY-----""", passphrase='encrypted')
- # key with bad IV (AES)
- self.assertRaises(
- keys.BadKeyError, keys.Key.fromString,
- """-----BEGIN ENCRYPTED RSA KEY-----
-Proc-Type: 4,ENCRYPTED
-DEK-Info: AES-128-CBC,01234
-
-4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n
-T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H
-g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB
-sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5
-9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV
-gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW
-0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE
-vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS
-hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC+OEKP+/s6HSKuqk
-2bzcl3/TcZXNSM815hnFRpz0anuyAsvwPNRyvxG2/DacJHL1f6luV4B0o6W410yf
-qXQx01DLo7nuyhJqoH3UGCyyXB+/QUs0mbG2PAEn3f5dVs31JMdbt+PrxURXXjKk
-4cexpUcIpqqlfpIRe3RD0sDVbH4OXsGhi2kiTfPZu7mgyFxKopRbn1KwU1qKinfY
-EU9O4PoTak/tPT+5jFNhaP+HrURoi/pU8EAUNSktl7xAkHYwkN/9Cm7DeBghgf3n
-8+tyCGYDsB5utPD0/Xe9yx0Qhc/kMm4xIyQDyA937dk3mUvLC9vulnAP8I+Izim0
-fZ182+D1bWwykoD0997mUHG/AUChWR01V1OLwRyPv2wUtiS8VNG76Y2aqKlgqP1P
-V+IvIEqR4ERvSBVFzXNF8Y6j/sVxo8+aZw+d0L1Ns/R55deErGg3B8i/2EqGd3r+
-0jps9BqFHHWW87n3VyEB3jWCMj8Vi2EJIfa/7pSaViFIQn8LiBLf+zxG5LTOToK5
-xkN42fReDcqi3UNfKNGnv4dsplyTR2hyx65lsj4bRKDGLKOuB1y7iB0AGb0LtcAI
-dcsVlcCeUquDXtqKvRnwfIMg+ZunyjqHBhj3qgRgbXbT6zjaSdNnih569aTg0Vup
-VykzZ7+n/KVcGLmvX0NesdoI7TKbq4TnEIOynuG5Sf+2GpARO5bjcWKSZeN/Ybgk
-gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c
-8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw
-SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7
-CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE
-xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P
------END RSA PRIVATE KEY-----""", passphrase='encrypted')
- # key with bad IV (DES3)
- self.assertRaises(
- keys.BadKeyError, keys.Key.fromString,
- """-----BEGIN ENCRYPTED RSA KEY-----
-Proc-Type: 4,ENCRYPTED
-DEK-Info: DES-EDE3-CBC,01234
-
-4Ed/a9OgJWHJsne7yOGWeWMzHYKsxuP9w1v0aYcp+puS75wvhHLiUnNwxz0KDi6n
-T3YkKLBsoCWS68ApR2J9yeQ6R+EyS+UQDrO9nwqo3DB5BT3Ggt8S1wE7vjNLQD0H
-g/SJnlqwsECNhh8aAx+Ag0m3ZKOZiRD5mCkcDQsZET7URSmFytDKOjhFn3u6ZFVB
-sXrfpYc6TJtOQlHd/52JB6aAbjt6afSv955Z7enIi+5yEJ5y7oYQTaE5zrFMP7N5
-9LbfJFlKXxEddy/DErRLxEjmC+t4svHesoJKc2jjjyNPiOoGGF3kJXea62vsjdNV
-gMK5Eged3TBVIk2dv8rtJUvyFeCUtjQ1UJZIebScRR47KrbsIpCmU8I4/uHWm5hW
-0mOwvdx1L/mqx/BHqVU9Dw2COhOdLbFxlFI92chkovkmNk4P48ziyVnpm7ME22sE
-vfCMsyirdqB1mrL4CSM7FXONv+CgfBfeYVkYW8RfJac9U1L/O+JNn7yee414O/rS
-hRYw4UdWnH6Gg6niklVKWNY0ZwUZC8zgm2iqy8YCYuneS37jC+OEKP+/s6HSKuqk
-2bzcl3/TcZXNSM815hnFRpz0anuyAsvwPNRyvxG2/DacJHL1f6luV4B0o6W410yf
-qXQx01DLo7nuyhJqoH3UGCyyXB+/QUs0mbG2PAEn3f5dVs31JMdbt+PrxURXXjKk
-4cexpUcIpqqlfpIRe3RD0sDVbH4OXsGhi2kiTfPZu7mgyFxKopRbn1KwU1qKinfY
-EU9O4PoTak/tPT+5jFNhaP+HrURoi/pU8EAUNSktl7xAkHYwkN/9Cm7DeBghgf3n
-8+tyCGYDsB5utPD0/Xe9yx0Qhc/kMm4xIyQDyA937dk3mUvLC9vulnAP8I+Izim0
-fZ182+D1bWwykoD0997mUHG/AUChWR01V1OLwRyPv2wUtiS8VNG76Y2aqKlgqP1P
-V+IvIEqR4ERvSBVFzXNF8Y6j/sVxo8+aZw+d0L1Ns/R55deErGg3B8i/2EqGd3r+
-0jps9BqFHHWW87n3VyEB3jWCMj8Vi2EJIfa/7pSaViFIQn8LiBLf+zxG5LTOToK5
-xkN42fReDcqi3UNfKNGnv4dsplyTR2hyx65lsj4bRKDGLKOuB1y7iB0AGb0LtcAI
-dcsVlcCeUquDXtqKvRnwfIMg+ZunyjqHBhj3qgRgbXbT6zjaSdNnih569aTg0Vup
-VykzZ7+n/KVcGLmvX0NesdoI7TKbq4TnEIOynuG5Sf+2GpARO5bjcWKSZeN/Ybgk
-gccf8Cqf6XWqiwlWd0B7BR3SymeHIaSymC45wmbgdstrbk7Ppa2Tp9AZku8M2Y7c
-8mY9b+onK075/ypiwBm4L4GRNTFLnoNQJXx0OSl4FNRWsn6ztbD+jZhu8Seu10Jw
-SEJVJ+gmTKdRLYORJKyqhDet6g7kAxs4EoJ25WsOnX5nNr00rit+NkMPA7xbJT+7
-CfI51GQLw7pUPeO2WNt6yZO/YkzZrqvTj5FEwybkUyBv7L0gkqu9wjfDdUw0fVHE
-xEm4DxjEoaIp8dW/JOzXQ2EF+WaSOgdYsw3Ac+rnnjnNptCdOEDGP6QBkt+oXj4P
------END RSA PRIVATE KEY-----""", passphrase='encrypted')
-
- def test_fromFile(self):
- """
- Test that fromFile works correctly.
- """
- self.assertEqual(keys.Key.fromFile(self.keyFile),
- keys.Key.fromString(keydata.privateRSA_lsh))
- self.assertRaises(keys.BadKeyError, keys.Key.fromFile,
- self.keyFile, 'bad_type')
- self.assertRaises(keys.BadKeyError, keys.Key.fromFile,
- self.keyFile, passphrase='unencrypted')
-
- def test_init(self):
- """
- Test that the PublicKey object is initialized correctly.
- """
- obj = Crypto.PublicKey.RSA.construct((1L, 2L))
- key = keys.Key(obj)
- self.assertEqual(key.keyObject, obj)
-
- def test_equal(self):
- """
- Test that Key objects are compared correctly.
- """
- rsa1 = keys.Key(self.rsaObj)
- rsa2 = keys.Key(self.rsaObj)
- rsa3 = keys.Key(Crypto.PublicKey.RSA.construct((1L, 2L)))
- dsa = keys.Key(self.dsaObj)
- self.assertTrue(rsa1 == rsa2)
- self.assertFalse(rsa1 == rsa3)
- self.assertFalse(rsa1 == dsa)
- self.assertFalse(rsa1 == object)
- self.assertFalse(rsa1 == None)
-
- def test_notEqual(self):
- """
- Test that Key objects are not-compared correctly.
- """
- rsa1 = keys.Key(self.rsaObj)
- rsa2 = keys.Key(self.rsaObj)
- rsa3 = keys.Key(Crypto.PublicKey.RSA.construct((1L, 2L)))
- dsa = keys.Key(self.dsaObj)
- self.assertFalse(rsa1 != rsa2)
- self.assertTrue(rsa1 != rsa3)
- self.assertTrue(rsa1 != dsa)
- self.assertTrue(rsa1 != object)
- self.assertTrue(rsa1 != None)
-
- def test_type(self):
- """
- Test that the type method returns the correct type for an object.
- """
- self.assertEqual(keys.Key(self.rsaObj).type(), 'RSA')
- self.assertEqual(keys.Key(self.rsaObj).sshType(), 'ssh-rsa')
- self.assertEqual(keys.Key(self.dsaObj).type(), 'DSA')
- self.assertEqual(keys.Key(self.dsaObj).sshType(), 'ssh-dss')
- self.assertRaises(RuntimeError, keys.Key(None).type)
- self.assertRaises(RuntimeError, keys.Key(None).sshType)
- self.assertRaises(RuntimeError, keys.Key(self).type)
- self.assertRaises(RuntimeError, keys.Key(self).sshType)
-
- def test_fromBlob(self):
- """
- Test that a public key is correctly generated from a public key blob.
- """
- rsaBlob = common.NS('ssh-rsa') + common.MP(2) + common.MP(3)
- rsaKey = keys.Key.fromString(rsaBlob)
- dsaBlob = (common.NS('ssh-dss') + common.MP(2) + common.MP(3) +
- common.MP(4) + common.MP(5))
- dsaKey = keys.Key.fromString(dsaBlob)
- badBlob = common.NS('ssh-bad')
- self.assertTrue(rsaKey.isPublic())
- self.assertEqual(rsaKey.data(), {'e':2L, 'n':3L})
- self.assertTrue(dsaKey.isPublic())
- self.assertEqual(dsaKey.data(), {'p':2L, 'q':3L, 'g':4L, 'y':5L})
- self.assertRaises(keys.BadKeyError,
- keys.Key.fromString, badBlob)
-
-
- def test_fromPrivateBlob(self):
- """
- Test that a private key is correctly generated from a private key blob.
- """
- rsaBlob = (common.NS('ssh-rsa') + common.MP(2) + common.MP(3) +
- common.MP(4) + common.MP(5) + common.MP(6) + common.MP(7))
- rsaKey = keys.Key._fromString_PRIVATE_BLOB(rsaBlob)
- dsaBlob = (common.NS('ssh-dss') + common.MP(2) + common.MP(3) +
- common.MP(4) + common.MP(5) + common.MP(6))
- dsaKey = keys.Key._fromString_PRIVATE_BLOB(dsaBlob)
- badBlob = common.NS('ssh-bad')
- self.assertFalse(rsaKey.isPublic())
- self.assertEqual(
- rsaKey.data(), {'n':2L, 'e':3L, 'd':4L, 'u':5L, 'p':6L, 'q':7L})
- self.assertFalse(dsaKey.isPublic())
- self.assertEqual(dsaKey.data(), {'p':2L, 'q':3L, 'g':4L, 'y':5L, 'x':6L})
- self.assertRaises(
- keys.BadKeyError, keys.Key._fromString_PRIVATE_BLOB, badBlob)
-
-
- def test_blob(self):
- """
- Test that the Key object generates blobs correctly.
- """
- self.assertEqual(keys.Key(self.rsaObj).blob(),
- '\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x01\x02'
- '\x00\x00\x00\x01\x01')
- self.assertEqual(keys.Key(self.dsaObj).blob(),
- '\x00\x00\x00\x07ssh-dss\x00\x00\x00\x01\x03'
- '\x00\x00\x00\x01\x04\x00\x00\x00\x01\x02'
- '\x00\x00\x00\x01\x01')
-
- badKey = keys.Key(None)
- self.assertRaises(RuntimeError, badKey.blob)
-
-
- def test_privateBlob(self):
- """
- L{Key.privateBlob} returns the SSH protocol-level format of the private
- key and raises L{RuntimeError} if the underlying key object is invalid.
- """
- self.assertEqual(keys.Key(self.rsaObj).privateBlob(),
- '\x00\x00\x00\x07ssh-rsa\x00\x00\x00\x01\x01'
- '\x00\x00\x00\x01\x02\x00\x00\x00\x01\x03\x00'
- '\x00\x00\x01\x04\x00\x00\x00\x01\x04\x00\x00'
- '\x00\x01\x05')
- self.assertEqual(keys.Key(self.dsaObj).privateBlob(),
- '\x00\x00\x00\x07ssh-dss\x00\x00\x00\x01\x03'
- '\x00\x00\x00\x01\x04\x00\x00\x00\x01\x02\x00'
- '\x00\x00\x01\x01\x00\x00\x00\x01\x05')
-
- badKey = keys.Key(None)
- self.assertRaises(RuntimeError, badKey.privateBlob)
-
-
- def test_toOpenSSH(self):
- """
- Test that the Key object generates OpenSSH keys correctly.
- """
- key = keys.Key.fromString(keydata.privateRSA_lsh)
- self.assertEqual(key.toString('openssh'), keydata.privateRSA_openssh)
- self.assertEqual(key.toString('openssh', 'encrypted'),
- keydata.privateRSA_openssh_encrypted)
- self.assertEqual(key.public().toString('openssh'),
- keydata.publicRSA_openssh[:-8]) # no comment
- self.assertEqual(key.public().toString('openssh', 'comment'),
- keydata.publicRSA_openssh)
- key = keys.Key.fromString(keydata.privateDSA_lsh)
- self.assertEqual(key.toString('openssh'), keydata.privateDSA_openssh)
- self.assertEqual(key.public().toString('openssh', 'comment'),
- keydata.publicDSA_openssh)
- self.assertEqual(key.public().toString('openssh'),
- keydata.publicDSA_openssh[:-8]) # no comment
-
- def test_toLSH(self):
- """
- Test that the Key object generates LSH keys correctly.
- """
- key = keys.Key.fromString(keydata.privateRSA_openssh)
- self.assertEqual(key.toString('lsh'), keydata.privateRSA_lsh)
- self.assertEqual(key.public().toString('lsh'),
- keydata.publicRSA_lsh)
- key = keys.Key.fromString(keydata.privateDSA_openssh)
- self.assertEqual(key.toString('lsh'), keydata.privateDSA_lsh)
- self.assertEqual(key.public().toString('lsh'),
- keydata.publicDSA_lsh)
-
- def test_toAgentv3(self):
- """
- Test that the Key object generates Agent v3 keys correctly.
- """
- key = keys.Key.fromString(keydata.privateRSA_openssh)
- self.assertEqual(key.toString('agentv3'), keydata.privateRSA_agentv3)
- key = keys.Key.fromString(keydata.privateDSA_openssh)
- self.assertEqual(key.toString('agentv3'), keydata.privateDSA_agentv3)
-
- def test_toStringErrors(self):
- """
- Test that toString raises errors appropriately.
- """
- self.assertRaises(keys.BadKeyError, keys.Key(self.rsaObj).toString,
- 'bad_type')
-
- def test_sign(self):
- """
- Test that the Key object generates correct signatures.
- """
- key = keys.Key.fromString(keydata.privateRSA_openssh)
- self.assertEqual(key.sign(''), self.rsaSignature)
- key = keys.Key.fromString(keydata.privateDSA_openssh)
- self.assertEqual(key.sign(''), self.dsaSignature)
-
-
- def test_verify(self):
- """
- Test that the Key object correctly verifies signatures.
- """
- key = keys.Key.fromString(keydata.publicRSA_openssh)
- self.assertTrue(key.verify(self.rsaSignature, ''))
- self.assertFalse(key.verify(self.rsaSignature, 'a'))
- self.assertFalse(key.verify(self.dsaSignature, ''))
- key = keys.Key.fromString(keydata.publicDSA_openssh)
- self.assertTrue(key.verify(self.dsaSignature, ''))
- self.assertFalse(key.verify(self.dsaSignature, 'a'))
- self.assertFalse(key.verify(self.rsaSignature, ''))
-
-
- def test_verifyDSANoPrefix(self):
- """
- Some commercial SSH servers send DSA keys as 2 20-byte numbers;
- they are still verified as valid keys.
- """
- key = keys.Key.fromString(keydata.publicDSA_openssh)
- self.assertTrue(key.verify(self.dsaSignature[-40:], ''))
-
-
- def test_repr(self):
- """
- Test the pretty representation of Key.
- """
- self.assertEqual(repr(keys.Key(self.rsaObj)),
-"""""")
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_knownhosts.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_knownhosts.py
deleted file mode 100644
index f584cdf..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_knownhosts.py
+++ /dev/null
@@ -1,1262 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.client.knownhosts}.
-"""
-
-import os
-from binascii import Error as BinasciiError, b2a_base64, a2b_base64
-
-try:
- import Crypto
- import pyasn1
-except ImportError:
- skip = "PyCrypto and PyASN1 required for twisted.conch.knownhosts."
-else:
- from twisted.conch.ssh.keys import Key, BadKeyError
- from twisted.conch.client.knownhosts import \
- PlainEntry, HashedEntry, KnownHostsFile, UnparsedEntry, ConsoleUI
- from twisted.conch.client import default
-
-from zope.interface.verify import verifyObject
-
-from twisted.python.filepath import FilePath
-from twisted.trial.unittest import TestCase
-from twisted.internet.defer import Deferred
-from twisted.conch.interfaces import IKnownHostEntry
-from twisted.conch.error import HostKeyChanged, UserRejectedKey, InvalidEntry
-from twisted.test.testutils import ComparisonTestsMixin
-
-
-sampleEncodedKey = (
- 'AAAAB3NzaC1yc2EAAAABIwAAAQEAsV0VMRbGmzhqxxayLRHmvnFvtyNqgbNKV46dU1bVFB+3y'
- 'tNvue4Riqv/SVkPRNwMb7eWH29SviXaBxUhYyzKkDoNUq3rTNnH1Vnif6d6X4JCrUb5d3W+Dm'
- 'YClyJrZ5HgD/hUpdSkTRqdbQ2TrvSAxRacj+vHHT4F4dm1bJSewm3B2D8HVOoi/CbVh3dsIiC'
- 'dp8VltdZx4qYVfYe2LwVINCbAa3d3tj9ma7RVfw3OH2Mfb+toLd1N5tBQFb7oqTt2nC6I/6Bd'
- '4JwPUld+IEitw/suElq/AIJVQXXujeyiZlea90HE65U2mF1ytr17HTAIT2ySokJWyuBANGACk'
- '6iIaw==')
-
-otherSampleEncodedKey = (
- 'AAAAB3NzaC1yc2EAAAABIwAAAIEAwaeCZd3UCuPXhX39+/p9qO028jTF76DMVd9mPvYVDVXuf'
- 'WckKZauF7+0b7qm+ChT7kan6BzRVo4++gCVNfAlMzLysSt3ylmOR48tFpAfygg9UCX3DjHz0E'
- 'lOOUKh3iifc9aUShD0OPaK3pR5JJ8jfiBfzSYWt/hDi/iZ4igsSs8=')
-
-thirdSampleEncodedKey = (
- 'AAAAB3NzaC1yc2EAAAABIwAAAQEAl/TQakPkePlnwCBRPitIVUTg6Z8VzN1en+DGkyo/evkmLw'
- '7o4NWR5qbysk9A9jXW332nxnEuAnbcCam9SHe1su1liVfyIK0+3bdn0YRB0sXIbNEtMs2LtCho'
- '/aV3cXPS+Cf1yut3wvIpaRnAzXxuKPCTXQ7/y0IXa8TwkRBH58OJa3RqfQ/NsSp5SAfdsrHyH2'
- 'aitiVKm2jfbTKzSEqOQG/zq4J9GXTkq61gZugory/Tvl5/yPgSnOR6C9jVOMHf27ZPoRtyj9SY'
- '343Hd2QHiIE0KPZJEgCynKeWoKz8v6eTSK8n4rBnaqWdp8MnGZK1WGy05MguXbyCDuTC8AmJXQ'
- '==')
-
-sampleKey = a2b_base64(sampleEncodedKey)
-otherSampleKey = a2b_base64(otherSampleEncodedKey)
-thirdSampleKey = a2b_base64(thirdSampleEncodedKey)
-
-samplePlaintextLine = (
- "www.twistedmatrix.com ssh-rsa " + sampleEncodedKey + "\n")
-
-otherSamplePlaintextLine = (
- "divmod.com ssh-rsa " + otherSampleEncodedKey + "\n")
-
-sampleHostIPLine = (
- "www.twistedmatrix.com,198.49.126.131 ssh-rsa " + sampleEncodedKey + "\n")
-
-sampleHashedLine = (
- "|1|gJbSEPBG9ZSBoZpHNtZBD1bHKBA=|bQv+0Xa0dByrwkA1EB0E7Xop/Fo= ssh-rsa " +
- sampleEncodedKey + "\n")
-
-
-class EntryTestsMixin:
- """
- Tests for implementations of L{IKnownHostEntry}. Subclasses must set the
- 'entry' attribute to a provider of that interface, the implementation of
- that interface under test.
-
- @ivar entry: a provider of L{IKnownHostEntry} with a hostname of
- www.twistedmatrix.com and an RSA key of sampleKey.
- """
-
- def test_providesInterface(self):
- """
- The given entry should provide IKnownHostEntry.
- """
- verifyObject(IKnownHostEntry, self.entry)
-
-
- def test_fromString(self):
- """
- Constructing a plain text entry from an unhashed known_hosts entry will
- result in an L{IKnownHostEntry} provider with 'keyString', 'hostname',
- and 'keyType' attributes. While outside the interface in question,
- these attributes are held in common by L{PlainEntry} and L{HashedEntry}
- implementations; other implementations should override this method in
- subclasses.
- """
- entry = self.entry
- self.assertEqual(entry.publicKey, Key.fromString(sampleKey))
- self.assertEqual(entry.keyType, "ssh-rsa")
-
-
- def test_matchesKey(self):
- """
- L{IKnownHostEntry.matchesKey} checks to see if an entry matches a given
- SSH key.
- """
- twistedmatrixDotCom = Key.fromString(sampleKey)
- divmodDotCom = Key.fromString(otherSampleKey)
- self.assertEqual(
- True,
- self.entry.matchesKey(twistedmatrixDotCom))
- self.assertEqual(
- False,
- self.entry.matchesKey(divmodDotCom))
-
-
- def test_matchesHost(self):
- """
- L{IKnownHostEntry.matchesHost} checks to see if an entry matches a
- given hostname.
- """
- self.assertEqual(True, self.entry.matchesHost(
- "www.twistedmatrix.com"))
- self.assertEqual(False, self.entry.matchesHost(
- "www.divmod.com"))
-
-
-
-class PlainEntryTests(EntryTestsMixin, TestCase):
- """
- Test cases for L{PlainEntry}.
- """
- plaintextLine = samplePlaintextLine
- hostIPLine = sampleHostIPLine
-
- def setUp(self):
- """
- Set 'entry' to a sample plain-text entry with sampleKey as its key.
- """
- self.entry = PlainEntry.fromString(self.plaintextLine)
-
-
- def test_matchesHostIP(self):
- """
- A "hostname,ip" formatted line will match both the host and the IP.
- """
- self.entry = PlainEntry.fromString(self.hostIPLine)
- self.assertEqual(True, self.entry.matchesHost("198.49.126.131"))
- self.test_matchesHost()
-
-
- def test_toString(self):
- """
- L{PlainEntry.toString} generates the serialized OpenSSL format string
- for the entry, sans newline.
- """
- self.assertEqual(self.entry.toString(), self.plaintextLine.rstrip("\n"))
- multiHostEntry = PlainEntry.fromString(self.hostIPLine)
- self.assertEqual(multiHostEntry.toString(),
- self.hostIPLine.rstrip("\n"))
-
-
-
-class PlainTextWithCommentTests(PlainEntryTests):
- """
- Test cases for L{PlainEntry} when parsed from a line with a comment.
- """
-
- plaintextLine = samplePlaintextLine[:-1] + " plain text comment.\n"
- hostIPLine = sampleHostIPLine[:-1] + " text following host/IP line\n"
-
-
-
-class HashedEntryTests(EntryTestsMixin, ComparisonTestsMixin, TestCase):
- """
- Tests for L{HashedEntry}.
-
- This suite doesn't include any tests for host/IP pairs because hashed
- entries store IP addresses the same way as hostnames and does not support
- comma-separated lists. (If you hash the IP and host together you can't
- tell if you've got the key already for one or the other.)
- """
- hashedLine = sampleHashedLine
-
- def setUp(self):
- """
- Set 'entry' to a sample hashed entry for twistedmatrix.com with
- sampleKey as its key.
- """
- self.entry = HashedEntry.fromString(self.hashedLine)
-
-
- def test_toString(self):
- """
- L{HashedEntry.toString} generates the serialized OpenSSL format string
- for the entry, sans the newline.
- """
- self.assertEqual(self.entry.toString(), self.hashedLine.rstrip("\n"))
-
-
- def test_equality(self):
- """
- Two L{HashedEntry} instances compare equal if and only if they represent
- the same host and key in exactly the same way: the host salt, host hash,
- public key type, public key, and comment fields must all be equal.
- """
- hostSalt = "gJbSEPBG9ZSBoZpHNtZBD1bHKBA"
- hostHash = "bQv+0Xa0dByrwkA1EB0E7Xop/Fo"
- publicKey = Key.fromString(sampleKey)
- comment = "hello, world"
-
- entry = HashedEntry(
- hostSalt, hostHash, publicKey.type(), publicKey, comment)
- duplicate = HashedEntry(
- hostSalt, hostHash, publicKey.type(), publicKey, comment)
-
- # Vary the host salt
- self.assertNormalEqualityImplementation(
- entry, duplicate,
- HashedEntry(
- hostSalt[::-1], hostHash, publicKey.type(), publicKey,
- comment))
-
- # Vary the host hash
- self.assertNormalEqualityImplementation(
- entry, duplicate,
- HashedEntry(
- hostSalt, hostHash[::-1], publicKey.type(), publicKey,
- comment))
-
- # Vary the key type
- self.assertNormalEqualityImplementation(
- entry, duplicate,
- HashedEntry(
- hostSalt, hostHash, publicKey.type()[::-1], publicKey,
- comment))
-
- # Vary the key
- self.assertNormalEqualityImplementation(
- entry, duplicate,
- HashedEntry(
- hostSalt, hostHash, publicKey.type(),
- Key.fromString(otherSampleKey), comment))
-
- # Vary the comment
- self.assertNormalEqualityImplementation(
- entry, duplicate,
- HashedEntry(
- hostSalt, hostHash, publicKey.type(), publicKey,
- comment[::-1]))
-
-
-
-class HashedEntryWithCommentTests(HashedEntryTests):
- """
- Test cases for L{PlainEntry} when parsed from a line with a comment.
- """
-
- hashedLine = sampleHashedLine[:-1] + " plain text comment.\n"
-
-
-
-class UnparsedEntryTests(TestCase, EntryTestsMixin):
- """
- Tests for L{UnparsedEntry}
- """
- def setUp(self):
- """
- Set up the 'entry' to be an unparsed entry for some random text.
- """
- self.entry = UnparsedEntry(" This is a bogus entry. \n")
-
-
- def test_fromString(self):
- """
- Creating an L{UnparsedEntry} should simply record the string it was
- passed.
- """
- self.assertEqual(" This is a bogus entry. \n",
- self.entry._string)
-
-
- def test_matchesHost(self):
- """
- An unparsed entry can't match any hosts.
- """
- self.assertEqual(False, self.entry.matchesHost("www.twistedmatrix.com"))
-
-
- def test_matchesKey(self):
- """
- An unparsed entry can't match any keys.
- """
- self.assertEqual(False, self.entry.matchesKey(Key.fromString(sampleKey)))
-
-
- def test_toString(self):
- """
- L{UnparsedEntry.toString} returns its input string, sans trailing
- newline.
- """
- self.assertEqual(" This is a bogus entry. ", self.entry.toString())
-
-
-
-class ParseErrorTests(TestCase):
- """
- L{HashedEntry.fromString} and L{PlainEntry.fromString} can raise a variety
- of errors depending on misformattings of certain strings. These tests make
- sure those errors are caught. Since many of the ways that this can go
- wrong are in the lower-level APIs being invoked by the parsing logic,
- several of these are integration tests with the C{base64} and
- L{twisted.conch.ssh.keys} modules.
- """
-
- def invalidEntryTest(self, cls):
- """
- If there are fewer than three elements, C{fromString} should raise
- L{InvalidEntry}.
- """
- self.assertRaises(InvalidEntry, cls.fromString, "invalid")
-
-
- def notBase64Test(self, cls):
- """
- If the key is not base64, C{fromString} should raise L{BinasciiError}.
- """
- self.assertRaises(BinasciiError, cls.fromString, "x x x")
-
-
- def badKeyTest(self, cls, prefix):
- """
- If the key portion of the entry is valid base64, but is not actually an
- SSH key, C{fromString} should raise L{BadKeyError}.
- """
- self.assertRaises(BadKeyError, cls.fromString, ' '.join(
- [prefix, "ssh-rsa", b2a_base64(
- "Hey, this isn't an SSH key!").strip()]))
-
-
- def test_invalidPlainEntry(self):
- """
- If there are fewer than three whitespace-separated elements in an
- entry, L{PlainEntry.fromString} should raise L{InvalidEntry}.
- """
- self.invalidEntryTest(PlainEntry)
-
-
- def test_invalidHashedEntry(self):
- """
- If there are fewer than three whitespace-separated elements in an
- entry, or the hostname salt/hash portion has more than two elements,
- L{HashedEntry.fromString} should raise L{InvalidEntry}.
- """
- self.invalidEntryTest(HashedEntry)
- a, b, c = sampleHashedLine.split()
- self.assertRaises(InvalidEntry, HashedEntry.fromString, ' '.join(
- [a + "||", b, c]))
-
-
- def test_plainNotBase64(self):
- """
- If the key portion of a plain entry is not decodable as base64,
- C{fromString} should raise L{BinasciiError}.
- """
- self.notBase64Test(PlainEntry)
-
-
- def test_hashedNotBase64(self):
- """
- If the key, host salt, or host hash portion of a hashed entry is not
- encoded, it will raise L{BinasciiError}.
- """
- self.notBase64Test(HashedEntry)
- a, b, c = sampleHashedLine.split()
- # Salt not valid base64.
- self.assertRaises(
- BinasciiError, HashedEntry.fromString,
- ' '.join(["|1|x|" + b2a_base64("stuff").strip(), b, c]))
- # Host hash not valid base64.
- self.assertRaises(
- BinasciiError, HashedEntry.fromString,
- ' '.join([HashedEntry.MAGIC + b2a_base64("stuff").strip() + "|x",
- b, c]))
- # Neither salt nor hash valid base64.
- self.assertRaises(
- BinasciiError, HashedEntry.fromString,
- ' '.join(["|1|x|x", b, c]))
-
-
- def test_hashedBadKey(self):
- """
- If the key portion of the entry is valid base64, but is not actually an
- SSH key, C{HashedEntry.fromString} should raise L{BadKeyError}.
- """
- a, b, c = sampleHashedLine.split()
- self.badKeyTest(HashedEntry, a)
-
-
- def test_plainBadKey(self):
- """
- If the key portion of the entry is valid base64, but is not actually an
- SSH key, C{PlainEntry.fromString} should raise L{BadKeyError}.
- """
- self.badKeyTest(PlainEntry, "hostname")
-
-
-
-class KnownHostsDatabaseTests(TestCase):
- """
- Tests for L{KnownHostsFile}.
- """
-
- def pathWithContent(self, content):
- """
- Return a FilePath with the given initial content.
- """
- fp = FilePath(self.mktemp())
- fp.setContent(content)
- return fp
-
-
- def loadSampleHostsFile(self, content=(
- sampleHashedLine + otherSamplePlaintextLine +
- "\n# That was a blank line.\n"
- "This is just unparseable.\n"
- "|1|This also unparseable.\n")):
- """
- Return a sample hosts file, with keys for www.twistedmatrix.com and
- divmod.com present.
- """
- return KnownHostsFile.fromPath(self.pathWithContent(content))
-
-
- def test_readOnlySavePath(self):
- """
- L{KnownHostsFile.savePath} is read-only; if an assignment is made to
- it, L{AttributeError} is raised and the value is unchanged.
- """
- path = FilePath(self.mktemp())
- new = FilePath(self.mktemp())
- hostsFile = KnownHostsFile(path)
- self.assertRaises(AttributeError, setattr, hostsFile, "savePath", new)
- self.assertEqual(path, hostsFile.savePath)
-
-
- def test_defaultInitializerIgnoresExisting(self):
- """
- The default initializer for L{KnownHostsFile} disregards any existing
- contents in the save path.
- """
- hostsFile = KnownHostsFile(self.pathWithContent(sampleHashedLine))
- self.assertEqual([], list(hostsFile.iterentries()))
-
-
- def test_defaultInitializerClobbersExisting(self):
- """
- After using the default initializer for L{KnownHostsFile}, the first use
- of L{KnownHostsFile.save} overwrites any existing contents in the save
- path.
- """
- path = self.pathWithContent(sampleHashedLine)
- hostsFile = KnownHostsFile(path)
- entry = hostsFile.addHostKey(
- "www.example.com", Key.fromString(otherSampleKey))
- hostsFile.save()
- # Check KnownHostsFile to see what it thinks the state is
- self.assertEqual([entry], list(hostsFile.iterentries()))
- # And also directly check the underlying file itself
- self.assertEqual(entry.toString() + "\n", path.getContent())
-
-
- def test_saveResetsClobberState(self):
- """
- After L{KnownHostsFile.save} is used once with an instance initialized
- by the default initializer, contents of the save path are respected and
- preserved.
- """
- hostsFile = KnownHostsFile(self.pathWithContent(sampleHashedLine))
- preSave = hostsFile.addHostKey(
- "www.example.com", Key.fromString(otherSampleKey))
- hostsFile.save()
- postSave = hostsFile.addHostKey(
- "another.example.com", Key.fromString(thirdSampleKey))
- hostsFile.save()
-
- self.assertEqual([preSave, postSave], list(hostsFile.iterentries()))
-
-
- def test_loadFromPath(self):
- """
- Loading a L{KnownHostsFile} from a path with six entries in it will
- result in a L{KnownHostsFile} object with six L{IKnownHostEntry}
- providers in it.
- """
- hostsFile = self.loadSampleHostsFile()
- self.assertEqual(6, len(list(hostsFile.iterentries())))
-
-
- def test_iterentriesUnsaved(self):
- """
- If the save path for a L{KnownHostsFile} does not exist,
- L{KnownHostsFile.iterentries} still returns added but unsaved entries.
- """
- hostsFile = KnownHostsFile(FilePath(self.mktemp()))
- hostsFile.addHostKey("www.example.com", Key.fromString(sampleKey))
- self.assertEqual(1, len(list(hostsFile.iterentries())))
-
-
- def test_verifyHashedEntry(self):
- """
- Loading a L{KnownHostsFile} from a path containing a single valid
- L{HashedEntry} entry will result in a L{KnownHostsFile} object
- with one L{IKnownHostEntry} provider.
- """
- hostsFile = self.loadSampleHostsFile((sampleHashedLine))
- entries = list(hostsFile.iterentries())
- self.assertIsInstance(entries[0], HashedEntry)
- self.assertEqual(True, entries[0].matchesHost("www.twistedmatrix.com"))
- self.assertEqual(1, len(entries))
-
-
- def test_verifyPlainEntry(self):
- """
- Loading a L{KnownHostsFile} from a path containing a single valid
- L{PlainEntry} entry will result in a L{KnownHostsFile} object
- with one L{IKnownHostEntry} provider.
- """
- hostsFile = self.loadSampleHostsFile((otherSamplePlaintextLine))
- entries = list(hostsFile.iterentries())
- self.assertIsInstance(entries[0], PlainEntry)
- self.assertEqual(True, entries[0].matchesHost("divmod.com"))
- self.assertEqual(1, len(entries))
-
-
- def test_verifyUnparsedEntry(self):
- """
- Loading a L{KnownHostsFile} from a path that only contains '\n' will
- result in a L{KnownHostsFile} object containing a L{UnparsedEntry}
- object.
- """
- hostsFile = self.loadSampleHostsFile(("\n"))
- entries = list(hostsFile.iterentries())
- self.assertIsInstance(entries[0], UnparsedEntry)
- self.assertEqual(entries[0].toString(), "")
- self.assertEqual(1, len(entries))
-
-
- def test_verifyUnparsedComment(self):
- """
- Loading a L{KnownHostsFile} from a path that contains a comment will
- result in a L{KnownHostsFile} object containing a L{UnparsedEntry}
- object.
- """
- hostsFile = self.loadSampleHostsFile(("# That was a blank line.\n"))
- entries = list(hostsFile.iterentries())
- self.assertIsInstance(entries[0], UnparsedEntry)
- self.assertEqual(entries[0].toString(), "# That was a blank line.")
-
-
- def test_verifyUnparsableLine(self):
- """
- Loading a L{KnownHostsFile} from a path that contains an unparseable
- line will be represented as an L{UnparsedEntry} instance.
- """
- hostsFile = self.loadSampleHostsFile(("This is just unparseable.\n"))
- entries = list(hostsFile.iterentries())
- self.assertIsInstance(entries[0], UnparsedEntry)
- self.assertEqual(entries[0].toString(), "This is just unparseable.")
- self.assertEqual(1, len(entries))
-
-
- def test_verifyUnparsableEncryptionMarker(self):
- """
- Loading a L{KnownHostsFile} from a path containing an unparseable line
- that starts with an encryption marker will be represented as an
- L{UnparsedEntry} instance.
- """
- hostsFile = self.loadSampleHostsFile(("|1|This is unparseable.\n"))
- entries = list(hostsFile.iterentries())
- self.assertIsInstance(entries[0], UnparsedEntry)
- self.assertEqual(entries[0].toString(), "|1|This is unparseable.")
- self.assertEqual(1, len(entries))
-
-
- def test_loadNonExistent(self):
- """
- Loading a L{KnownHostsFile} from a path that does not exist should
- result in an empty L{KnownHostsFile} that will save back to that path.
- """
- pn = self.mktemp()
- knownHostsFile = KnownHostsFile.fromPath(FilePath(pn))
- entries = list(knownHostsFile.iterentries())
- self.assertEqual([], entries)
- self.assertEqual(False, FilePath(pn).exists())
- knownHostsFile.save()
- self.assertEqual(True, FilePath(pn).exists())
-
-
- def test_loadNonExistentParent(self):
- """
- Loading a L{KnownHostsFile} from a path whose parent directory does not
- exist should result in an empty L{KnownHostsFile} that will save back
- to that path, creating its parent directory(ies) in the process.
- """
- thePath = FilePath(self.mktemp())
- knownHostsPath = thePath.child("foo").child("known_hosts")
- knownHostsFile = KnownHostsFile.fromPath(knownHostsPath)
- knownHostsFile.save()
- knownHostsPath.restat(False)
- self.assertEqual(True, knownHostsPath.exists())
-
-
- def test_savingAddsEntry(self):
- """
- L{KnownHostsFile.save} will write out a new file with any entries
- that have been added.
- """
- path = self.pathWithContent(sampleHashedLine +
- otherSamplePlaintextLine)
- knownHostsFile = KnownHostsFile.fromPath(path)
- newEntry = knownHostsFile.addHostKey("some.example.com",
- Key.fromString(thirdSampleKey))
- expectedContent = (
- sampleHashedLine +
- otherSamplePlaintextLine + HashedEntry.MAGIC +
- b2a_base64(newEntry._hostSalt).strip() + "|" +
- b2a_base64(newEntry._hostHash).strip() + " ssh-rsa " +
- thirdSampleEncodedKey + "\n")
-
- # Sanity check, let's make sure the base64 API being used for the test
- # isn't inserting spurious newlines.
- self.assertEqual(3, expectedContent.count("\n"))
- knownHostsFile.save()
- self.assertEqual(expectedContent, path.getContent())
-
-
- def test_savingAvoidsDuplication(self):
- """
- L{KnownHostsFile.save} only writes new entries to the save path, not
- entries which were added and already written by a previous call to
- C{save}.
- """
- path = FilePath(self.mktemp())
- knownHosts = KnownHostsFile(path)
- entry = knownHosts.addHostKey(
- "some.example.com", Key.fromString(sampleKey))
- knownHosts.save()
- knownHosts.save()
-
- knownHosts = KnownHostsFile.fromPath(path)
- self.assertEqual([entry], list(knownHosts.iterentries()))
-
-
- def test_savingsPreservesExisting(self):
- """
- L{KnownHostsFile.save} will not overwrite existing entries in its save
- path, even if they were only added after the L{KnownHostsFile} instance
- was initialized.
- """
- # Start off with one host/key pair in the file
- path = self.pathWithContent(sampleHashedLine)
- knownHosts = KnownHostsFile.fromPath(path)
-
- # After initializing the KnownHostsFile instance, add a second host/key
- # pair to the file directly - without the instance's help or knowledge.
- with path.open("a") as hostsFileObj:
- hostsFileObj.write(otherSamplePlaintextLine)
-
- # Add a third host/key pair using the KnownHostsFile instance
- key = Key.fromString(thirdSampleKey)
- knownHosts.addHostKey("brandnew.example.com", key)
- knownHosts.save()
-
- # Check that all three host/key pairs are present.
- knownHosts = KnownHostsFile.fromPath(path)
- self.assertEqual([True, True, True], [
- knownHosts.hasHostKey(
- "www.twistedmatrix.com", Key.fromString(sampleKey)),
- knownHosts.hasHostKey(
- "divmod.com", Key.fromString(otherSampleKey)),
- knownHosts.hasHostKey("brandnew.example.com", key)])
-
-
- def test_hasPresentKey(self):
- """
- L{KnownHostsFile.hasHostKey} returns C{True} when a key for the given
- hostname is present and matches the expected key.
- """
- hostsFile = self.loadSampleHostsFile()
- self.assertEqual(True, hostsFile.hasHostKey(
- "www.twistedmatrix.com", Key.fromString(sampleKey)))
-
-
- def test_hasNonPresentKey(self):
- """
- L{KnownHostsFile.hasHostKey} returns C{False} when a key for the given
- hostname is not present.
- """
- hostsFile = self.loadSampleHostsFile()
- self.assertEqual(False, hostsFile.hasHostKey(
- "non-existent.example.com", Key.fromString(sampleKey)))
-
-
- def test_hasLaterAddedKey(self):
- """
- L{KnownHostsFile.hasHostKey} returns C{True} when a key for the given
- hostname is present in the file, even if it is only added to the file
- after the L{KnownHostsFile} instance is initialized.
- """
- key = Key.fromString(sampleKey)
- entry = PlainEntry(["brandnew.example.com"], key.sshType(), key, "")
- hostsFile = self.loadSampleHostsFile()
- with hostsFile.savePath.open("a") as hostsFileObj:
- hostsFileObj.write(entry.toString() + "\n")
- self.assertEqual(
- True, hostsFile.hasHostKey("brandnew.example.com", key))
-
-
- def test_savedEntryHasKeyMismatch(self):
- """
- L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key is
- present in the underlying file, but different from the expected one.
- The resulting exception should have an C{offendingEntry} indicating the
- given entry.
- """
- hostsFile = self.loadSampleHostsFile()
- entries = list(hostsFile.iterentries())
- exception = self.assertRaises(
- HostKeyChanged, hostsFile.hasHostKey,
- "www.twistedmatrix.com", Key.fromString(otherSampleKey))
- self.assertEqual(exception.offendingEntry, entries[0])
- self.assertEqual(exception.lineno, 1)
- self.assertEqual(exception.path, hostsFile.savePath)
-
-
- def test_savedEntryAfterAddHasKeyMismatch(self):
- """
- Even after a new entry has been added in memory but not yet saved, the
- L{HostKeyChanged} exception raised by L{KnownHostsFile.hasHostKey} has a
- C{lineno} attribute which indicates the 1-based line number of the
- offending entry in the underlying file when the given host key does not
- match the expected host key.
- """
- hostsFile = self.loadSampleHostsFile()
- hostsFile.addHostKey(
- "www.example.com", Key.fromString(otherSampleKey))
- exception = self.assertRaises(
- HostKeyChanged, hostsFile.hasHostKey,
- "www.twistedmatrix.com", Key.fromString(otherSampleKey))
- self.assertEqual(exception.lineno, 1)
- self.assertEqual(exception.path, hostsFile.savePath)
-
-
- def test_unsavedEntryHasKeyMismatch(self):
- """
- L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key is
- present in memory (but not yet saved), but different from the expected
- one. The resulting exception has a C{offendingEntry} indicating the
- given entry, but no filename or line number information (reflecting the
- fact that the entry exists only in memory).
- """
- hostsFile = KnownHostsFile(FilePath(self.mktemp()))
- entry = hostsFile.addHostKey(
- "www.example.com", Key.fromString(otherSampleKey))
- exception = self.assertRaises(
- HostKeyChanged, hostsFile.hasHostKey,
- "www.example.com", Key.fromString(thirdSampleKey))
- self.assertEqual(exception.offendingEntry, entry)
- self.assertEqual(exception.lineno, None)
- self.assertEqual(exception.path, None)
-
-
- def test_addHostKey(self):
- """
- L{KnownHostsFile.addHostKey} adds a new L{HashedEntry} to the host
- file, and returns it.
- """
- hostsFile = self.loadSampleHostsFile()
- aKey = Key.fromString(thirdSampleKey)
- self.assertEqual(False,
- hostsFile.hasHostKey("somewhere.example.com", aKey))
- newEntry = hostsFile.addHostKey("somewhere.example.com", aKey)
-
- # The code in OpenSSH requires host salts to be 20 characters long.
- # This is the required length of a SHA-1 HMAC hash, so it's just a
- # sanity check.
- self.assertEqual(20, len(newEntry._hostSalt))
- self.assertEqual(True,
- newEntry.matchesHost("somewhere.example.com"))
- self.assertEqual(newEntry.keyType, "ssh-rsa")
- self.assertEqual(aKey, newEntry.publicKey)
- self.assertEqual(True,
- hostsFile.hasHostKey("somewhere.example.com", aKey))
-
-
- def test_randomSalts(self):
- """
- L{KnownHostsFile.addHostKey} generates a random salt for each new key,
- so subsequent salts will be different.
- """
- hostsFile = self.loadSampleHostsFile()
- aKey = Key.fromString(thirdSampleKey)
- self.assertNotEqual(
- hostsFile.addHostKey("somewhere.example.com", aKey)._hostSalt,
- hostsFile.addHostKey("somewhere-else.example.com", aKey)._hostSalt)
-
-
- def test_verifyValidKey(self):
- """
- Verifying a valid key should return a L{Deferred} which fires with
- True.
- """
- hostsFile = self.loadSampleHostsFile()
- hostsFile.addHostKey("1.2.3.4", Key.fromString(sampleKey))
- ui = FakeUI()
- d = hostsFile.verifyHostKey(ui, "www.twistedmatrix.com", "1.2.3.4",
- Key.fromString(sampleKey))
- l = []
- d.addCallback(l.append)
- self.assertEqual(l, [True])
-
-
- def test_verifyInvalidKey(self):
- """
- Verfying an invalid key should return a L{Deferred} which fires with a
- L{HostKeyChanged} failure.
- """
- hostsFile = self.loadSampleHostsFile()
- wrongKey = Key.fromString(thirdSampleKey)
- ui = FakeUI()
- hostsFile.addHostKey("1.2.3.4", Key.fromString(sampleKey))
- d = hostsFile.verifyHostKey(
- ui, "www.twistedmatrix.com", "1.2.3.4", wrongKey)
- return self.assertFailure(d, HostKeyChanged)
-
-
- def verifyNonPresentKey(self):
- """
- Set up a test to verify a key that isn't present. Return a 3-tuple of
- the UI, a list set up to collect the result of the verifyHostKey call,
- and the sample L{KnownHostsFile} being used.
-
- This utility method avoids returning a L{Deferred}, and records results
- in the returned list instead, because the events which get generated
- here are pre-recorded in the 'ui' object. If the L{Deferred} in
- question does not fire, the it will fail quickly with an empty list.
- """
- hostsFile = self.loadSampleHostsFile()
- absentKey = Key.fromString(thirdSampleKey)
- ui = FakeUI()
- l = []
- d = hostsFile.verifyHostKey(
- ui, "sample-host.example.com", "4.3.2.1", absentKey)
- d.addBoth(l.append)
- self.assertEqual([], l)
- self.assertEqual(
- ui.promptText,
- "The authenticity of host 'sample-host.example.com (4.3.2.1)' "
- "can't be established.\n"
- "RSA key fingerprint is "
- "89:4e:cc:8c:57:83:96:48:ef:63:ad:ee:99:00:4c:8f.\n"
- "Are you sure you want to continue connecting (yes/no)? ")
- return ui, l, hostsFile
-
-
- def test_verifyNonPresentKey_Yes(self):
- """
- Verifying a key where neither the hostname nor the IP are present
- should result in the UI being prompted with a message explaining as
- much. If the UI says yes, the Deferred should fire with True.
- """
- ui, l, knownHostsFile = self.verifyNonPresentKey()
- ui.promptDeferred.callback(True)
- self.assertEqual([True], l)
- reloaded = KnownHostsFile.fromPath(knownHostsFile.savePath)
- self.assertEqual(
- True,
- reloaded.hasHostKey("4.3.2.1", Key.fromString(thirdSampleKey)))
- self.assertEqual(
- True,
- reloaded.hasHostKey("sample-host.example.com",
- Key.fromString(thirdSampleKey)))
-
-
- def test_verifyNonPresentKey_No(self):
- """
- Verifying a key where neither the hostname nor the IP are present
- should result in the UI being prompted with a message explaining as
- much. If the UI says no, the Deferred should fail with
- UserRejectedKey.
- """
- ui, l, knownHostsFile = self.verifyNonPresentKey()
- ui.promptDeferred.callback(False)
- l[0].trap(UserRejectedKey)
-
-
- def test_verifyHostIPMismatch(self):
- """
- Verifying a key where the host is present (and correct), but the IP is
- present and different, should result the deferred firing in a
- HostKeyChanged failure.
- """
- hostsFile = self.loadSampleHostsFile()
- wrongKey = Key.fromString(thirdSampleKey)
- ui = FakeUI()
- d = hostsFile.verifyHostKey(
- ui, "www.twistedmatrix.com", "4.3.2.1", wrongKey)
- return self.assertFailure(d, HostKeyChanged)
-
-
- def test_verifyKeyForHostAndIP(self):
- """
- Verifying a key where the hostname is present but the IP is not should
- result in the key being added for the IP and the user being warned
- about the change.
- """
- ui = FakeUI()
- hostsFile = self.loadSampleHostsFile()
- expectedKey = Key.fromString(sampleKey)
- hostsFile.verifyHostKey(
- ui, "www.twistedmatrix.com", "5.4.3.2", expectedKey)
- self.assertEqual(
- True, KnownHostsFile.fromPath(hostsFile.savePath).hasHostKey(
- "5.4.3.2", expectedKey))
- self.assertEqual(
- ["Warning: Permanently added the RSA host key for IP address "
- "'5.4.3.2' to the list of known hosts."],
- ui.userWarnings)
-
-
-class FakeFile(object):
- """
- A fake file-like object that acts enough like a file for
- L{ConsoleUI.prompt}.
- """
-
- def __init__(self):
- self.inlines = []
- self.outchunks = []
- self.closed = False
-
-
- def readline(self):
- """
- Return a line from the 'inlines' list.
- """
- return self.inlines.pop(0)
-
-
- def write(self, chunk):
- """
- Append the given item to the 'outchunks' list.
- """
- if self.closed:
- raise IOError("the file was closed")
- self.outchunks.append(chunk)
-
-
- def close(self):
- """
- Set the 'closed' flag to True, explicitly marking that it has been
- closed.
- """
- self.closed = True
-
-
-
-class ConsoleUITests(TestCase):
- """
- Test cases for L{ConsoleUI}.
- """
-
- def setUp(self):
- """
- Create a L{ConsoleUI} pointed at a L{FakeFile}.
- """
- self.fakeFile = FakeFile()
- self.ui = ConsoleUI(self.openFile)
-
-
- def openFile(self):
- """
- Return the current fake file.
- """
- return self.fakeFile
-
-
- def newFile(self, lines):
- """
- Create a new fake file (the next file that self.ui will open) with the
- given list of lines to be returned from readline().
- """
- self.fakeFile = FakeFile()
- self.fakeFile.inlines = lines
-
-
- def test_promptYes(self):
- """
- L{ConsoleUI.prompt} writes a message to the console, then reads a line.
- If that line is 'yes', then it returns a L{Deferred} that fires with
- True.
- """
- for okYes in ['yes', 'Yes', 'yes\n']:
- self.newFile([okYes])
- l = []
- self.ui.prompt("Hello, world!").addCallback(l.append)
- self.assertEqual(["Hello, world!"], self.fakeFile.outchunks)
- self.assertEqual([True], l)
- self.assertEqual(True, self.fakeFile.closed)
-
-
- def test_promptNo(self):
- """
- L{ConsoleUI.prompt} writes a message to the console, then reads a line.
- If that line is 'no', then it returns a L{Deferred} that fires with
- False.
- """
- for okNo in ['no', 'No', 'no\n']:
- self.newFile([okNo])
- l = []
- self.ui.prompt("Goodbye, world!").addCallback(l.append)
- self.assertEqual(["Goodbye, world!"], self.fakeFile.outchunks)
- self.assertEqual([False], l)
- self.assertEqual(True, self.fakeFile.closed)
-
-
- def test_promptRepeatedly(self):
- """
- L{ConsoleUI.prompt} writes a message to the console, then reads a line.
- If that line is neither 'yes' nor 'no', then it says "Please enter
- 'yes' or 'no'" until it gets a 'yes' or a 'no', at which point it
- returns a Deferred that answers either True or False.
- """
- self.newFile(['what', 'uh', 'okay', 'yes'])
- l = []
- self.ui.prompt("Please say something useful.").addCallback(l.append)
- self.assertEqual([True], l)
- self.assertEqual(self.fakeFile.outchunks,
- ["Please say something useful."] +
- ["Please type 'yes' or 'no': "] * 3)
- self.assertEqual(True, self.fakeFile.closed)
- self.newFile(['blah', 'stuff', 'feh', 'no'])
- l = []
- self.ui.prompt("Please say something negative.").addCallback(l.append)
- self.assertEqual([False], l)
- self.assertEqual(self.fakeFile.outchunks,
- ["Please say something negative."] +
- ["Please type 'yes' or 'no': "] * 3)
- self.assertEqual(True, self.fakeFile.closed)
-
-
- def test_promptOpenFailed(self):
- """
- If the C{opener} passed to L{ConsoleUI} raises an exception, that
- exception will fail the L{Deferred} returned from L{ConsoleUI.prompt}.
- """
- def raiseIt():
- raise IOError()
- ui = ConsoleUI(raiseIt)
- d = ui.prompt("This is a test.")
- return self.assertFailure(d, IOError)
-
-
- def test_warn(self):
- """
- L{ConsoleUI.warn} should output a message to the console object.
- """
- self.ui.warn("Test message.")
- self.assertEqual(["Test message."], self.fakeFile.outchunks)
- self.assertEqual(True, self.fakeFile.closed)
-
-
- def test_warnOpenFailed(self):
- """
- L{ConsoleUI.warn} should log a traceback if the output can't be opened.
- """
- def raiseIt():
- 1 / 0
- ui = ConsoleUI(raiseIt)
- ui.warn("This message never makes it.")
- self.assertEqual(len(self.flushLoggedErrors(ZeroDivisionError)), 1)
-
-
-
-class FakeUI(object):
- """
- A fake UI object, adhering to the interface expected by
- L{KnownHostsFile.verifyHostKey}
-
- @ivar userWarnings: inputs provided to 'warn'.
-
- @ivar promptDeferred: last result returned from 'prompt'.
-
- @ivar promptText: the last input provided to 'prompt'.
- """
-
- def __init__(self):
- self.userWarnings = []
- self.promptDeferred = None
- self.promptText = None
-
-
- def prompt(self, text):
- """
- Issue the user an interactive prompt, which they can accept or deny.
- """
- self.promptText = text
- self.promptDeferred = Deferred()
- return self.promptDeferred
-
-
- def warn(self, text):
- """
- Issue a non-interactive warning to the user.
- """
- self.userWarnings.append(text)
-
-
-
-class FakeObject(object):
- """
- A fake object that can have some attributes. Used to fake
- L{SSHClientTransport} and L{SSHClientFactory}.
- """
-
-
-class DefaultAPITests(TestCase):
- """
- The API in L{twisted.conch.client.default.verifyHostKey} is the integration
- point between the code in the rest of conch and L{KnownHostsFile}.
- """
-
- def patchedOpen(self, fname, mode):
- """
- The patched version of 'open'; this returns a L{FakeFile} that the
- instantiated L{ConsoleUI} can use.
- """
- self.assertEqual(fname, "/dev/tty")
- self.assertEqual(mode, "r+b")
- return self.fakeFile
-
-
- def setUp(self):
- """
- Patch 'open' in verifyHostKey.
- """
- self.fakeFile = FakeFile()
- self.patch(default, "_open", self.patchedOpen)
- self.hostsOption = self.mktemp()
- knownHostsFile = KnownHostsFile(FilePath(self.hostsOption))
- knownHostsFile.addHostKey("exists.example.com",
- Key.fromString(sampleKey))
- knownHostsFile.addHostKey("4.3.2.1", Key.fromString(sampleKey))
- knownHostsFile.save()
- self.fakeTransport = FakeObject()
- self.fakeTransport.factory = FakeObject()
- self.options = self.fakeTransport.factory.options = {
- 'host': "exists.example.com",
- 'known-hosts': self.hostsOption
- }
-
-
- def test_verifyOKKey(self):
- """
- L{default.verifyHostKey} should return a L{Deferred} which fires with
- C{1} when passed a host, IP, and key which already match the
- known_hosts file it is supposed to check.
- """
- l = []
- default.verifyHostKey(self.fakeTransport, "4.3.2.1", sampleKey,
- "I don't care.").addCallback(l.append)
- self.assertEqual([1], l)
-
-
- def replaceHome(self, tempHome):
- """
- Replace the HOME environment variable until the end of the current
- test, with the given new home-directory, so that L{os.path.expanduser}
- will yield controllable, predictable results.
-
- @param tempHome: the pathname to replace the HOME variable with.
-
- @type tempHome: L{str}
- """
- oldHome = os.environ.get('HOME')
- def cleanupHome():
- if oldHome is None:
- del os.environ['HOME']
- else:
- os.environ['HOME'] = oldHome
- self.addCleanup(cleanupHome)
- os.environ['HOME'] = tempHome
-
-
- def test_noKnownHostsOption(self):
- """
- L{default.verifyHostKey} should find your known_hosts file in
- ~/.ssh/known_hosts if you don't specify one explicitly on the command
- line.
- """
- l = []
- tmpdir = self.mktemp()
- oldHostsOption = self.hostsOption
- hostsNonOption = FilePath(tmpdir).child(".ssh").child("known_hosts")
- hostsNonOption.parent().makedirs()
- FilePath(oldHostsOption).moveTo(hostsNonOption)
- self.replaceHome(tmpdir)
- self.options['known-hosts'] = None
- default.verifyHostKey(self.fakeTransport, "4.3.2.1", sampleKey,
- "I don't care.").addCallback(l.append)
- self.assertEqual([1], l)
-
-
- def test_verifyHostButNotIP(self):
- """
- L{default.verifyHostKey} should return a L{Deferred} which fires with
- C{1} when passed a host which matches with an IP is not present in its
- known_hosts file, and should also warn the user that it has added the
- IP address.
- """
- l = []
- default.verifyHostKey(self.fakeTransport, "8.7.6.5", sampleKey,
- "Fingerprint not required.").addCallback(l.append)
- self.assertEqual(
- ["Warning: Permanently added the RSA host key for IP address "
- "'8.7.6.5' to the list of known hosts."],
- self.fakeFile.outchunks)
- self.assertEqual([1], l)
- knownHostsFile = KnownHostsFile.fromPath(FilePath(self.hostsOption))
- self.assertEqual(True, knownHostsFile.hasHostKey("8.7.6.5",
- Key.fromString(sampleKey)))
-
-
- def test_verifyQuestion(self):
- """
- L{default.verifyHostKey} should return a L{Default} which fires with
- C{0} when passed a unknown host that the user refuses to acknowledge.
- """
- self.fakeTransport.factory.options['host'] = 'fake.example.com'
- self.fakeFile.inlines.append("no")
- d = default.verifyHostKey(
- self.fakeTransport, "9.8.7.6", otherSampleKey, "No fingerprint!")
- self.assertEqual(
- ["The authenticity of host 'fake.example.com (9.8.7.6)' "
- "can't be established.\n"
- "RSA key fingerprint is "
- "57:a1:c2:a1:07:a0:2b:f4:ce:b5:e5:b7:ae:cc:e1:99.\n"
- "Are you sure you want to continue connecting (yes/no)? "],
- self.fakeFile.outchunks)
- return self.assertFailure(d, UserRejectedKey)
-
-
- def test_verifyBadKey(self):
- """
- L{default.verifyHostKey} should return a L{Deferred} which fails with
- L{HostKeyChanged} if the host key is incorrect.
- """
- d = default.verifyHostKey(
- self.fakeTransport, "4.3.2.1", otherSampleKey,
- "Again, not required.")
- return self.assertFailure(d, HostKeyChanged)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_manhole.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_manhole.py
deleted file mode 100644
index 09dd52c..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_manhole.py
+++ /dev/null
@@ -1,372 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_manhole -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.manhole}.
-"""
-
-import traceback
-
-from twisted.trial import unittest
-from twisted.internet import error, defer
-from twisted.test.proto_helpers import StringTransport
-from twisted.conch.test.test_recvline import _TelnetMixin, _SSHMixin, _StdioMixin, stdio, ssh
-from twisted.conch import manhole
-from twisted.conch.insults import insults
-
-
-def determineDefaultFunctionName():
- """
- Return the string used by Python as the name for code objects which are
- compiled from interactive input or at the top-level of modules.
- """
- try:
- 1 // 0
- except:
- # The last frame is this function. The second to last frame is this
- # function's caller, which is module-scope, which is what we want,
- # so -2.
- return traceback.extract_stack()[-2][2]
-defaultFunctionName = determineDefaultFunctionName()
-
-
-
-class ManholeInterpreterTests(unittest.TestCase):
- """
- Tests for L{manhole.ManholeInterpreter}.
- """
- def test_resetBuffer(self):
- """
- L{ManholeInterpreter.resetBuffer} should empty the input buffer.
- """
- interpreter = manhole.ManholeInterpreter(None)
- interpreter.buffer.extend(["1", "2"])
- interpreter.resetBuffer()
- self.assertFalse(interpreter.buffer)
-
-
-
-class ManholeProtocolTests(unittest.TestCase):
- """
- Tests for L{manhole.Manhole}.
- """
- def test_interruptResetsInterpreterBuffer(self):
- """
- L{manhole.Manhole.handle_INT} should cause the interpreter input buffer
- to be reset.
- """
- transport = StringTransport()
- terminal = insults.ServerProtocol(manhole.Manhole)
- terminal.makeConnection(transport)
- protocol = terminal.terminalProtocol
- interpreter = protocol.interpreter
- interpreter.buffer.extend(["1", "2"])
- protocol.handle_INT()
- self.assertFalse(interpreter.buffer)
-
-
-
-class WriterTestCase(unittest.TestCase):
- def testInteger(self):
- manhole.lastColorizedLine("1")
-
-
- def testDoubleQuoteString(self):
- manhole.lastColorizedLine('"1"')
-
-
- def testSingleQuoteString(self):
- manhole.lastColorizedLine("'1'")
-
-
- def testTripleSingleQuotedString(self):
- manhole.lastColorizedLine("'''1'''")
-
-
- def testTripleDoubleQuotedString(self):
- manhole.lastColorizedLine('"""1"""')
-
-
- def testFunctionDefinition(self):
- manhole.lastColorizedLine("def foo():")
-
-
- def testClassDefinition(self):
- manhole.lastColorizedLine("class foo:")
-
-
-class ManholeLoopbackMixin:
- serverProtocol = manhole.ColoredManhole
-
- def wfd(self, d):
- return defer.waitForDeferred(d)
-
- def testSimpleExpression(self):
- done = self.recvlineClient.expect("done")
-
- self._testwrite(
- "1 + 1\n"
- "done")
-
- def finished(ign):
- self._assertBuffer(
- [">>> 1 + 1",
- "2",
- ">>> done"])
-
- return done.addCallback(finished)
-
- def testTripleQuoteLineContinuation(self):
- done = self.recvlineClient.expect("done")
-
- self._testwrite(
- "'''\n'''\n"
- "done")
-
- def finished(ign):
- self._assertBuffer(
- [">>> '''",
- "... '''",
- "'\\n'",
- ">>> done"])
-
- return done.addCallback(finished)
-
- def testFunctionDefinition(self):
- done = self.recvlineClient.expect("done")
-
- self._testwrite(
- "def foo(bar):\n"
- "\tprint bar\n\n"
- "foo(42)\n"
- "done")
-
- def finished(ign):
- self._assertBuffer(
- [">>> def foo(bar):",
- "... print bar",
- "... ",
- ">>> foo(42)",
- "42",
- ">>> done"])
-
- return done.addCallback(finished)
-
- def testClassDefinition(self):
- done = self.recvlineClient.expect("done")
-
- self._testwrite(
- "class Foo:\n"
- "\tdef bar(self):\n"
- "\t\tprint 'Hello, world!'\n\n"
- "Foo().bar()\n"
- "done")
-
- def finished(ign):
- self._assertBuffer(
- [">>> class Foo:",
- "... def bar(self):",
- "... print 'Hello, world!'",
- "... ",
- ">>> Foo().bar()",
- "Hello, world!",
- ">>> done"])
-
- return done.addCallback(finished)
-
- def testException(self):
- done = self.recvlineClient.expect("done")
-
- self._testwrite(
- "raise Exception('foo bar baz')\n"
- "done")
-
- def finished(ign):
- self._assertBuffer(
- [">>> raise Exception('foo bar baz')",
- "Traceback (most recent call last):",
- ' File "", line 1, in ' + defaultFunctionName,
- "Exception: foo bar baz",
- ">>> done"])
-
- return done.addCallback(finished)
-
- def testControlC(self):
- done = self.recvlineClient.expect("done")
-
- self._testwrite(
- "cancelled line" + manhole.CTRL_C +
- "done")
-
- def finished(ign):
- self._assertBuffer(
- [">>> cancelled line",
- "KeyboardInterrupt",
- ">>> done"])
-
- return done.addCallback(finished)
-
-
- def test_interruptDuringContinuation(self):
- """
- Sending ^C to Manhole while in a state where more input is required to
- complete a statement should discard the entire ongoing statement and
- reset the input prompt to the non-continuation prompt.
- """
- continuing = self.recvlineClient.expect("things")
-
- self._testwrite("(\nthings")
-
- def gotContinuation(ignored):
- self._assertBuffer(
- [">>> (",
- "... things"])
- interrupted = self.recvlineClient.expect(">>> ")
- self._testwrite(manhole.CTRL_C)
- return interrupted
- continuing.addCallback(gotContinuation)
-
- def gotInterruption(ignored):
- self._assertBuffer(
- [">>> (",
- "... things",
- "KeyboardInterrupt",
- ">>> "])
- continuing.addCallback(gotInterruption)
- return continuing
-
-
- def testControlBackslash(self):
- self._testwrite("cancelled line")
- partialLine = self.recvlineClient.expect("cancelled line")
-
- def gotPartialLine(ign):
- self._assertBuffer(
- [">>> cancelled line"])
- self._testwrite(manhole.CTRL_BACKSLASH)
-
- d = self.recvlineClient.onDisconnection
- return self.assertFailure(d, error.ConnectionDone)
-
- def gotClearedLine(ign):
- self._assertBuffer(
- [""])
-
- return partialLine.addCallback(gotPartialLine).addCallback(gotClearedLine)
-
- def testControlD(self):
- self._testwrite("1 + 1")
- helloWorld = self.wfd(self.recvlineClient.expect(r"\+ 1"))
- yield helloWorld
- helloWorld.getResult()
- self._assertBuffer([">>> 1 + 1"])
-
- self._testwrite(manhole.CTRL_D + " + 1")
- cleared = self.wfd(self.recvlineClient.expect(r"\+ 1"))
- yield cleared
- cleared.getResult()
- self._assertBuffer([">>> 1 + 1 + 1"])
-
- self._testwrite("\n")
- printed = self.wfd(self.recvlineClient.expect("3\n>>> "))
- yield printed
- printed.getResult()
-
- self._testwrite(manhole.CTRL_D)
- d = self.recvlineClient.onDisconnection
- disconnected = self.wfd(self.assertFailure(d, error.ConnectionDone))
- yield disconnected
- disconnected.getResult()
- testControlD = defer.deferredGenerator(testControlD)
-
-
- def testControlL(self):
- """
- CTRL+L is generally used as a redraw-screen command in terminal
- applications. Manhole doesn't currently respect this usage of it,
- but it should at least do something reasonable in response to this
- event (rather than, say, eating your face).
- """
- # Start off with a newline so that when we clear the display we can
- # tell by looking for the missing first empty prompt line.
- self._testwrite("\n1 + 1")
- helloWorld = self.wfd(self.recvlineClient.expect(r"\+ 1"))
- yield helloWorld
- helloWorld.getResult()
- self._assertBuffer([">>> ", ">>> 1 + 1"])
-
- self._testwrite(manhole.CTRL_L + " + 1")
- redrew = self.wfd(self.recvlineClient.expect(r"1 \+ 1 \+ 1"))
- yield redrew
- redrew.getResult()
- self._assertBuffer([">>> 1 + 1 + 1"])
- testControlL = defer.deferredGenerator(testControlL)
-
-
- def test_controlA(self):
- """
- CTRL-A can be used as HOME - returning cursor to beginning of
- current line buffer.
- """
- self._testwrite('rint "hello"' + '\x01' + 'p')
- d = self.recvlineClient.expect('print "hello"')
- def cb(ignore):
- self._assertBuffer(['>>> print "hello"'])
- return d.addCallback(cb)
-
-
- def test_controlE(self):
- """
- CTRL-E can be used as END - setting cursor to end of current
- line buffer.
- """
- self._testwrite('rint "hello' + '\x01' + 'p' + '\x05' + '"')
- d = self.recvlineClient.expect('print "hello"')
- def cb(ignore):
- self._assertBuffer(['>>> print "hello"'])
- return d.addCallback(cb)
-
-
- def testDeferred(self):
- self._testwrite(
- "from twisted.internet import defer, reactor\n"
- "d = defer.Deferred()\n"
- "d\n")
-
- deferred = self.wfd(self.recvlineClient.expect(""))
- yield deferred
- deferred.getResult()
-
- self._testwrite(
- "c = reactor.callLater(0.1, d.callback, 'Hi!')\n")
- delayed = self.wfd(self.recvlineClient.expect(">>> "))
- yield delayed
- delayed.getResult()
-
- called = self.wfd(self.recvlineClient.expect("Deferred #0 called back: 'Hi!'\n>>> "))
- yield called
- called.getResult()
- self._assertBuffer(
- [">>> from twisted.internet import defer, reactor",
- ">>> d = defer.Deferred()",
- ">>> d",
- "",
- ">>> c = reactor.callLater(0.1, d.callback, 'Hi!')",
- "Deferred #0 called back: 'Hi!'",
- ">>> "])
-
- testDeferred = defer.deferredGenerator(testDeferred)
-
-class ManholeLoopbackTelnet(_TelnetMixin, unittest.TestCase, ManholeLoopbackMixin):
- pass
-
-class ManholeLoopbackSSH(_SSHMixin, unittest.TestCase, ManholeLoopbackMixin):
- if ssh is None:
- skip = "Crypto requirements missing, can't run manhole tests over ssh"
-
-class ManholeLoopbackStdio(_StdioMixin, unittest.TestCase, ManholeLoopbackMixin):
- if stdio is None:
- skip = "Terminal requirements missing, can't run manhole tests over stdio"
- else:
- serverProtocol = stdio.ConsoleManhole
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_mixin.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_mixin.py
deleted file mode 100644
index 592aa48..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_mixin.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# -*- twisted.conch.test.test_mixin -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-import time
-
-from twisted.internet import reactor, protocol
-
-from twisted.trial import unittest
-from twisted.test.proto_helpers import StringTransport
-
-from twisted.conch import mixin
-
-
-class TestBufferingProto(mixin.BufferingMixin):
- scheduled = False
- rescheduled = 0
- def schedule(self):
- self.scheduled = True
- return object()
-
- def reschedule(self, token):
- self.rescheduled += 1
-
-
-
-class BufferingTest(unittest.TestCase):
- def testBuffering(self):
- p = TestBufferingProto()
- t = p.transport = StringTransport()
-
- self.assertFalse(p.scheduled)
-
- L = ['foo', 'bar', 'baz', 'quux']
-
- p.write('foo')
- self.assertTrue(p.scheduled)
- self.assertFalse(p.rescheduled)
-
- for s in L:
- n = p.rescheduled
- p.write(s)
- self.assertEqual(p.rescheduled, n + 1)
- self.assertEqual(t.value(), '')
-
- p.flush()
- self.assertEqual(t.value(), 'foo' + ''.join(L))
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_openssh_compat.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_openssh_compat.py
deleted file mode 100644
index 2713fcc..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_openssh_compat.py
+++ /dev/null
@@ -1,101 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.openssh_compat}.
-"""
-
-import os
-
-from twisted.trial.unittest import TestCase
-from twisted.python.filepath import FilePath
-
-try:
- import Crypto.Cipher.DES3
- import pyasn1
-except ImportError:
- OpenSSHFactory = None
-else:
- from twisted.conch.openssh_compat.factory import OpenSSHFactory
-
-from twisted.conch.test import keydata
-from twisted.test.test_process import MockOS
-
-
-class OpenSSHFactoryTests(TestCase):
- """
- Tests for L{OpenSSHFactory}.
- """
- if getattr(os, "geteuid", None) is None:
- skip = "geteuid/seteuid not available"
- elif OpenSSHFactory is None:
- skip = "Cannot run without PyCrypto or PyASN1"
-
- def setUp(self):
- self.factory = OpenSSHFactory()
- self.keysDir = FilePath(self.mktemp())
- self.keysDir.makedirs()
- self.factory.dataRoot = self.keysDir.path
-
- self.keysDir.child("ssh_host_foo").setContent("foo")
- self.keysDir.child("bar_key").setContent("foo")
- self.keysDir.child("ssh_host_one_key").setContent(
- keydata.privateRSA_openssh)
- self.keysDir.child("ssh_host_two_key").setContent(
- keydata.privateDSA_openssh)
- self.keysDir.child("ssh_host_three_key").setContent(
- "not a key content")
-
- self.keysDir.child("ssh_host_one_key.pub").setContent(
- keydata.publicRSA_openssh)
-
- self.mockos = MockOS()
- self.patch(os, "seteuid", self.mockos.seteuid)
- self.patch(os, "setegid", self.mockos.setegid)
-
-
- def test_getPublicKeys(self):
- """
- L{OpenSSHFactory.getPublicKeys} should return the available public keys
- in the data directory
- """
- keys = self.factory.getPublicKeys()
- self.assertEqual(len(keys), 1)
- keyTypes = keys.keys()
- self.assertEqual(keyTypes, ['ssh-rsa'])
-
-
- def test_getPrivateKeys(self):
- """
- L{OpenSSHFactory.getPrivateKeys} should return the available private
- keys in the data directory.
- """
- keys = self.factory.getPrivateKeys()
- self.assertEqual(len(keys), 2)
- keyTypes = keys.keys()
- self.assertEqual(set(keyTypes), set(['ssh-rsa', 'ssh-dss']))
- self.assertEqual(self.mockos.seteuidCalls, [])
- self.assertEqual(self.mockos.setegidCalls, [])
-
-
- def test_getPrivateKeysAsRoot(self):
- """
- L{OpenSSHFactory.getPrivateKeys} should switch to root if the keys
- aren't readable by the current user.
- """
- keyFile = self.keysDir.child("ssh_host_two_key")
- # Fake permission error by changing the mode
- keyFile.chmod(0000)
- self.addCleanup(keyFile.chmod, 0777)
- # And restore the right mode when seteuid is called
- savedSeteuid = os.seteuid
- def seteuid(euid):
- keyFile.chmod(0777)
- return savedSeteuid(euid)
- self.patch(os, "seteuid", seteuid)
- keys = self.factory.getPrivateKeys()
- self.assertEqual(len(keys), 2)
- keyTypes = keys.keys()
- self.assertEqual(set(keyTypes), set(['ssh-rsa', 'ssh-dss']))
- self.assertEqual(self.mockos.seteuidCalls, [0, os.geteuid()])
- self.assertEqual(self.mockos.setegidCalls, [0, os.getegid()])
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_recvline.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_recvline.py
deleted file mode 100644
index 3d53564..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_recvline.py
+++ /dev/null
@@ -1,706 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_recvline -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.recvline} and fixtures for testing related
-functionality.
-"""
-
-import sys, os
-
-from twisted.conch.insults import insults
-from twisted.conch import recvline
-
-from twisted.python import reflect, components
-from twisted.internet import defer, error
-from twisted.trial import unittest
-from twisted.cred import portal
-from twisted.test.proto_helpers import StringTransport
-
-class Arrows(unittest.TestCase):
- def setUp(self):
- self.underlyingTransport = StringTransport()
- self.pt = insults.ServerProtocol()
- self.p = recvline.HistoricRecvLine()
- self.pt.protocolFactory = lambda: self.p
- self.pt.factory = self
- self.pt.makeConnection(self.underlyingTransport)
- # self.p.makeConnection(self.pt)
-
- def test_printableCharacters(self):
- """
- When L{HistoricRecvLine} receives a printable character,
- it adds it to the current line buffer.
- """
- self.p.keystrokeReceived('x', None)
- self.p.keystrokeReceived('y', None)
- self.p.keystrokeReceived('z', None)
-
- self.assertEqual(self.p.currentLineBuffer(), ('xyz', ''))
-
- def test_horizontalArrows(self):
- """
- When L{HistoricRecvLine} receives an LEFT_ARROW or
- RIGHT_ARROW keystroke it moves the cursor left or right
- in the current line buffer, respectively.
- """
- kR = lambda ch: self.p.keystrokeReceived(ch, None)
- for ch in 'xyz':
- kR(ch)
-
- self.assertEqual(self.p.currentLineBuffer(), ('xyz', ''))
-
- kR(self.pt.RIGHT_ARROW)
- self.assertEqual(self.p.currentLineBuffer(), ('xyz', ''))
-
- kR(self.pt.LEFT_ARROW)
- self.assertEqual(self.p.currentLineBuffer(), ('xy', 'z'))
-
- kR(self.pt.LEFT_ARROW)
- self.assertEqual(self.p.currentLineBuffer(), ('x', 'yz'))
-
- kR(self.pt.LEFT_ARROW)
- self.assertEqual(self.p.currentLineBuffer(), ('', 'xyz'))
-
- kR(self.pt.LEFT_ARROW)
- self.assertEqual(self.p.currentLineBuffer(), ('', 'xyz'))
-
- kR(self.pt.RIGHT_ARROW)
- self.assertEqual(self.p.currentLineBuffer(), ('x', 'yz'))
-
- kR(self.pt.RIGHT_ARROW)
- self.assertEqual(self.p.currentLineBuffer(), ('xy', 'z'))
-
- kR(self.pt.RIGHT_ARROW)
- self.assertEqual(self.p.currentLineBuffer(), ('xyz', ''))
-
- kR(self.pt.RIGHT_ARROW)
- self.assertEqual(self.p.currentLineBuffer(), ('xyz', ''))
-
- def test_newline(self):
- """
- When {HistoricRecvLine} receives a newline, it adds the current
- line buffer to the end of its history buffer.
- """
- kR = lambda ch: self.p.keystrokeReceived(ch, None)
-
- for ch in 'xyz\nabc\n123\n':
- kR(ch)
-
- self.assertEqual(self.p.currentHistoryBuffer(),
- (('xyz', 'abc', '123'), ()))
-
- kR('c')
- kR('b')
- kR('a')
- self.assertEqual(self.p.currentHistoryBuffer(),
- (('xyz', 'abc', '123'), ()))
-
- kR('\n')
- self.assertEqual(self.p.currentHistoryBuffer(),
- (('xyz', 'abc', '123', 'cba'), ()))
-
- def test_verticalArrows(self):
- """
- When L{HistoricRecvLine} receives UP_ARROW or DOWN_ARROW
- keystrokes it move the current index in the current history
- buffer up or down, and resets the current line buffer to the
- previous or next line in history, respectively for each.
- """
- kR = lambda ch: self.p.keystrokeReceived(ch, None)
-
- for ch in 'xyz\nabc\n123\n':
- kR(ch)
-
- self.assertEqual(self.p.currentHistoryBuffer(),
- (('xyz', 'abc', '123'), ()))
- self.assertEqual(self.p.currentLineBuffer(), ('', ''))
-
- kR(self.pt.UP_ARROW)
- self.assertEqual(self.p.currentHistoryBuffer(),
- (('xyz', 'abc'), ('123',)))
- self.assertEqual(self.p.currentLineBuffer(), ('123', ''))
-
- kR(self.pt.UP_ARROW)
- self.assertEqual(self.p.currentHistoryBuffer(),
- (('xyz',), ('abc', '123')))
- self.assertEqual(self.p.currentLineBuffer(), ('abc', ''))
-
- kR(self.pt.UP_ARROW)
- self.assertEqual(self.p.currentHistoryBuffer(),
- ((), ('xyz', 'abc', '123')))
- self.assertEqual(self.p.currentLineBuffer(), ('xyz', ''))
-
- kR(self.pt.UP_ARROW)
- self.assertEqual(self.p.currentHistoryBuffer(),
- ((), ('xyz', 'abc', '123')))
- self.assertEqual(self.p.currentLineBuffer(), ('xyz', ''))
-
- for i in range(4):
- kR(self.pt.DOWN_ARROW)
- self.assertEqual(self.p.currentHistoryBuffer(),
- (('xyz', 'abc', '123'), ()))
-
- def test_home(self):
- """
- When L{HistoricRecvLine} receives a HOME keystroke it moves the
- cursor to the beginning of the current line buffer.
- """
- kR = lambda ch: self.p.keystrokeReceived(ch, None)
-
- for ch in 'hello, world':
- kR(ch)
- self.assertEqual(self.p.currentLineBuffer(), ('hello, world', ''))
-
- kR(self.pt.HOME)
- self.assertEqual(self.p.currentLineBuffer(), ('', 'hello, world'))
-
- def test_end(self):
- """
- When L{HistoricRecvLine} receives a END keystroke it moves the cursor
- to the end of the current line buffer.
- """
- kR = lambda ch: self.p.keystrokeReceived(ch, None)
-
- for ch in 'hello, world':
- kR(ch)
- self.assertEqual(self.p.currentLineBuffer(), ('hello, world', ''))
-
- kR(self.pt.HOME)
- kR(self.pt.END)
- self.assertEqual(self.p.currentLineBuffer(), ('hello, world', ''))
-
- def test_backspace(self):
- """
- When L{HistoricRecvLine} receives a BACKSPACE keystroke it deletes
- the character immediately before the cursor.
- """
- kR = lambda ch: self.p.keystrokeReceived(ch, None)
-
- for ch in 'xyz':
- kR(ch)
- self.assertEqual(self.p.currentLineBuffer(), ('xyz', ''))
-
- kR(self.pt.BACKSPACE)
- self.assertEqual(self.p.currentLineBuffer(), ('xy', ''))
-
- kR(self.pt.LEFT_ARROW)
- kR(self.pt.BACKSPACE)
- self.assertEqual(self.p.currentLineBuffer(), ('', 'y'))
-
- kR(self.pt.BACKSPACE)
- self.assertEqual(self.p.currentLineBuffer(), ('', 'y'))
-
- def test_delete(self):
- """
- When L{HistoricRecvLine} receives a DELETE keystroke, it
- delets the character immediately after the cursor.
- """
- kR = lambda ch: self.p.keystrokeReceived(ch, None)
-
- for ch in 'xyz':
- kR(ch)
- self.assertEqual(self.p.currentLineBuffer(), ('xyz', ''))
-
- kR(self.pt.DELETE)
- self.assertEqual(self.p.currentLineBuffer(), ('xyz', ''))
-
- kR(self.pt.LEFT_ARROW)
- kR(self.pt.DELETE)
- self.assertEqual(self.p.currentLineBuffer(), ('xy', ''))
-
- kR(self.pt.LEFT_ARROW)
- kR(self.pt.DELETE)
- self.assertEqual(self.p.currentLineBuffer(), ('x', ''))
-
- kR(self.pt.LEFT_ARROW)
- kR(self.pt.DELETE)
- self.assertEqual(self.p.currentLineBuffer(), ('', ''))
-
- kR(self.pt.DELETE)
- self.assertEqual(self.p.currentLineBuffer(), ('', ''))
-
- def test_insert(self):
- """
- When not in INSERT mode, L{HistoricRecvLine} inserts the typed
- character at the cursor before the next character.
- """
- kR = lambda ch: self.p.keystrokeReceived(ch, None)
-
- for ch in 'xyz':
- kR(ch)
-
- kR(self.pt.LEFT_ARROW)
- kR('A')
- self.assertEqual(self.p.currentLineBuffer(), ('xyA', 'z'))
-
- kR(self.pt.LEFT_ARROW)
- kR('B')
- self.assertEqual(self.p.currentLineBuffer(), ('xyB', 'Az'))
-
- def test_typeover(self):
- """
- When in INSERT mode and upon receiving a keystroke with a printable
- character, L{HistoricRecvLine} replaces the character at
- the cursor with the typed character rather than inserting before.
- Ah, the ironies of INSERT mode.
- """
- kR = lambda ch: self.p.keystrokeReceived(ch, None)
-
- for ch in 'xyz':
- kR(ch)
-
- kR(self.pt.INSERT)
-
- kR(self.pt.LEFT_ARROW)
- kR('A')
- self.assertEqual(self.p.currentLineBuffer(), ('xyA', ''))
-
- kR(self.pt.LEFT_ARROW)
- kR('B')
- self.assertEqual(self.p.currentLineBuffer(), ('xyB', ''))
-
-
- def test_unprintableCharacters(self):
- """
- When L{HistoricRecvLine} receives a keystroke for an unprintable
- function key with no assigned behavior, the line buffer is unmodified.
- """
- kR = lambda ch: self.p.keystrokeReceived(ch, None)
- pt = self.pt
-
- for ch in (pt.F1, pt.F2, pt.F3, pt.F4, pt.F5, pt.F6, pt.F7, pt.F8,
- pt.F9, pt.F10, pt.F11, pt.F12, pt.PGUP, pt.PGDN):
- kR(ch)
- self.assertEqual(self.p.currentLineBuffer(), ('', ''))
-
-
-from twisted.conch import telnet
-from twisted.conch.insults import helper
-from twisted.protocols import loopback
-
-class EchoServer(recvline.HistoricRecvLine):
- def lineReceived(self, line):
- self.terminal.write(line + '\n' + self.ps[self.pn])
-
-# An insults API for this would be nice.
-left = "\x1b[D"
-right = "\x1b[C"
-up = "\x1b[A"
-down = "\x1b[B"
-insert = "\x1b[2~"
-home = "\x1b[1~"
-delete = "\x1b[3~"
-end = "\x1b[4~"
-backspace = "\x7f"
-
-from twisted.cred import checkers
-
-try:
- from twisted.conch.ssh import userauth, transport, channel, connection, session
- from twisted.conch.manhole_ssh import TerminalUser, TerminalSession, TerminalRealm, TerminalSessionTransport, ConchFactory
-except ImportError:
- ssh = False
-else:
- ssh = True
- class SessionChannel(channel.SSHChannel):
- name = 'session'
-
- def __init__(self, protocolFactory, protocolArgs, protocolKwArgs, width, height, *a, **kw):
- channel.SSHChannel.__init__(self, *a, **kw)
-
- self.protocolFactory = protocolFactory
- self.protocolArgs = protocolArgs
- self.protocolKwArgs = protocolKwArgs
-
- self.width = width
- self.height = height
-
- def channelOpen(self, data):
- term = session.packRequest_pty_req("vt102", (self.height, self.width, 0, 0), '')
- self.conn.sendRequest(self, 'pty-req', term)
- self.conn.sendRequest(self, 'shell', '')
-
- self._protocolInstance = self.protocolFactory(*self.protocolArgs, **self.protocolKwArgs)
- self._protocolInstance.factory = self
- self._protocolInstance.makeConnection(self)
-
- def closed(self):
- self._protocolInstance.connectionLost(error.ConnectionDone())
-
- def dataReceived(self, data):
- self._protocolInstance.dataReceived(data)
-
- class TestConnection(connection.SSHConnection):
- def __init__(self, protocolFactory, protocolArgs, protocolKwArgs, width, height, *a, **kw):
- connection.SSHConnection.__init__(self, *a, **kw)
-
- self.protocolFactory = protocolFactory
- self.protocolArgs = protocolArgs
- self.protocolKwArgs = protocolKwArgs
-
- self.width = width
- self.height = height
-
- def serviceStarted(self):
- self.__channel = SessionChannel(self.protocolFactory, self.protocolArgs, self.protocolKwArgs, self.width, self.height)
- self.openChannel(self.__channel)
-
- def write(self, bytes):
- return self.__channel.write(bytes)
-
- class TestAuth(userauth.SSHUserAuthClient):
- def __init__(self, username, password, *a, **kw):
- userauth.SSHUserAuthClient.__init__(self, username, *a, **kw)
- self.password = password
-
- def getPassword(self):
- return defer.succeed(self.password)
-
- class TestTransport(transport.SSHClientTransport):
- def __init__(self, protocolFactory, protocolArgs, protocolKwArgs, username, password, width, height, *a, **kw):
- # transport.SSHClientTransport.__init__(self, *a, **kw)
- self.protocolFactory = protocolFactory
- self.protocolArgs = protocolArgs
- self.protocolKwArgs = protocolKwArgs
- self.username = username
- self.password = password
- self.width = width
- self.height = height
-
- def verifyHostKey(self, hostKey, fingerprint):
- return defer.succeed(True)
-
- def connectionSecure(self):
- self.__connection = TestConnection(self.protocolFactory, self.protocolArgs, self.protocolKwArgs, self.width, self.height)
- self.requestService(
- TestAuth(self.username, self.password, self.__connection))
-
- def write(self, bytes):
- return self.__connection.write(bytes)
-
- class TestSessionTransport(TerminalSessionTransport):
- def protocolFactory(self):
- return self.avatar.conn.transport.factory.serverProtocol()
-
- class TestSession(TerminalSession):
- transportFactory = TestSessionTransport
-
- class TestUser(TerminalUser):
- pass
-
- components.registerAdapter(TestSession, TestUser, session.ISession)
-
-
-class LoopbackRelay(loopback.LoopbackRelay):
- clearCall = None
-
- def logPrefix(self):
- return "LoopbackRelay(%r)" % (self.target.__class__.__name__,)
-
- def write(self, bytes):
- loopback.LoopbackRelay.write(self, bytes)
- if self.clearCall is not None:
- self.clearCall.cancel()
-
- from twisted.internet import reactor
- self.clearCall = reactor.callLater(0, self._clearBuffer)
-
- def _clearBuffer(self):
- self.clearCall = None
- loopback.LoopbackRelay.clearBuffer(self)
-
-
-class NotifyingExpectableBuffer(helper.ExpectableBuffer):
- def __init__(self):
- self.onConnection = defer.Deferred()
- self.onDisconnection = defer.Deferred()
-
- def connectionMade(self):
- helper.ExpectableBuffer.connectionMade(self)
- self.onConnection.callback(self)
-
- def connectionLost(self, reason):
- self.onDisconnection.errback(reason)
-
-
-class _BaseMixin:
- WIDTH = 80
- HEIGHT = 24
-
- def _assertBuffer(self, lines):
- receivedLines = str(self.recvlineClient).splitlines()
- expectedLines = lines + ([''] * (self.HEIGHT - len(lines) - 1))
- self.assertEqual(len(receivedLines), len(expectedLines))
- for i in range(len(receivedLines)):
- self.assertEqual(
- receivedLines[i], expectedLines[i],
- str(receivedLines[max(0, i-1):i+1]) +
- " != " +
- str(expectedLines[max(0, i-1):i+1]))
-
- def _trivialTest(self, input, output):
- done = self.recvlineClient.expect("done")
-
- self._testwrite(input)
-
- def finished(ign):
- self._assertBuffer(output)
-
- return done.addCallback(finished)
-
-
-class _SSHMixin(_BaseMixin):
- def setUp(self):
- if not ssh:
- raise unittest.SkipTest("Crypto requirements missing, can't run historic recvline tests over ssh")
-
- u, p = 'testuser', 'testpass'
- rlm = TerminalRealm()
- rlm.userFactory = TestUser
- rlm.chainedProtocolFactory = lambda: insultsServer
-
- ptl = portal.Portal(
- rlm,
- [checkers.InMemoryUsernamePasswordDatabaseDontUse(**{u: p})])
- sshFactory = ConchFactory(ptl)
- sshFactory.serverProtocol = self.serverProtocol
- sshFactory.startFactory()
-
- recvlineServer = self.serverProtocol()
- insultsServer = insults.ServerProtocol(lambda: recvlineServer)
- sshServer = sshFactory.buildProtocol(None)
- clientTransport = LoopbackRelay(sshServer)
-
- recvlineClient = NotifyingExpectableBuffer()
- insultsClient = insults.ClientProtocol(lambda: recvlineClient)
- sshClient = TestTransport(lambda: insultsClient, (), {}, u, p, self.WIDTH, self.HEIGHT)
- serverTransport = LoopbackRelay(sshClient)
-
- sshClient.makeConnection(clientTransport)
- sshServer.makeConnection(serverTransport)
-
- self.recvlineClient = recvlineClient
- self.sshClient = sshClient
- self.sshServer = sshServer
- self.clientTransport = clientTransport
- self.serverTransport = serverTransport
-
- return recvlineClient.onConnection
-
- def _testwrite(self, bytes):
- self.sshClient.write(bytes)
-
-from twisted.conch.test import test_telnet
-
-class TestInsultsClientProtocol(insults.ClientProtocol,
- test_telnet.TestProtocol):
- pass
-
-
-class TestInsultsServerProtocol(insults.ServerProtocol,
- test_telnet.TestProtocol):
- pass
-
-class _TelnetMixin(_BaseMixin):
- def setUp(self):
- recvlineServer = self.serverProtocol()
- insultsServer = TestInsultsServerProtocol(lambda: recvlineServer)
- telnetServer = telnet.TelnetTransport(lambda: insultsServer)
- clientTransport = LoopbackRelay(telnetServer)
-
- recvlineClient = NotifyingExpectableBuffer()
- insultsClient = TestInsultsClientProtocol(lambda: recvlineClient)
- telnetClient = telnet.TelnetTransport(lambda: insultsClient)
- serverTransport = LoopbackRelay(telnetClient)
-
- telnetClient.makeConnection(clientTransport)
- telnetServer.makeConnection(serverTransport)
-
- serverTransport.clearBuffer()
- clientTransport.clearBuffer()
-
- self.recvlineClient = recvlineClient
- self.telnetClient = telnetClient
- self.clientTransport = clientTransport
- self.serverTransport = serverTransport
-
- return recvlineClient.onConnection
-
- def _testwrite(self, bytes):
- self.telnetClient.write(bytes)
-
-try:
- from twisted.conch import stdio
-except ImportError:
- stdio = None
-
-class _StdioMixin(_BaseMixin):
- def setUp(self):
- # A memory-only terminal emulator, into which the server will
- # write things and make other state changes. What ends up
- # here is basically what a user would have seen on their
- # screen.
- testTerminal = NotifyingExpectableBuffer()
-
- # An insults client protocol which will translate bytes
- # received from the child process into keystroke commands for
- # an ITerminalProtocol.
- insultsClient = insults.ClientProtocol(lambda: testTerminal)
-
- # A process protocol which will translate stdout and stderr
- # received from the child process to dataReceived calls and
- # error reporting on an insults client protocol.
- processClient = stdio.TerminalProcessProtocol(insultsClient)
-
- # Run twisted/conch/stdio.py with the name of a class
- # implementing ITerminalProtocol. This class will be used to
- # handle bytes we send to the child process.
- exe = sys.executable
- module = stdio.__file__
- if module.endswith('.pyc') or module.endswith('.pyo'):
- module = module[:-1]
- args = [exe, module, reflect.qual(self.serverProtocol)]
- env = os.environ.copy()
- env["PYTHONPATH"] = os.pathsep.join(sys.path)
-
- from twisted.internet import reactor
- clientTransport = reactor.spawnProcess(processClient, exe, args,
- env=env, usePTY=True)
-
- self.recvlineClient = self.testTerminal = testTerminal
- self.processClient = processClient
- self.clientTransport = clientTransport
-
- # Wait for the process protocol and test terminal to become
- # connected before proceeding. The former should always
- # happen first, but it doesn't hurt to be safe.
- return defer.gatherResults(filter(None, [
- processClient.onConnection,
- testTerminal.expect(">>> ")]))
-
- def tearDown(self):
- # Kill the child process. We're done with it.
- try:
- self.clientTransport.signalProcess("KILL")
- except (error.ProcessExitedAlready, OSError):
- pass
- def trap(failure):
- failure.trap(error.ProcessTerminated)
- self.assertEqual(failure.value.exitCode, None)
- self.assertEqual(failure.value.status, 9)
- return self.testTerminal.onDisconnection.addErrback(trap)
-
- def _testwrite(self, bytes):
- self.clientTransport.write(bytes)
-
-class RecvlineLoopbackMixin:
- serverProtocol = EchoServer
-
- def testSimple(self):
- return self._trivialTest(
- "first line\ndone",
- [">>> first line",
- "first line",
- ">>> done"])
-
- def testLeftArrow(self):
- return self._trivialTest(
- insert + 'first line' + left * 4 + "xxxx\ndone",
- [">>> first xxxx",
- "first xxxx",
- ">>> done"])
-
- def testRightArrow(self):
- return self._trivialTest(
- insert + 'right line' + left * 4 + right * 2 + "xx\ndone",
- [">>> right lixx",
- "right lixx",
- ">>> done"])
-
- def testBackspace(self):
- return self._trivialTest(
- "second line" + backspace * 4 + "xxxx\ndone",
- [">>> second xxxx",
- "second xxxx",
- ">>> done"])
-
- def testDelete(self):
- return self._trivialTest(
- "delete xxxx" + left * 4 + delete * 4 + "line\ndone",
- [">>> delete line",
- "delete line",
- ">>> done"])
-
- def testInsert(self):
- return self._trivialTest(
- "third ine" + left * 3 + "l\ndone",
- [">>> third line",
- "third line",
- ">>> done"])
-
- def testTypeover(self):
- return self._trivialTest(
- "fourth xine" + left * 4 + insert + "l\ndone",
- [">>> fourth line",
- "fourth line",
- ">>> done"])
-
- def testHome(self):
- return self._trivialTest(
- insert + "blah line" + home + "home\ndone",
- [">>> home line",
- "home line",
- ">>> done"])
-
- def testEnd(self):
- return self._trivialTest(
- "end " + left * 4 + end + "line\ndone",
- [">>> end line",
- "end line",
- ">>> done"])
-
-class RecvlineLoopbackTelnet(_TelnetMixin, unittest.TestCase, RecvlineLoopbackMixin):
- pass
-
-class RecvlineLoopbackSSH(_SSHMixin, unittest.TestCase, RecvlineLoopbackMixin):
- pass
-
-class RecvlineLoopbackStdio(_StdioMixin, unittest.TestCase, RecvlineLoopbackMixin):
- if stdio is None:
- skip = "Terminal requirements missing, can't run recvline tests over stdio"
-
-
-class HistoricRecvlineLoopbackMixin:
- serverProtocol = EchoServer
-
- def testUpArrow(self):
- return self._trivialTest(
- "first line\n" + up + "\ndone",
- [">>> first line",
- "first line",
- ">>> first line",
- "first line",
- ">>> done"])
-
- def testDownArrow(self):
- return self._trivialTest(
- "first line\nsecond line\n" + up * 2 + down + "\ndone",
- [">>> first line",
- "first line",
- ">>> second line",
- "second line",
- ">>> second line",
- "second line",
- ">>> done"])
-
-class HistoricRecvlineLoopbackTelnet(_TelnetMixin, unittest.TestCase, HistoricRecvlineLoopbackMixin):
- pass
-
-class HistoricRecvlineLoopbackSSH(_SSHMixin, unittest.TestCase, HistoricRecvlineLoopbackMixin):
- pass
-
-class HistoricRecvlineLoopbackStdio(_StdioMixin, unittest.TestCase, HistoricRecvlineLoopbackMixin):
- if stdio is None:
- skip = "Terminal requirements missing, can't run historic recvline tests over stdio"
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_scripts.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_scripts.py
deleted file mode 100644
index ae90e82..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_scripts.py
+++ /dev/null
@@ -1,82 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for the command-line interfaces to conch.
-"""
-
-try:
- import pyasn1
-except ImportError:
- pyasn1Skip = "Cannot run without PyASN1"
-else:
- pyasn1Skip = None
-
-try:
- import Crypto
-except ImportError:
- cryptoSkip = "can't run w/o PyCrypto"
-else:
- cryptoSkip = None
-
-try:
- import tty
-except ImportError:
- ttySkip = "can't run w/o tty"
-else:
- ttySkip = None
-
-try:
- import Tkinter
-except ImportError:
- tkskip = "can't run w/o Tkinter"
-else:
- try:
- Tkinter.Tk().destroy()
- except Tkinter.TclError, e:
- tkskip = "Can't test Tkinter: " + str(e)
- else:
- tkskip = None
-
-from twisted.trial.unittest import TestCase
-from twisted.scripts.test.test_scripts import ScriptTestsMixin
-from twisted.python.test.test_shellcomp import ZshScriptTestMixin
-
-
-
-class ScriptTests(TestCase, ScriptTestsMixin):
- """
- Tests for the Conch scripts.
- """
- skip = pyasn1Skip or cryptoSkip
-
-
- def test_conch(self):
- self.scriptTest("conch/conch")
- test_conch.skip = ttySkip or skip
-
-
- def test_cftp(self):
- self.scriptTest("conch/cftp")
- test_cftp.skip = ttySkip or skip
-
-
- def test_ckeygen(self):
- self.scriptTest("conch/ckeygen")
-
-
- def test_tkconch(self):
- self.scriptTest("conch/tkconch")
- test_tkconch.skip = tkskip or skip
-
-
-
-class ZshIntegrationTestCase(TestCase, ZshScriptTestMixin):
- """
- Test that zsh completion functions are generated without error
- """
- generateFor = [('conch', 'twisted.conch.scripts.conch.ClientOptions'),
- ('cftp', 'twisted.conch.scripts.cftp.ClientOptions'),
- ('ckeygen', 'twisted.conch.scripts.ckeygen.GeneralOptions'),
- ('tkconch', 'twisted.conch.scripts.tkconch.GeneralOptions'),
- ]
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_session.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_session.py
deleted file mode 100644
index 2b45c92..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_session.py
+++ /dev/null
@@ -1,1254 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for the 'session' channel implementation in twisted.conch.ssh.session.
-
-See also RFC 4254.
-"""
-
-import os, signal, sys, struct
-
-from zope.interface import implements
-
-from twisted.internet.address import IPv4Address
-from twisted.internet.error import ProcessTerminated, ProcessDone
-from twisted.python.failure import Failure
-from twisted.conch.ssh import common, session, connection
-from twisted.internet import defer, protocol, error
-from twisted.python import components, failure
-from twisted.trial import unittest
-
-
-
-class SubsystemOnlyAvatar(object):
- """
- A stub class representing an avatar that is only useful for
- getting a subsystem.
- """
-
-
- def lookupSubsystem(self, name, data):
- """
- If the other side requests the 'subsystem' subsystem, allow it by
- returning a MockProtocol to implement it. Otherwise, return
- None which is interpreted by SSHSession as a failure.
- """
- if name == 'subsystem':
- return MockProtocol()
-
-
-
-class StubAvatar:
- """
- A stub class representing the avatar representing the authenticated user.
- It implements the I{ISession} interface.
- """
-
-
- def lookupSubsystem(self, name, data):
- """
- If the user requests the TestSubsystem subsystem, connect them to a
- MockProtocol. If they request neither, then None is returned which is
- interpreted by SSHSession as a failure.
- """
- if name == 'TestSubsystem':
- self.subsystem = MockProtocol()
- self.subsystem.packetData = data
- return self.subsystem
-
-
-
-class StubSessionForStubAvatar(object):
- """
- A stub ISession implementation for our StubAvatar. The instance
- variables generally keep track of method invocations so that we can test
- that the methods were called.
-
- @ivar avatar: the L{StubAvatar} we are adapting.
- @ivar ptyRequest: if present, the terminal, window size, and modes passed
- to the getPty method.
- @ivar windowChange: if present, the window size passed to the
- windowChangned method.
- @ivar shellProtocol: if present, the L{SSHSessionProcessProtocol} passed
- to the openShell method.
- @ivar shellTransport: if present, the L{EchoTransport} connected to
- shellProtocol.
- @ivar execProtocol: if present, the L{SSHSessionProcessProtocol} passed
- to the execCommand method.
- @ivar execTransport: if present, the L{EchoTransport} connected to
- execProtocol.
- @ivar execCommandLine: if present, the command line passed to the
- execCommand method.
- @ivar gotEOF: if present, an EOF message was received.
- @ivar gotClosed: if present, a closed message was received.
- """
-
-
- implements(session.ISession)
-
-
- def __init__(self, avatar):
- """
- Store the avatar we're adapting.
- """
- self.avatar = avatar
- self.shellProtocol = None
-
-
- def getPty(self, terminal, window, modes):
- """
- If the terminal is 'bad', fail. Otherwise, store the information in
- the ptyRequest variable.
- """
- if terminal != 'bad':
- self.ptyRequest = (terminal, window, modes)
- else:
- raise RuntimeError('not getting a pty')
-
-
- def windowChanged(self, window):
- """
- If all the window sizes are 0, fail. Otherwise, store the size in the
- windowChange variable.
- """
- if window == (0, 0, 0, 0):
- raise RuntimeError('not changing the window size')
- else:
- self.windowChange = window
-
-
- def openShell(self, pp):
- """
- If we have gotten a shell request before, fail. Otherwise, store the
- process protocol in the shellProtocol variable, connect it to the
- EchoTransport and store that as shellTransport.
- """
- if self.shellProtocol is not None:
- raise RuntimeError('not getting a shell this time')
- else:
- self.shellProtocol = pp
- self.shellTransport = EchoTransport(pp)
-
-
- def execCommand(self, pp, command):
- """
- If the command is 'true', store the command, the process protocol, and
- the transport we connect to the process protocol. Otherwise, just
- store the command and raise an error.
- """
- self.execCommandLine = command
- if command == 'success':
- self.execProtocol = pp
- elif command[:6] == 'repeat':
- self.execProtocol = pp
- self.execTransport = EchoTransport(pp)
- pp.outReceived(command[7:])
- else:
- raise RuntimeError('not getting a command')
-
-
- def eofReceived(self):
- """
- Note that EOF has been received.
- """
- self.gotEOF = True
-
-
- def closed(self):
- """
- Note that close has been received.
- """
- self.gotClosed = True
-
-
-
-components.registerAdapter(StubSessionForStubAvatar, StubAvatar,
- session.ISession)
-
-
-
-
-class MockProcessProtocol(protocol.ProcessProtocol):
- """
- A mock ProcessProtocol which echoes back data sent to it and
- appends a tilde. The tilde is appended so the tests can verify that
- we received and processed the data.
-
- @ivar packetData: C{str} of data to be sent when the connection is made.
- @ivar data: a C{str} of data received.
- @ivar err: a C{str} of error data received.
- @ivar inConnectionOpen: True if the input side is open.
- @ivar outConnectionOpen: True if the output side is open.
- @ivar errConnectionOpen: True if the error side is open.
- @ivar ended: False if the protocol has not ended, a C{Failure} if the
- process has ended.
- """
- packetData = ''
-
-
- def connectionMade(self):
- """
- Set up variables.
- """
- self.data = ''
- self.err = ''
- self.inConnectionOpen = True
- self.outConnectionOpen = True
- self.errConnectionOpen = True
- self.ended = False
- if self.packetData:
- self.outReceived(self.packetData)
-
-
- def outReceived(self, data):
- """
- Data was received. Store it and echo it back with a tilde.
- """
- self.data += data
- if self.transport is not None:
- self.transport.write(data + '~')
-
-
- def errReceived(self, data):
- """
- Error data was received. Store it and echo it back backwards.
- """
- self.err += data
- self.transport.write(data[::-1])
-
-
- def inConnectionLost(self):
- """
- Close the input side.
- """
- self.inConnectionOpen = False
-
-
- def outConnectionLost(self):
- """
- Close the output side.
- """
- self.outConnectionOpen = False
-
-
- def errConnectionLost(self):
- """
- Close the error side.
- """
- self.errConnectionOpen = False
-
-
- def processEnded(self, reason):
- """
- End the process and store the reason.
- """
- self.ended = reason
-
-
-
-class EchoTransport:
- """
- A transport for a ProcessProtocol which echos data that is sent to it with
- a Window newline (CR LF) appended to it. If a null byte is in the data,
- disconnect. When we are asked to disconnect, disconnect the
- C{ProcessProtocol} with a 0 exit code.
-
- @ivar proto: the C{ProcessProtocol} connected to us.
- @ivar data: a C{str} of data written to us.
- """
-
-
- def __init__(self, processProtocol):
- """
- Initialize our instance variables.
-
- @param processProtocol: a C{ProcessProtocol} to connect to ourself.
- """
- self.proto = processProtocol
- self.closed = False
- self.data = ''
- processProtocol.makeConnection(self)
-
-
- def write(self, data):
- """
- We got some data. Give it back to our C{ProcessProtocol} with
- a newline attached. Disconnect if there's a null byte.
- """
- self.data += data
- self.proto.outReceived(data)
- self.proto.outReceived('\r\n')
- if '\x00' in data: # mimic 'exit' for the shell test
- self.loseConnection()
-
-
- def loseConnection(self):
- """
- If we're asked to disconnect (and we haven't already) shut down
- the C{ProcessProtocol} with a 0 exit code.
- """
- if self.closed:
- return
- self.closed = 1
- self.proto.inConnectionLost()
- self.proto.outConnectionLost()
- self.proto.errConnectionLost()
- self.proto.processEnded(failure.Failure(
- error.ProcessTerminated(0, None, None)))
-
-
-
-class MockProtocol(protocol.Protocol):
- """
- A sample Protocol which stores the data passed to it.
-
- @ivar packetData: a C{str} of data to be sent when the connection is made.
- @ivar data: a C{str} of the data passed to us.
- @ivar open: True if the channel is open.
- @ivar reason: if not None, the reason the protocol was closed.
- """
- packetData = ''
-
-
- def connectionMade(self):
- """
- Set up the instance variables. If we have any packetData, send it
- along.
- """
-
- self.data = ''
- self.open = True
- self.reason = None
- if self.packetData:
- self.dataReceived(self.packetData)
-
-
- def dataReceived(self, data):
- """
- Store the received data and write it back with a tilde appended.
- The tilde is appended so that the tests can verify that we processed
- the data.
- """
- self.data += data
- if self.transport is not None:
- self.transport.write(data + '~')
-
-
- def connectionLost(self, reason):
- """
- Close the protocol and store the reason.
- """
- self.open = False
- self.reason = reason
-
-
-
-class StubConnection(object):
- """
- A stub for twisted.conch.ssh.connection.SSHConnection. Record the data
- that channels send, and when they try to close the connection.
-
- @ivar data: a C{dict} mapping C{SSHChannel}s to a C{list} of C{str} of data
- they sent.
- @ivar extData: a C{dict} mapping L{SSHChannel}s to a C{list} of C{tuple} of
- (C{int}, C{str}) of extended data they sent.
- @ivar requests: a C{dict} mapping L{SSHChannel}s to a C{list} of C{tuple}
- of (C{str}, C{str}) of channel requests they made.
- @ivar eofs: a C{dict} mapping L{SSHChannel}s to C{true} if they have sent
- an EOF.
- @ivar closes: a C{dict} mapping L{SSHChannel}s to C{true} if they have sent
- a close.
- """
-
-
- def __init__(self, transport=None):
- """
- Initialize our instance variables.
- """
- self.data = {}
- self.extData = {}
- self.requests = {}
- self.eofs = {}
- self.closes = {}
- self.transport = transport
-
-
- def logPrefix(self):
- """
- Return our logging prefix.
- """
- return "MockConnection"
-
-
- def sendData(self, channel, data):
- """
- Record the sent data.
- """
- self.data.setdefault(channel, []).append(data)
-
-
- def sendExtendedData(self, channel, type, data):
- """
- Record the sent extended data.
- """
- self.extData.setdefault(channel, []).append((type, data))
-
-
- def sendRequest(self, channel, request, data, wantReply=False):
- """
- Record the sent channel request.
- """
- self.requests.setdefault(channel, []).append((request, data,
- wantReply))
- if wantReply:
- return defer.succeed(None)
-
-
- def sendEOF(self, channel):
- """
- Record the sent EOF.
- """
- self.eofs[channel] = True
-
-
- def sendClose(self, channel):
- """
- Record the sent close.
- """
- self.closes[channel] = True
-
-
-
-class StubTransport:
- """
- A stub transport which records the data written.
-
- @ivar buf: the data sent to the transport.
- @type buf: C{str}
-
- @ivar close: flags indicating if the transport has been closed.
- @type close: C{bool}
- """
-
- buf = ''
- close = False
-
-
- def getPeer(self):
- """
- Return an arbitrary L{IAddress}.
- """
- return IPv4Address('TCP', 'remotehost', 8888)
-
-
- def getHost(self):
- """
- Return an arbitrary L{IAddress}.
- """
- return IPv4Address('TCP', 'localhost', 9999)
-
-
- def write(self, data):
- """
- Record data in the buffer.
- """
- self.buf += data
-
-
- def loseConnection(self):
- """
- Note that the connection was closed.
- """
- self.close = True
-
-
-class StubTransportWithWriteErr(StubTransport):
- """
- A version of StubTransport which records the error data sent to it.
-
- @ivar err: the extended data sent to the transport.
- @type err: C{str}
- """
-
- err = ''
-
-
- def writeErr(self, data):
- """
- Record the extended data in the buffer. This was an old interface
- that allowed the Transports from ISession.openShell() or
- ISession.execCommand() to receive extended data from the client.
- """
- self.err += data
-
-
-
-class StubClient(object):
- """
- A stub class representing the client to a SSHSession.
-
- @ivar transport: A L{StubTransport} object which keeps track of the data
- passed to it.
- """
-
-
- def __init__(self):
- self.transport = StubTransportWithWriteErr()
-
-
-
-class SessionInterfaceTestCase(unittest.TestCase):
- """
- Tests for the SSHSession class interface. This interface is not ideal, but
- it is tested in order to maintain backwards compatibility.
- """
-
-
- def setUp(self):
- """
- Make an SSHSession object to test. Give the channel some window
- so that it's allowed to send packets. 500 and 100 are arbitrary
- values.
- """
- self.session = session.SSHSession(remoteWindow=500,
- remoteMaxPacket=100, conn=StubConnection(),
- avatar=StubAvatar())
-
-
- def assertSessionIsStubSession(self):
- """
- Asserts that self.session.session is an instance of
- StubSessionForStubOldAvatar.
- """
- self.assertIsInstance(self.session.session,
- StubSessionForStubAvatar)
-
-
- def test_init(self):
- """
- SSHSession initializes its buffer (buf), client, and ISession adapter.
- The avatar should not need to be adaptable to an ISession immediately.
- """
- s = session.SSHSession(avatar=object) # use object because it doesn't
- # have an adapter
- self.assertEqual(s.buf, '')
- self.assertIs(s.client, None)
- self.assertIs(s.session, None)
-
-
- def test_client_dataReceived(self):
- """
- SSHSession.dataReceived() passes data along to a client. If the data
- comes before there is a client, the data should be discarded.
- """
- self.session.dataReceived('1')
- self.session.client = StubClient()
- self.session.dataReceived('2')
- self.assertEqual(self.session.client.transport.buf, '2')
-
- def test_client_extReceived(self):
- """
- SSHSession.extReceived() passed data of type EXTENDED_DATA_STDERR along
- to the client. If the data comes before there is a client, or if the
- data is not of type EXTENDED_DATA_STDERR, it is discared.
- """
- self.session.extReceived(connection.EXTENDED_DATA_STDERR, '1')
- self.session.extReceived(255, '2') # 255 is arbitrary
- self.session.client = StubClient()
- self.session.extReceived(connection.EXTENDED_DATA_STDERR, '3')
- self.assertEqual(self.session.client.transport.err, '3')
-
-
- def test_client_extReceivedWithoutWriteErr(self):
- """
- SSHSession.extReceived() should handle the case where the transport
- on the client doesn't have a writeErr method.
- """
- client = self.session.client = StubClient()
- client.transport = StubTransport() # doesn't have writeErr
-
- # should not raise an error
- self.session.extReceived(connection.EXTENDED_DATA_STDERR, 'ignored')
-
-
-
- def test_client_closed(self):
- """
- SSHSession.closed() should tell the transport connected to the client
- that the connection was lost.
- """
- self.session.client = StubClient()
- self.session.closed()
- self.assertTrue(self.session.client.transport.close)
- self.session.client.transport.close = False
-
-
- def test_badSubsystemDoesNotCreateClient(self):
- """
- When a subsystem request fails, SSHSession.client should not be set.
- """
- ret = self.session.requestReceived(
- 'subsystem', common.NS('BadSubsystem'))
- self.assertFalse(ret)
- self.assertIs(self.session.client, None)
-
-
- def test_lookupSubsystem(self):
- """
- When a client requests a subsystem, the SSHSession object should get
- the subsystem by calling avatar.lookupSubsystem, and attach it as
- the client.
- """
- ret = self.session.requestReceived(
- 'subsystem', common.NS('TestSubsystem') + 'data')
- self.assertTrue(ret)
- self.assertIsInstance(self.session.client, protocol.ProcessProtocol)
- self.assertIs(self.session.client.transport.proto,
- self.session.avatar.subsystem)
-
-
-
- def test_lookupSubsystemDoesNotNeedISession(self):
- """
- Previously, if one only wanted to implement a subsystem, an ISession
- adapter wasn't needed because subsystems were looked up using the
- lookupSubsystem method on the avatar.
- """
- s = session.SSHSession(avatar=SubsystemOnlyAvatar(),
- conn=StubConnection())
- ret = s.request_subsystem(
- common.NS('subsystem') + 'data')
- self.assertTrue(ret)
- self.assertIsNot(s.client, None)
- self.assertIs(s.conn.closes.get(s), None)
- s.eofReceived()
- self.assertTrue(s.conn.closes.get(s))
- # these should not raise errors
- s.loseConnection()
- s.closed()
-
-
- def test_lookupSubsystem_data(self):
- """
- After having looked up a subsystem, data should be passed along to the
- client. Additionally, subsystems were passed the entire request packet
- as data, instead of just the additional data.
-
- We check for the additional tidle to verify that the data passed
- through the client.
- """
- #self.session.dataReceived('1')
- # subsystems didn't get extended data
- #self.session.extReceived(connection.EXTENDED_DATA_STDERR, '2')
-
- self.session.requestReceived('subsystem',
- common.NS('TestSubsystem') + 'data')
-
- self.assertEqual(self.session.conn.data[self.session],
- ['\x00\x00\x00\x0dTestSubsystemdata~'])
- self.session.dataReceived('more data')
- self.assertEqual(self.session.conn.data[self.session][-1],
- 'more data~')
-
-
- def test_lookupSubsystem_closeReceived(self):
- """
- SSHSession.closeReceived() should sent a close message to the remote
- side.
- """
- self.session.requestReceived('subsystem',
- common.NS('TestSubsystem') + 'data')
-
- self.session.closeReceived()
- self.assertTrue(self.session.conn.closes[self.session])
-
-
- def assertRequestRaisedRuntimeError(self):
- """
- Assert that the request we just made raised a RuntimeError (and only a
- RuntimeError).
- """
- errors = self.flushLoggedErrors(RuntimeError)
- self.assertEqual(len(errors), 1, "Multiple RuntimeErrors raised: %s" %
- '\n'.join([repr(error) for error in errors]))
- errors[0].trap(RuntimeError)
-
-
- def test_requestShell(self):
- """
- When a client requests a shell, the SSHSession object should get
- the shell by getting an ISession adapter for the avatar, then
- calling openShell() with a ProcessProtocol to attach.
- """
- # gets a shell the first time
- ret = self.session.requestReceived('shell', '')
- self.assertTrue(ret)
- self.assertSessionIsStubSession()
- self.assertIsInstance(self.session.client,
- session.SSHSessionProcessProtocol)
- self.assertIs(self.session.session.shellProtocol, self.session.client)
- # doesn't get a shell the second time
- self.assertFalse(self.session.requestReceived('shell', ''))
- self.assertRequestRaisedRuntimeError()
-
-
- def test_requestShellWithData(self):
- """
- When a client executes a shell, it should be able to give pass data
- back and forth between the local and the remote side.
- """
- ret = self.session.requestReceived('shell', '')
- self.assertTrue(ret)
- self.assertSessionIsStubSession()
- self.session.dataReceived('some data\x00')
- self.assertEqual(self.session.session.shellTransport.data,
- 'some data\x00')
- self.assertEqual(self.session.conn.data[self.session],
- ['some data\x00', '\r\n'])
- self.assertTrue(self.session.session.shellTransport.closed)
- self.assertEqual(self.session.conn.requests[self.session],
- [('exit-status', '\x00\x00\x00\x00', False)])
-
-
- def test_requestExec(self):
- """
- When a client requests a command, the SSHSession object should get
- the command by getting an ISession adapter for the avatar, then
- calling execCommand with a ProcessProtocol to attach and the
- command line.
- """
- ret = self.session.requestReceived('exec',
- common.NS('failure'))
- self.assertFalse(ret)
- self.assertRequestRaisedRuntimeError()
- self.assertIs(self.session.client, None)
-
- self.assertTrue(self.session.requestReceived('exec',
- common.NS('success')))
- self.assertSessionIsStubSession()
- self.assertIsInstance(self.session.client,
- session.SSHSessionProcessProtocol)
- self.assertIs(self.session.session.execProtocol, self.session.client)
- self.assertEqual(self.session.session.execCommandLine,
- 'success')
-
-
- def test_requestExecWithData(self):
- """
- When a client executes a command, it should be able to give pass data
- back and forth.
- """
- ret = self.session.requestReceived('exec',
- common.NS('repeat hello'))
- self.assertTrue(ret)
- self.assertSessionIsStubSession()
- self.session.dataReceived('some data')
- self.assertEqual(self.session.session.execTransport.data, 'some data')
- self.assertEqual(self.session.conn.data[self.session],
- ['hello', 'some data', '\r\n'])
- self.session.eofReceived()
- self.session.closeReceived()
- self.session.closed()
- self.assertTrue(self.session.session.execTransport.closed)
- self.assertEqual(self.session.conn.requests[self.session],
- [('exit-status', '\x00\x00\x00\x00', False)])
-
-
- def test_requestPty(self):
- """
- When a client requests a PTY, the SSHSession object should make
- the request by getting an ISession adapter for the avatar, then
- calling getPty with the terminal type, the window size, and any modes
- the client gave us.
- """
- # 'bad' terminal type fails
- ret = self.session.requestReceived(
- 'pty_req', session.packRequest_pty_req(
- 'bad', (1, 2, 3, 4), ''))
- self.assertFalse(ret)
- self.assertSessionIsStubSession()
- self.assertRequestRaisedRuntimeError()
- # 'good' terminal type succeeds
- self.assertTrue(self.session.requestReceived('pty_req',
- session.packRequest_pty_req('good', (1, 2, 3, 4), '')))
- self.assertEqual(self.session.session.ptyRequest,
- ('good', (1, 2, 3, 4), []))
-
-
- def test_requestWindowChange(self):
- """
- When the client requests to change the window size, the SSHSession
- object should make the request by getting an ISession adapter for the
- avatar, then calling windowChanged with the new window size.
- """
- ret = self.session.requestReceived(
- 'window_change',
- session.packRequest_window_change((0, 0, 0, 0)))
- self.assertFalse(ret)
- self.assertRequestRaisedRuntimeError()
- self.assertSessionIsStubSession()
- self.assertTrue(self.session.requestReceived('window_change',
- session.packRequest_window_change((1, 2, 3, 4))))
- self.assertEqual(self.session.session.windowChange,
- (1, 2, 3, 4))
-
-
- def test_eofReceived(self):
- """
- When an EOF is received and a ISession adapter is present, it should
- be notified of the EOF message.
- """
- self.session.session = session.ISession(self.session.avatar)
- self.session.eofReceived()
- self.assertTrue(self.session.session.gotEOF)
-
-
- def test_closeReceived(self):
- """
- When a close is received, the session should send a close message.
- """
- ret = self.session.closeReceived()
- self.assertIs(ret, None)
- self.assertTrue(self.session.conn.closes[self.session])
-
-
- def test_closed(self):
- """
- When a close is received and a ISession adapter is present, it should
- be notified of the close message.
- """
- self.session.session = session.ISession(self.session.avatar)
- self.session.closed()
- self.assertTrue(self.session.session.gotClosed)
-
-
-
-class SessionWithNoAvatarTestCase(unittest.TestCase):
- """
- Test for the SSHSession interface. Several of the methods (request_shell,
- request_exec, request_pty_req, request_window_change) would create a
- 'session' instance variable from the avatar if one didn't exist when they
- were called.
- """
-
-
- def setUp(self):
- self.session = session.SSHSession()
- self.session.avatar = StubAvatar()
- self.assertIs(self.session.session, None)
-
-
- def assertSessionProvidesISession(self):
- """
- self.session.session should provide I{ISession}.
- """
- self.assertTrue(session.ISession.providedBy(self.session.session),
- "ISession not provided by %r" % self.session.session)
-
-
- def test_requestShellGetsSession(self):
- """
- If an ISession adapter isn't already present, request_shell should get
- one.
- """
- self.session.requestReceived('shell', '')
- self.assertSessionProvidesISession()
-
-
- def test_requestExecGetsSession(self):
- """
- If an ISession adapter isn't already present, request_exec should get
- one.
- """
- self.session.requestReceived('exec',
- common.NS('success'))
- self.assertSessionProvidesISession()
-
-
- def test_requestPtyReqGetsSession(self):
- """
- If an ISession adapter isn't already present, request_pty_req should
- get one.
- """
- self.session.requestReceived('pty_req',
- session.packRequest_pty_req(
- 'term', (0, 0, 0, 0), ''))
- self.assertSessionProvidesISession()
-
-
- def test_requestWindowChangeGetsSession(self):
- """
- If an ISession adapter isn't already present, request_window_change
- should get one.
- """
- self.session.requestReceived(
- 'window_change',
- session.packRequest_window_change(
- (1, 1, 1, 1)))
- self.assertSessionProvidesISession()
-
-
-
-class WrappersTestCase(unittest.TestCase):
- """
- A test for the wrapProtocol and wrapProcessProtocol functions.
- """
-
- def test_wrapProtocol(self):
- """
- L{wrapProtocol}, when passed a L{Protocol} should return something that
- has write(), writeSequence(), loseConnection() methods which call the
- Protocol's dataReceived() and connectionLost() methods, respectively.
- """
- protocol = MockProtocol()
- protocol.transport = StubTransport()
- protocol.connectionMade()
- wrapped = session.wrapProtocol(protocol)
- wrapped.dataReceived('dataReceived')
- self.assertEqual(protocol.transport.buf, 'dataReceived')
- wrapped.write('data')
- wrapped.writeSequence(['1', '2'])
- wrapped.loseConnection()
- self.assertEqual(protocol.data, 'data12')
- protocol.reason.trap(error.ConnectionDone)
-
- def test_wrapProcessProtocol_Protocol(self):
- """
- L{wrapPRocessProtocol}, when passed a L{Protocol} should return
- something that follows the L{IProcessProtocol} interface, with
- connectionMade() mapping to connectionMade(), outReceived() mapping to
- dataReceived() and processEnded() mapping to connectionLost().
- """
- protocol = MockProtocol()
- protocol.transport = StubTransport()
- process_protocol = session.wrapProcessProtocol(protocol)
- process_protocol.connectionMade()
- process_protocol.outReceived('data')
- self.assertEqual(protocol.transport.buf, 'data~')
- process_protocol.processEnded(failure.Failure(
- error.ProcessTerminated(0, None, None)))
- protocol.reason.trap(error.ProcessTerminated)
-
-
-
-class TestHelpers(unittest.TestCase):
- """
- Tests for the 4 helper functions: parseRequest_* and packRequest_*.
- """
-
-
- def test_parseRequest_pty_req(self):
- """
- The payload of a pty-req message is::
- string terminal
- uint32 columns
- uint32 rows
- uint32 x pixels
- uint32 y pixels
- string modes
-
- Modes are::
- byte mode number
- uint32 mode value
- """
- self.assertEqual(session.parseRequest_pty_req(common.NS('xterm') +
- struct.pack('>4L',
- 1, 2, 3, 4)
- + common.NS(
- struct.pack('>BL', 5, 6))),
- ('xterm', (2, 1, 3, 4), [(5, 6)]))
-
-
- def test_packRequest_pty_req_old(self):
- """
- See test_parseRequest_pty_req for the payload format.
- """
- packed = session.packRequest_pty_req('xterm', (2, 1, 3, 4),
- '\x05\x00\x00\x00\x06')
-
- self.assertEqual(packed,
- common.NS('xterm') + struct.pack('>4L', 1, 2, 3, 4) +
- common.NS(struct.pack('>BL', 5, 6)))
-
-
- def test_packRequest_pty_req(self):
- """
- See test_parseRequest_pty_req for the payload format.
- """
- packed = session.packRequest_pty_req('xterm', (2, 1, 3, 4),
- '\x05\x00\x00\x00\x06')
- self.assertEqual(packed,
- common.NS('xterm') + struct.pack('>4L', 1, 2, 3, 4) +
- common.NS(struct.pack('>BL', 5, 6)))
-
-
- def test_parseRequest_window_change(self):
- """
- The payload of a window_change request is::
- uint32 columns
- uint32 rows
- uint32 x pixels
- uint32 y pixels
-
- parseRequest_window_change() returns (rows, columns, x pixels,
- y pixels).
- """
- self.assertEqual(session.parseRequest_window_change(
- struct.pack('>4L', 1, 2, 3, 4)), (2, 1, 3, 4))
-
-
- def test_packRequest_window_change(self):
- """
- See test_parseRequest_window_change for the payload format.
- """
- self.assertEqual(session.packRequest_window_change((2, 1, 3, 4)),
- struct.pack('>4L', 1, 2, 3, 4))
-
-
-
-class SSHSessionProcessProtocolTestCase(unittest.TestCase):
- """
- Tests for L{SSHSessionProcessProtocol}.
- """
-
- def setUp(self):
- self.transport = StubTransport()
- self.session = session.SSHSession(
- conn=StubConnection(self.transport), remoteWindow=500,
- remoteMaxPacket=100)
- self.pp = session.SSHSessionProcessProtocol(self.session)
- self.pp.makeConnection(self.transport)
-
-
- def assertSessionClosed(self):
- """
- Assert that C{self.session} is closed.
- """
- self.assertTrue(self.session.conn.closes[self.session])
-
-
- def assertRequestsEqual(self, expectedRequests):
- """
- Assert that C{self.session} has sent the C{expectedRequests}.
- """
- self.assertEqual(
- self.session.conn.requests[self.session],
- expectedRequests)
-
-
- def test_init(self):
- """
- SSHSessionProcessProtocol should set self.session to the session passed
- to the __init__ method.
- """
- self.assertEqual(self.pp.session, self.session)
-
-
- def test_getHost(self):
- """
- SSHSessionProcessProtocol.getHost() just delegates to its
- session.conn.transport.getHost().
- """
- self.assertEqual(
- self.session.conn.transport.getHost(), self.pp.getHost())
-
-
- def test_getPeer(self):
- """
- SSHSessionProcessProtocol.getPeer() just delegates to its
- session.conn.transport.getPeer().
- """
- self.assertEqual(
- self.session.conn.transport.getPeer(), self.pp.getPeer())
-
-
- def test_connectionMade(self):
- """
- SSHSessionProcessProtocol.connectionMade() should check if there's a
- 'buf' attribute on its session and write it to the transport if so.
- """
- self.session.buf = 'buffer'
- self.pp.connectionMade()
- self.assertEqual(self.transport.buf, 'buffer')
-
-
- def test_getSignalName(self):
- """
- _getSignalName should return the name of a signal when given the
- signal number.
- """
- for signalName in session.SUPPORTED_SIGNALS:
- signalName = 'SIG' + signalName
- signalValue = getattr(signal, signalName)
- sshName = self.pp._getSignalName(signalValue)
- self.assertEqual(sshName, signalName,
- "%i: %s != %s" % (signalValue, sshName,
- signalName))
-
-
- def test_getSignalNameWithLocalSignal(self):
- """
- If there are signals in the signal module which aren't in the SSH RFC,
- we map their name to [signal name]@[platform].
- """
- signal.SIGTwistedTest = signal.NSIG + 1 # value can't exist normally
- # Force reinitialization of signals
- self.pp._signalValuesToNames = None
- self.assertEqual(self.pp._getSignalName(signal.SIGTwistedTest),
- 'SIGTwistedTest@' + sys.platform)
-
-
- if getattr(signal, 'SIGALRM', None) is None:
- test_getSignalName.skip = test_getSignalNameWithLocalSignal.skip = \
- "Not all signals available"
-
-
- def test_outReceived(self):
- """
- When data is passed to the outReceived method, it should be sent to
- the session's write method.
- """
- self.pp.outReceived('test data')
- self.assertEqual(self.session.conn.data[self.session],
- ['test data'])
-
-
- def test_write(self):
- """
- When data is passed to the write method, it should be sent to the
- session channel's write method.
- """
- self.pp.write('test data')
- self.assertEqual(self.session.conn.data[self.session],
- ['test data'])
-
- def test_writeSequence(self):
- """
- When a sequence is passed to the writeSequence method, it should be
- joined together and sent to the session channel's write method.
- """
- self.pp.writeSequence(['test ', 'data'])
- self.assertEqual(self.session.conn.data[self.session],
- ['test data'])
-
-
- def test_errReceived(self):
- """
- When data is passed to the errReceived method, it should be sent to
- the session's writeExtended method.
- """
- self.pp.errReceived('test data')
- self.assertEqual(self.session.conn.extData[self.session],
- [(1, 'test data')])
-
-
- def test_outConnectionLost(self):
- """
- When outConnectionLost and errConnectionLost are both called, we should
- send an EOF message.
- """
- self.pp.outConnectionLost()
- self.assertFalse(self.session in self.session.conn.eofs)
- self.pp.errConnectionLost()
- self.assertTrue(self.session.conn.eofs[self.session])
-
-
- def test_errConnectionLost(self):
- """
- Make sure reverse ordering of events in test_outConnectionLost also
- sends EOF.
- """
- self.pp.errConnectionLost()
- self.assertFalse(self.session in self.session.conn.eofs)
- self.pp.outConnectionLost()
- self.assertTrue(self.session.conn.eofs[self.session])
-
-
- def test_loseConnection(self):
- """
- When loseConnection() is called, it should call loseConnection
- on the session channel.
- """
- self.pp.loseConnection()
- self.assertTrue(self.session.conn.closes[self.session])
-
-
- def test_connectionLost(self):
- """
- When connectionLost() is called, it should call loseConnection()
- on the session channel.
- """
- self.pp.connectionLost(failure.Failure(
- ProcessDone(0)))
-
-
- def test_processEndedWithExitCode(self):
- """
- When processEnded is called, if there is an exit code in the reason
- it should be sent in an exit-status method. The connection should be
- closed.
- """
- self.pp.processEnded(Failure(ProcessDone(None)))
- self.assertRequestsEqual(
- [('exit-status', struct.pack('>I', 0) , False)])
- self.assertSessionClosed()
-
-
- def test_processEndedWithExitSignalCoreDump(self):
- """
- When processEnded is called, if there is an exit signal in the reason
- it should be sent in an exit-signal message. The connection should be
- closed.
- """
- self.pp.processEnded(
- Failure(ProcessTerminated(1,
- signal.SIGTERM, 1 << 7))) # 7th bit means core dumped
- self.assertRequestsEqual(
- [('exit-signal',
- common.NS('TERM') # signal name
- + '\x01' # core dumped is true
- + common.NS('') # error message
- + common.NS(''), # language tag
- False)])
- self.assertSessionClosed()
-
-
- def test_processEndedWithExitSignalNoCoreDump(self):
- """
- When processEnded is called, if there is an exit signal in the
- reason it should be sent in an exit-signal message. If no
- core was dumped, don't set the core-dump bit.
- """
- self.pp.processEnded(
- Failure(ProcessTerminated(1, signal.SIGTERM, 0)))
- # see comments in test_processEndedWithExitSignalCoreDump for the
- # meaning of the parts in the request
- self.assertRequestsEqual(
- [('exit-signal', common.NS('TERM') + '\x00' + common.NS('') +
- common.NS(''), False)])
- self.assertSessionClosed()
-
-
- if getattr(os, 'WCOREDUMP', None) is None:
- skipMsg = "can't run this w/o os.WCOREDUMP"
- test_processEndedWithExitSignalCoreDump.skip = skipMsg
- test_processEndedWithExitSignalNoCoreDump.skip = skipMsg
-
-
-
-class SSHSessionClientTestCase(unittest.TestCase):
- """
- SSHSessionClient is an obsolete class used to connect standard IO to
- an SSHSession.
- """
-
-
- def test_dataReceived(self):
- """
- When data is received, it should be sent to the transport.
- """
- client = session.SSHSessionClient()
- client.transport = StubTransport()
- client.dataReceived('test data')
- self.assertEqual(client.transport.buf, 'test data')
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_ssh.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_ssh.py
deleted file mode 100644
index af2a474..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_ssh.py
+++ /dev/null
@@ -1,995 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.ssh}.
-"""
-
-import struct
-
-try:
- import Crypto.Cipher.DES3
-except ImportError:
- Crypto = None
-
-try:
- import pyasn1
-except ImportError:
- pyasn1 = None
-
-from twisted.conch.ssh import common, session, forwarding
-from twisted.conch import avatar, error
-from twisted.conch.test.keydata import publicRSA_openssh, privateRSA_openssh
-from twisted.conch.test.keydata import publicDSA_openssh, privateDSA_openssh
-from twisted.cred import portal
-from twisted.cred.error import UnauthorizedLogin
-from twisted.internet import defer, protocol, reactor
-from twisted.internet.error import ProcessTerminated
-from twisted.python import failure, log
-from twisted.trial import unittest
-
-from twisted.conch.test.test_recvline import LoopbackRelay
-
-
-
-class ConchTestRealm(object):
- """
- A realm which expects a particular avatarId to log in once and creates a
- L{ConchTestAvatar} for that request.
-
- @ivar expectedAvatarID: The only avatarID that this realm will produce an
- avatar for.
-
- @ivar avatar: A reference to the avatar after it is requested.
- """
- avatar = None
-
- def __init__(self, expectedAvatarID):
- self.expectedAvatarID = expectedAvatarID
-
-
- def requestAvatar(self, avatarID, mind, *interfaces):
- """
- Return a new L{ConchTestAvatar} if the avatarID matches the expected one
- and this is the first avatar request.
- """
- if avatarID == self.expectedAvatarID:
- if self.avatar is not None:
- raise UnauthorizedLogin("Only one login allowed")
- self.avatar = ConchTestAvatar()
- return interfaces[0], self.avatar, self.avatar.logout
- raise UnauthorizedLogin(
- "Only %r may log in, not %r" % (self.expectedAvatarID, avatarID))
-
-
-
-class ConchTestAvatar(avatar.ConchUser):
- """
- An avatar against which various SSH features can be tested.
-
- @ivar loggedOut: A flag indicating whether the avatar logout method has been
- called.
- """
- loggedOut = False
-
- def __init__(self):
- avatar.ConchUser.__init__(self)
- self.listeners = {}
- self.globalRequests = {}
- self.channelLookup.update({'session': session.SSHSession,
- 'direct-tcpip':forwarding.openConnectForwardingClient})
- self.subsystemLookup.update({'crazy': CrazySubsystem})
-
-
- def global_foo(self, data):
- self.globalRequests['foo'] = data
- return 1
-
-
- def global_foo_2(self, data):
- self.globalRequests['foo_2'] = data
- return 1, 'data'
-
-
- def global_tcpip_forward(self, data):
- host, port = forwarding.unpackGlobal_tcpip_forward(data)
- try:
- listener = reactor.listenTCP(
- port, forwarding.SSHListenForwardingFactory(
- self.conn, (host, port),
- forwarding.SSHListenServerForwardingChannel),
- interface=host)
- except:
- log.err(None, "something went wrong with remote->local forwarding")
- return 0
- else:
- self.listeners[(host, port)] = listener
- return 1
-
-
- def global_cancel_tcpip_forward(self, data):
- host, port = forwarding.unpackGlobal_tcpip_forward(data)
- listener = self.listeners.get((host, port), None)
- if not listener:
- return 0
- del self.listeners[(host, port)]
- listener.stopListening()
- return 1
-
-
- def logout(self):
- self.loggedOut = True
- for listener in self.listeners.values():
- log.msg('stopListening %s' % listener)
- listener.stopListening()
-
-
-
-class ConchSessionForTestAvatar(object):
- """
- An ISession adapter for ConchTestAvatar.
- """
- def __init__(self, avatar):
- """
- Initialize the session and create a reference to it on the avatar for
- later inspection.
- """
- self.avatar = avatar
- self.avatar._testSession = self
- self.cmd = None
- self.proto = None
- self.ptyReq = False
- self.eof = 0
- self.onClose = defer.Deferred()
-
-
- def getPty(self, term, windowSize, attrs):
- log.msg('pty req')
- self._terminalType = term
- self._windowSize = windowSize
- self.ptyReq = True
-
-
- def openShell(self, proto):
- log.msg('opening shell')
- self.proto = proto
- EchoTransport(proto)
- self.cmd = 'shell'
-
-
- def execCommand(self, proto, cmd):
- self.cmd = cmd
- self.proto = proto
- f = cmd.split()[0]
- if f == 'false':
- t = FalseTransport(proto)
- # Avoid disconnecting this immediately. If the channel is closed
- # before execCommand even returns the caller gets confused.
- reactor.callLater(0, t.loseConnection)
- elif f == 'echo':
- t = EchoTransport(proto)
- t.write(cmd[5:])
- t.loseConnection()
- elif f == 'secho':
- t = SuperEchoTransport(proto)
- t.write(cmd[6:])
- t.loseConnection()
- elif f == 'eecho':
- t = ErrEchoTransport(proto)
- t.write(cmd[6:])
- t.loseConnection()
- else:
- raise error.ConchError('bad exec')
- self.avatar.conn.transport.expectedLoseConnection = 1
-
-
- def eofReceived(self):
- self.eof = 1
-
-
- def closed(self):
- log.msg('closed cmd "%s"' % self.cmd)
- self.remoteWindowLeftAtClose = self.proto.session.remoteWindowLeft
- self.onClose.callback(None)
-
-from twisted.python import components
-components.registerAdapter(ConchSessionForTestAvatar, ConchTestAvatar, session.ISession)
-
-class CrazySubsystem(protocol.Protocol):
-
- def __init__(self, *args, **kw):
- pass
-
- def connectionMade(self):
- """
- good ... good
- """
-
-
-
-class FalseTransport:
- """
- False transport should act like a /bin/false execution, i.e. just exit with
- nonzero status, writing nothing to the terminal.
-
- @ivar proto: The protocol associated with this transport.
- @ivar closed: A flag tracking whether C{loseConnection} has been called yet.
- """
-
- def __init__(self, p):
- """
- @type p L{twisted.conch.ssh.session.SSHSessionProcessProtocol} instance
- """
- self.proto = p
- p.makeConnection(self)
- self.closed = 0
-
-
- def loseConnection(self):
- """
- Disconnect the protocol associated with this transport.
- """
- if self.closed:
- return
- self.closed = 1
- self.proto.inConnectionLost()
- self.proto.outConnectionLost()
- self.proto.errConnectionLost()
- self.proto.processEnded(failure.Failure(ProcessTerminated(255, None, None)))
-
-
-
-class EchoTransport:
-
- def __init__(self, p):
- self.proto = p
- p.makeConnection(self)
- self.closed = 0
-
- def write(self, data):
- log.msg(repr(data))
- self.proto.outReceived(data)
- self.proto.outReceived('\r\n')
- if '\x00' in data: # mimic 'exit' for the shell test
- self.loseConnection()
-
- def loseConnection(self):
- if self.closed: return
- self.closed = 1
- self.proto.inConnectionLost()
- self.proto.outConnectionLost()
- self.proto.errConnectionLost()
- self.proto.processEnded(failure.Failure(ProcessTerminated(0, None, None)))
-
-class ErrEchoTransport:
-
- def __init__(self, p):
- self.proto = p
- p.makeConnection(self)
- self.closed = 0
-
- def write(self, data):
- self.proto.errReceived(data)
- self.proto.errReceived('\r\n')
-
- def loseConnection(self):
- if self.closed: return
- self.closed = 1
- self.proto.inConnectionLost()
- self.proto.outConnectionLost()
- self.proto.errConnectionLost()
- self.proto.processEnded(failure.Failure(ProcessTerminated(0, None, None)))
-
-class SuperEchoTransport:
-
- def __init__(self, p):
- self.proto = p
- p.makeConnection(self)
- self.closed = 0
-
- def write(self, data):
- self.proto.outReceived(data)
- self.proto.outReceived('\r\n')
- self.proto.errReceived(data)
- self.proto.errReceived('\r\n')
-
- def loseConnection(self):
- if self.closed: return
- self.closed = 1
- self.proto.inConnectionLost()
- self.proto.outConnectionLost()
- self.proto.errConnectionLost()
- self.proto.processEnded(failure.Failure(ProcessTerminated(0, None, None)))
-
-
-if Crypto is not None and pyasn1 is not None:
- from twisted.conch import checkers
- from twisted.conch.ssh import channel, connection, factory, keys
- from twisted.conch.ssh import transport, userauth
-
- class UtilityTestCase(unittest.TestCase):
- def testCounter(self):
- c = transport._Counter('\x00\x00', 2)
- for i in xrange(256 * 256):
- self.assertEqual(c(), struct.pack('!H', (i + 1) % (2 ** 16)))
- # It should wrap around, too.
- for i in xrange(256 * 256):
- self.assertEqual(c(), struct.pack('!H', (i + 1) % (2 ** 16)))
-
-
- class ConchTestPublicKeyChecker(checkers.SSHPublicKeyDatabase):
- def checkKey(self, credentials):
- blob = keys.Key.fromString(publicDSA_openssh).blob()
- if credentials.username == 'testuser' and credentials.blob == blob:
- return True
- return False
-
-
- class ConchTestPasswordChecker:
- credentialInterfaces = checkers.IUsernamePassword,
-
- def requestAvatarId(self, credentials):
- if credentials.username == 'testuser' and credentials.password == 'testpass':
- return defer.succeed(credentials.username)
- return defer.fail(Exception("Bad credentials"))
-
-
- class ConchTestSSHChecker(checkers.SSHProtocolChecker):
-
- def areDone(self, avatarId):
- if avatarId != 'testuser' or len(self.successfulCredentials[avatarId]) < 2:
- return False
- return True
-
- class ConchTestServerFactory(factory.SSHFactory):
- noisy = 0
-
- services = {
- 'ssh-userauth':userauth.SSHUserAuthServer,
- 'ssh-connection':connection.SSHConnection
- }
-
- def buildProtocol(self, addr):
- proto = ConchTestServer()
- proto.supportedPublicKeys = self.privateKeys.keys()
- proto.factory = self
-
- if hasattr(self, 'expectedLoseConnection'):
- proto.expectedLoseConnection = self.expectedLoseConnection
-
- self.proto = proto
- return proto
-
- def getPublicKeys(self):
- return {
- 'ssh-rsa': keys.Key.fromString(publicRSA_openssh),
- 'ssh-dss': keys.Key.fromString(publicDSA_openssh)
- }
-
- def getPrivateKeys(self):
- return {
- 'ssh-rsa': keys.Key.fromString(privateRSA_openssh),
- 'ssh-dss': keys.Key.fromString(privateDSA_openssh)
- }
-
- def getPrimes(self):
- return {
- 2048:[(transport.DH_GENERATOR, transport.DH_PRIME)]
- }
-
- def getService(self, trans, name):
- return factory.SSHFactory.getService(self, trans, name)
-
- class ConchTestBase:
-
- done = 0
-
- def connectionLost(self, reason):
- if self.done:
- return
- if not hasattr(self,'expectedLoseConnection'):
- unittest.fail('unexpectedly lost connection %s\n%s' % (self, reason))
- self.done = 1
-
- def receiveError(self, reasonCode, desc):
- self.expectedLoseConnection = 1
- # Some versions of OpenSSH (for example, OpenSSH_5.3p1) will
- # send a DISCONNECT_BY_APPLICATION error before closing the
- # connection. Other, older versions (for example,
- # OpenSSH_5.1p1), won't. So accept this particular error here,
- # but no others.
- if reasonCode != transport.DISCONNECT_BY_APPLICATION:
- log.err(
- Exception(
- 'got disconnect for %s: reason %s, desc: %s' % (
- self, reasonCode, desc)))
- self.loseConnection()
-
- def receiveUnimplemented(self, seqID):
- unittest.fail('got unimplemented: seqid %s' % seqID)
- self.expectedLoseConnection = 1
- self.loseConnection()
-
- class ConchTestServer(ConchTestBase, transport.SSHServerTransport):
-
- def connectionLost(self, reason):
- ConchTestBase.connectionLost(self, reason)
- transport.SSHServerTransport.connectionLost(self, reason)
-
-
- class ConchTestClient(ConchTestBase, transport.SSHClientTransport):
- """
- @ivar _channelFactory: A callable which accepts an SSH connection and
- returns a channel which will be attached to a new channel on that
- connection.
- """
- def __init__(self, channelFactory):
- self._channelFactory = channelFactory
-
- def connectionLost(self, reason):
- ConchTestBase.connectionLost(self, reason)
- transport.SSHClientTransport.connectionLost(self, reason)
-
- def verifyHostKey(self, key, fp):
- keyMatch = key == keys.Key.fromString(publicRSA_openssh).blob()
- fingerprintMatch = (
- fp == '3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af')
- if keyMatch and fingerprintMatch:
- return defer.succeed(1)
- return defer.fail(Exception("Key or fingerprint mismatch"))
-
- def connectionSecure(self):
- self.requestService(ConchTestClientAuth('testuser',
- ConchTestClientConnection(self._channelFactory)))
-
-
- class ConchTestClientAuth(userauth.SSHUserAuthClient):
-
- hasTriedNone = 0 # have we tried the 'none' auth yet?
- canSucceedPublicKey = 0 # can we succed with this yet?
- canSucceedPassword = 0
-
- def ssh_USERAUTH_SUCCESS(self, packet):
- if not self.canSucceedPassword and self.canSucceedPublicKey:
- unittest.fail('got USERAUTH_SUCESS before password and publickey')
- userauth.SSHUserAuthClient.ssh_USERAUTH_SUCCESS(self, packet)
-
- def getPassword(self):
- self.canSucceedPassword = 1
- return defer.succeed('testpass')
-
- def getPrivateKey(self):
- self.canSucceedPublicKey = 1
- return defer.succeed(keys.Key.fromString(privateDSA_openssh))
-
- def getPublicKey(self):
- return keys.Key.fromString(publicDSA_openssh)
-
-
- class ConchTestClientConnection(connection.SSHConnection):
- """
- @ivar _completed: A L{Deferred} which will be fired when the number of
- results collected reaches C{totalResults}.
- """
- name = 'ssh-connection'
- results = 0
- totalResults = 8
-
- def __init__(self, channelFactory):
- connection.SSHConnection.__init__(self)
- self._channelFactory = channelFactory
-
- def serviceStarted(self):
- self.openChannel(self._channelFactory(conn=self))
-
-
- class SSHTestChannel(channel.SSHChannel):
-
- def __init__(self, name, opened, *args, **kwargs):
- self.name = name
- self._opened = opened
- self.received = []
- self.receivedExt = []
- self.onClose = defer.Deferred()
- channel.SSHChannel.__init__(self, *args, **kwargs)
-
-
- def openFailed(self, reason):
- self._opened.errback(reason)
-
-
- def channelOpen(self, ignore):
- self._opened.callback(self)
-
-
- def dataReceived(self, data):
- self.received.append(data)
-
-
- def extReceived(self, dataType, data):
- if dataType == connection.EXTENDED_DATA_STDERR:
- self.receivedExt.append(data)
- else:
- log.msg("Unrecognized extended data: %r" % (dataType,))
-
-
- def request_exit_status(self, status):
- [self.status] = struct.unpack('>L', status)
-
-
- def eofReceived(self):
- self.eofCalled = True
-
-
- def closed(self):
- self.onClose.callback(None)
-
-
-
-class SSHProtocolTestCase(unittest.TestCase):
- """
- Tests for communication between L{SSHServerTransport} and
- L{SSHClientTransport}.
- """
-
- if not Crypto:
- skip = "can't run w/o PyCrypto"
-
- if not pyasn1:
- skip = "Cannot run without PyASN1"
-
- def _ourServerOurClientTest(self, name='session', **kwargs):
- """
- Create a connected SSH client and server protocol pair and return a
- L{Deferred} which fires with an L{SSHTestChannel} instance connected to
- a channel on that SSH connection.
- """
- result = defer.Deferred()
- self.realm = ConchTestRealm('testuser')
- p = portal.Portal(self.realm)
- sshpc = ConchTestSSHChecker()
- sshpc.registerChecker(ConchTestPasswordChecker())
- sshpc.registerChecker(ConchTestPublicKeyChecker())
- p.registerChecker(sshpc)
- fac = ConchTestServerFactory()
- fac.portal = p
- fac.startFactory()
- self.server = fac.buildProtocol(None)
- self.clientTransport = LoopbackRelay(self.server)
- self.client = ConchTestClient(
- lambda conn: SSHTestChannel(name, result, conn=conn, **kwargs))
-
- self.serverTransport = LoopbackRelay(self.client)
-
- self.server.makeConnection(self.serverTransport)
- self.client.makeConnection(self.clientTransport)
- return result
-
-
- def test_subsystemsAndGlobalRequests(self):
- """
- Run the Conch server against the Conch client. Set up several different
- channels which exercise different behaviors and wait for them to
- complete. Verify that the channels with errors log them.
- """
- channel = self._ourServerOurClientTest()
-
- def cbSubsystem(channel):
- self.channel = channel
- return self.assertFailure(
- channel.conn.sendRequest(
- channel, 'subsystem', common.NS('not-crazy'), 1),
- Exception)
- channel.addCallback(cbSubsystem)
-
- def cbNotCrazyFailed(ignored):
- channel = self.channel
- return channel.conn.sendRequest(
- channel, 'subsystem', common.NS('crazy'), 1)
- channel.addCallback(cbNotCrazyFailed)
-
- def cbGlobalRequests(ignored):
- channel = self.channel
- d1 = channel.conn.sendGlobalRequest('foo', 'bar', 1)
-
- d2 = channel.conn.sendGlobalRequest('foo-2', 'bar2', 1)
- d2.addCallback(self.assertEqual, 'data')
-
- d3 = self.assertFailure(
- channel.conn.sendGlobalRequest('bar', 'foo', 1),
- Exception)
-
- return defer.gatherResults([d1, d2, d3])
- channel.addCallback(cbGlobalRequests)
-
- def disconnect(ignored):
- self.assertEqual(
- self.realm.avatar.globalRequests,
- {"foo": "bar", "foo_2": "bar2"})
- channel = self.channel
- channel.conn.transport.expectedLoseConnection = True
- channel.conn.serviceStopped()
- channel.loseConnection()
- channel.addCallback(disconnect)
-
- return channel
-
-
- def test_shell(self):
- """
- L{SSHChannel.sendRequest} can open a shell with a I{pty-req} request,
- specifying a terminal type and window size.
- """
- channel = self._ourServerOurClientTest()
-
- data = session.packRequest_pty_req('conch-test-term', (24, 80, 0, 0), '')
- def cbChannel(channel):
- self.channel = channel
- return channel.conn.sendRequest(channel, 'pty-req', data, 1)
- channel.addCallback(cbChannel)
-
- def cbPty(ignored):
- # The server-side object corresponding to our client side channel.
- session = self.realm.avatar.conn.channels[0].session
- self.assertIs(session.avatar, self.realm.avatar)
- self.assertEqual(session._terminalType, 'conch-test-term')
- self.assertEqual(session._windowSize, (24, 80, 0, 0))
- self.assertTrue(session.ptyReq)
- channel = self.channel
- return channel.conn.sendRequest(channel, 'shell', '', 1)
- channel.addCallback(cbPty)
-
- def cbShell(ignored):
- self.channel.write('testing the shell!\x00')
- self.channel.conn.sendEOF(self.channel)
- return defer.gatherResults([
- self.channel.onClose,
- self.realm.avatar._testSession.onClose])
- channel.addCallback(cbShell)
-
- def cbExited(ignored):
- if self.channel.status != 0:
- log.msg(
- 'shell exit status was not 0: %i' % (self.channel.status,))
- self.assertEqual(
- "".join(self.channel.received),
- 'testing the shell!\x00\r\n')
- self.assertTrue(self.channel.eofCalled)
- self.assertTrue(
- self.realm.avatar._testSession.eof)
- channel.addCallback(cbExited)
- return channel
-
-
- def test_failedExec(self):
- """
- If L{SSHChannel.sendRequest} issues an exec which the server responds to
- with an error, the L{Deferred} it returns fires its errback.
- """
- channel = self._ourServerOurClientTest()
-
- def cbChannel(channel):
- self.channel = channel
- return self.assertFailure(
- channel.conn.sendRequest(
- channel, 'exec', common.NS('jumboliah'), 1),
- Exception)
- channel.addCallback(cbChannel)
-
- def cbFailed(ignored):
- # The server logs this exception when it cannot perform the
- # requested exec.
- errors = self.flushLoggedErrors(error.ConchError)
- self.assertEqual(errors[0].value.args, ('bad exec', None))
- channel.addCallback(cbFailed)
- return channel
-
-
- def test_falseChannel(self):
- """
- When the process started by a L{SSHChannel.sendRequest} exec request
- exits, the exit status is reported to the channel.
- """
- channel = self._ourServerOurClientTest()
-
- def cbChannel(channel):
- self.channel = channel
- return channel.conn.sendRequest(
- channel, 'exec', common.NS('false'), 1)
- channel.addCallback(cbChannel)
-
- def cbExec(ignored):
- return self.channel.onClose
- channel.addCallback(cbExec)
-
- def cbClosed(ignored):
- # No data is expected
- self.assertEqual(self.channel.received, [])
- self.assertNotEqual(self.channel.status, 0)
- channel.addCallback(cbClosed)
- return channel
-
-
- def test_errorChannel(self):
- """
- Bytes sent over the extended channel for stderr data are delivered to
- the channel's C{extReceived} method.
- """
- channel = self._ourServerOurClientTest(localWindow=4, localMaxPacket=5)
-
- def cbChannel(channel):
- self.channel = channel
- return channel.conn.sendRequest(
- channel, 'exec', common.NS('eecho hello'), 1)
- channel.addCallback(cbChannel)
-
- def cbExec(ignored):
- return defer.gatherResults([
- self.channel.onClose,
- self.realm.avatar._testSession.onClose])
- channel.addCallback(cbExec)
-
- def cbClosed(ignored):
- self.assertEqual(self.channel.received, [])
- self.assertEqual("".join(self.channel.receivedExt), "hello\r\n")
- self.assertEqual(self.channel.status, 0)
- self.assertTrue(self.channel.eofCalled)
- self.assertEqual(self.channel.localWindowLeft, 4)
- self.assertEqual(
- self.channel.localWindowLeft,
- self.realm.avatar._testSession.remoteWindowLeftAtClose)
- channel.addCallback(cbClosed)
- return channel
-
-
- def test_unknownChannel(self):
- """
- When an attempt is made to open an unknown channel type, the L{Deferred}
- returned by L{SSHChannel.sendRequest} fires its errback.
- """
- d = self.assertFailure(
- self._ourServerOurClientTest('crazy-unknown-channel'), Exception)
- def cbFailed(ignored):
- errors = self.flushLoggedErrors(error.ConchError)
- self.assertEqual(errors[0].value.args, (3, 'unknown channel'))
- self.assertEqual(len(errors), 1)
- d.addCallback(cbFailed)
- return d
-
-
- def test_maxPacket(self):
- """
- An L{SSHChannel} can be configured with a maximum packet size to
- receive.
- """
- # localWindow needs to be at least 11 otherwise the assertion about it
- # in cbClosed is invalid.
- channel = self._ourServerOurClientTest(
- localWindow=11, localMaxPacket=1)
-
- def cbChannel(channel):
- self.channel = channel
- return channel.conn.sendRequest(
- channel, 'exec', common.NS('secho hello'), 1)
- channel.addCallback(cbChannel)
-
- def cbExec(ignored):
- return self.channel.onClose
- channel.addCallback(cbExec)
-
- def cbClosed(ignored):
- self.assertEqual(self.channel.status, 0)
- self.assertEqual("".join(self.channel.received), "hello\r\n")
- self.assertEqual("".join(self.channel.receivedExt), "hello\r\n")
- self.assertEqual(self.channel.localWindowLeft, 11)
- self.assertTrue(self.channel.eofCalled)
- channel.addCallback(cbClosed)
- return channel
-
-
- def test_echo(self):
- """
- Normal standard out bytes are sent to the channel's C{dataReceived}
- method.
- """
- channel = self._ourServerOurClientTest(localWindow=4, localMaxPacket=5)
-
- def cbChannel(channel):
- self.channel = channel
- return channel.conn.sendRequest(
- channel, 'exec', common.NS('echo hello'), 1)
- channel.addCallback(cbChannel)
-
- def cbEcho(ignored):
- return defer.gatherResults([
- self.channel.onClose,
- self.realm.avatar._testSession.onClose])
- channel.addCallback(cbEcho)
-
- def cbClosed(ignored):
- self.assertEqual(self.channel.status, 0)
- self.assertEqual("".join(self.channel.received), "hello\r\n")
- self.assertEqual(self.channel.localWindowLeft, 4)
- self.assertTrue(self.channel.eofCalled)
- self.assertEqual(
- self.channel.localWindowLeft,
- self.realm.avatar._testSession.remoteWindowLeftAtClose)
- channel.addCallback(cbClosed)
- return channel
-
-
-
-class TestSSHFactory(unittest.TestCase):
-
- if not Crypto:
- skip = "can't run w/o PyCrypto"
-
- if not pyasn1:
- skip = "Cannot run without PyASN1"
-
- def makeSSHFactory(self, primes=None):
- sshFactory = factory.SSHFactory()
- gpk = lambda: {'ssh-rsa' : keys.Key(None)}
- sshFactory.getPrimes = lambda: primes
- sshFactory.getPublicKeys = sshFactory.getPrivateKeys = gpk
- sshFactory.startFactory()
- return sshFactory
-
-
- def test_buildProtocol(self):
- """
- By default, buildProtocol() constructs an instance of
- SSHServerTransport.
- """
- factory = self.makeSSHFactory()
- protocol = factory.buildProtocol(None)
- self.assertIsInstance(protocol, transport.SSHServerTransport)
-
-
- def test_buildProtocolRespectsProtocol(self):
- """
- buildProtocol() calls 'self.protocol()' to construct a protocol
- instance.
- """
- calls = []
- def makeProtocol(*args):
- calls.append(args)
- return transport.SSHServerTransport()
- factory = self.makeSSHFactory()
- factory.protocol = makeProtocol
- factory.buildProtocol(None)
- self.assertEqual([()], calls)
-
-
- def test_multipleFactories(self):
- f1 = self.makeSSHFactory(primes=None)
- f2 = self.makeSSHFactory(primes={1:(2,3)})
- p1 = f1.buildProtocol(None)
- p2 = f2.buildProtocol(None)
- self.assertNotIn(
- 'diffie-hellman-group-exchange-sha1', p1.supportedKeyExchanges)
- self.assertIn(
- 'diffie-hellman-group-exchange-sha1', p2.supportedKeyExchanges)
-
-
-
-class MPTestCase(unittest.TestCase):
- """
- Tests for L{common.getMP}.
-
- @cvar getMP: a method providing a MP parser.
- @type getMP: C{callable}
- """
- getMP = staticmethod(common.getMP)
-
- if not Crypto:
- skip = "can't run w/o PyCrypto"
-
- if not pyasn1:
- skip = "Cannot run without PyASN1"
-
-
- def test_getMP(self):
- """
- L{common.getMP} should parse the a multiple precision integer from a
- string: a 4-byte length followed by length bytes of the integer.
- """
- self.assertEqual(
- self.getMP('\x00\x00\x00\x04\x00\x00\x00\x01'),
- (1, ''))
-
-
- def test_getMPBigInteger(self):
- """
- L{common.getMP} should be able to parse a big enough integer
- (that doesn't fit on one byte).
- """
- self.assertEqual(
- self.getMP('\x00\x00\x00\x04\x01\x02\x03\x04'),
- (16909060, ''))
-
-
- def test_multipleGetMP(self):
- """
- L{common.getMP} has the ability to parse multiple integer in the same
- string.
- """
- self.assertEqual(
- self.getMP('\x00\x00\x00\x04\x00\x00\x00\x01'
- '\x00\x00\x00\x04\x00\x00\x00\x02', 2),
- (1, 2, ''))
-
-
- def test_getMPRemainingData(self):
- """
- When more data than needed is sent to L{common.getMP}, it should return
- the remaining data.
- """
- self.assertEqual(
- self.getMP('\x00\x00\x00\x04\x00\x00\x00\x01foo'),
- (1, 'foo'))
-
-
- def test_notEnoughData(self):
- """
- When the string passed to L{common.getMP} doesn't even make 5 bytes,
- it should raise a L{struct.error}.
- """
- self.assertRaises(struct.error, self.getMP, '\x02\x00')
-
-
-
-class PyMPTestCase(MPTestCase):
- """
- Tests for the python implementation of L{common.getMP}.
- """
- getMP = staticmethod(common.getMP_py)
-
-
-
-class GMPYMPTestCase(MPTestCase):
- """
- Tests for the gmpy implementation of L{common.getMP}.
- """
- getMP = staticmethod(common._fastgetMP)
-
-
-class BuiltinPowHackTestCase(unittest.TestCase):
- """
- Tests that the builtin pow method is still correct after
- L{twisted.conch.ssh.common} monkeypatches it to use gmpy.
- """
-
- def test_floatBase(self):
- """
- pow gives the correct result when passed a base of type float with a
- non-integer value.
- """
- self.assertEqual(6.25, pow(2.5, 2))
-
- def test_intBase(self):
- """
- pow gives the correct result when passed a base of type int.
- """
- self.assertEqual(81, pow(3, 4))
-
- def test_longBase(self):
- """
- pow gives the correct result when passed a base of type long.
- """
- self.assertEqual(81, pow(3, 4))
-
- def test_mpzBase(self):
- """
- pow gives the correct result when passed a base of type gmpy.mpz.
- """
- if gmpy is None:
- raise unittest.SkipTest('gmpy not available')
- self.assertEqual(81, pow(gmpy.mpz(3), 4))
-
-
-try:
- import gmpy
-except ImportError:
- GMPYMPTestCase.skip = "gmpy not available"
- gmpy = None
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_tap.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_tap.py
deleted file mode 100644
index 9a88f98..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_tap.py
+++ /dev/null
@@ -1,183 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.tap}.
-"""
-
-try:
- import Crypto.Cipher.DES3
-except:
- Crypto = None
-
-try:
- import pyasn1
-except ImportError:
- pyasn1 = None
-
-try:
- from twisted.conch import unix
-except ImportError:
- unix = None
-
-if Crypto and pyasn1 and unix:
- from twisted.conch import tap
- from twisted.conch.openssh_compat.factory import OpenSSHFactory
-
-from twisted.application.internet import StreamServerEndpointService
-from twisted.cred import error
-from twisted.cred.credentials import IPluggableAuthenticationModules
-from twisted.cred.credentials import ISSHPrivateKey
-from twisted.cred.credentials import IUsernamePassword, UsernamePassword
-
-from twisted.trial.unittest import TestCase
-
-
-
-class MakeServiceTest(TestCase):
- """
- Tests for L{tap.makeService}.
- """
-
- if not Crypto:
- skip = "can't run w/o PyCrypto"
-
- if not pyasn1:
- skip = "Cannot run without PyASN1"
-
- if not unix:
- skip = "can't run on non-posix computers"
-
- usernamePassword = ('iamuser', 'thisispassword')
-
- def setUp(self):
- """
- Create a file with two users.
- """
- self.filename = self.mktemp()
- f = open(self.filename, 'wb+')
- f.write(':'.join(self.usernamePassword))
- f.close()
- self.options = tap.Options()
-
-
- def test_basic(self):
- """
- L{tap.makeService} returns a L{StreamServerEndpointService} instance
- running on TCP port 22, and the linked protocol factory is an instance
- of L{OpenSSHFactory}.
- """
- config = tap.Options()
- service = tap.makeService(config)
- self.assertIsInstance(service, StreamServerEndpointService)
- self.assertEqual(service.endpoint._port, 22)
- self.assertIsInstance(service.factory, OpenSSHFactory)
-
-
- def test_defaultAuths(self):
- """
- Make sure that if the C{--auth} command-line option is not passed,
- the default checkers are (for backwards compatibility): SSH, UNIX, and
- PAM if available
- """
- numCheckers = 2
- try:
- from twisted.cred import pamauth
- self.assertIn(IPluggableAuthenticationModules,
- self.options['credInterfaces'],
- "PAM should be one of the modules")
- numCheckers += 1
- except ImportError:
- pass
-
- self.assertIn(ISSHPrivateKey, self.options['credInterfaces'],
- "SSH should be one of the default checkers")
- self.assertIn(IUsernamePassword, self.options['credInterfaces'],
- "UNIX should be one of the default checkers")
- self.assertEqual(numCheckers, len(self.options['credCheckers']),
- "There should be %d checkers by default" % (numCheckers,))
-
-
- def test_authAdded(self):
- """
- The C{--auth} command-line option will add a checker to the list of
- checkers, and it should be the only auth checker
- """
- self.options.parseOptions(['--auth', 'file:' + self.filename])
- self.assertEqual(len(self.options['credCheckers']), 1)
-
-
- def test_multipleAuthAdded(self):
- """
- Multiple C{--auth} command-line options will add all checkers specified
- to the list ofcheckers, and there should only be the specified auth
- checkers (no default checkers).
- """
- self.options.parseOptions(['--auth', 'file:' + self.filename,
- '--auth', 'memory:testuser:testpassword'])
- self.assertEqual(len(self.options['credCheckers']), 2)
-
-
- def test_authFailure(self):
- """
- The checker created by the C{--auth} command-line option returns a
- L{Deferred} that fails with L{UnauthorizedLogin} when
- presented with credentials that are unknown to that checker.
- """
- self.options.parseOptions(['--auth', 'file:' + self.filename])
- checker = self.options['credCheckers'][-1]
- invalid = UsernamePassword(self.usernamePassword[0], 'fake')
- # Wrong password should raise error
- return self.assertFailure(
- checker.requestAvatarId(invalid), error.UnauthorizedLogin)
-
-
- def test_authSuccess(self):
- """
- The checker created by the C{--auth} command-line option returns a
- L{Deferred} that returns the avatar id when presented with credentials
- that are known to that checker.
- """
- self.options.parseOptions(['--auth', 'file:' + self.filename])
- checker = self.options['credCheckers'][-1]
- correct = UsernamePassword(*self.usernamePassword)
- d = checker.requestAvatarId(correct)
-
- def checkSuccess(username):
- self.assertEqual(username, correct.username)
-
- return d.addCallback(checkSuccess)
-
-
- def test_checkersPamAuth(self):
- """
- The L{OpenSSHFactory} built by L{tap.makeService} has a portal with
- L{IPluggableAuthenticationModules}, L{ISSHPrivateKey} and
- L{IUsernamePassword} interfaces registered as checkers if C{pamauth} is
- available.
- """
- # Fake the presence of pamauth, even if PyPAM is not installed
- self.patch(tap, "pamauth", object())
- config = tap.Options()
- service = tap.makeService(config)
- portal = service.factory.portal
- self.assertEqual(
- set(portal.checkers.keys()),
- set([IPluggableAuthenticationModules, ISSHPrivateKey,
- IUsernamePassword]))
-
-
- def test_checkersWithoutPamAuth(self):
- """
- The L{OpenSSHFactory} built by L{tap.makeService} has a portal with
- L{ISSHPrivateKey} and L{IUsernamePassword} interfaces registered as
- checkers if C{pamauth} is not available.
- """
- # Fake the absence of pamauth, even if PyPAM is installed
- self.patch(tap, "pamauth", None)
- config = tap.Options()
- service = tap.makeService(config)
- portal = service.factory.portal
- self.assertEqual(
- set(portal.checkers.keys()),
- set([ISSHPrivateKey, IUsernamePassword]))
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_telnet.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_telnet.py
deleted file mode 100644
index 9b5bf76..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_telnet.py
+++ /dev/null
@@ -1,767 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_telnet -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for L{twisted.conch.telnet}.
-"""
-
-from zope.interface import implements
-from zope.interface.verify import verifyObject
-
-from twisted.internet import defer
-
-from twisted.conch import telnet
-
-from twisted.trial import unittest
-from twisted.test import proto_helpers
-
-
-class TestProtocol:
- implements(telnet.ITelnetProtocol)
-
- localEnableable = ()
- remoteEnableable = ()
-
- def __init__(self):
- self.bytes = ''
- self.subcmd = ''
- self.calls = []
-
- self.enabledLocal = []
- self.enabledRemote = []
- self.disabledLocal = []
- self.disabledRemote = []
-
- def makeConnection(self, transport):
- d = transport.negotiationMap = {}
- d['\x12'] = self.neg_TEST_COMMAND
-
- d = transport.commandMap = transport.commandMap.copy()
- for cmd in ('NOP', 'DM', 'BRK', 'IP', 'AO', 'AYT', 'EC', 'EL', 'GA'):
- d[getattr(telnet, cmd)] = lambda arg, cmd=cmd: self.calls.append(cmd)
-
- def dataReceived(self, bytes):
- self.bytes += bytes
-
- def connectionLost(self, reason):
- pass
-
- def neg_TEST_COMMAND(self, payload):
- self.subcmd = payload
-
- def enableLocal(self, option):
- if option in self.localEnableable:
- self.enabledLocal.append(option)
- return True
- return False
-
- def disableLocal(self, option):
- self.disabledLocal.append(option)
-
- def enableRemote(self, option):
- if option in self.remoteEnableable:
- self.enabledRemote.append(option)
- return True
- return False
-
- def disableRemote(self, option):
- self.disabledRemote.append(option)
-
-
-
-class TestInterfaces(unittest.TestCase):
- def test_interface(self):
- """
- L{telnet.TelnetProtocol} implements L{telnet.ITelnetProtocol}
- """
- p = telnet.TelnetProtocol()
- verifyObject(telnet.ITelnetProtocol, p)
-
-
-
-class TelnetTransportTestCase(unittest.TestCase):
- """
- Tests for L{telnet.TelnetTransport}.
- """
- def setUp(self):
- self.p = telnet.TelnetTransport(TestProtocol)
- self.t = proto_helpers.StringTransport()
- self.p.makeConnection(self.t)
-
- def testRegularBytes(self):
- # Just send a bunch of bytes. None of these do anything
- # with telnet. They should pass right through to the
- # application layer.
- h = self.p.protocol
-
- L = ["here are some bytes la la la",
- "some more arrive here",
- "lots of bytes to play with",
- "la la la",
- "ta de da",
- "dum"]
- for b in L:
- self.p.dataReceived(b)
-
- self.assertEqual(h.bytes, ''.join(L))
-
- def testNewlineHandling(self):
- # Send various kinds of newlines and make sure they get translated
- # into \n.
- h = self.p.protocol
-
- L = ["here is the first line\r\n",
- "here is the second line\r\0",
- "here is the third line\r\n",
- "here is the last line\r\0"]
-
- for b in L:
- self.p.dataReceived(b)
-
- self.assertEqual(h.bytes, L[0][:-2] + '\n' +
- L[1][:-2] + '\r' +
- L[2][:-2] + '\n' +
- L[3][:-2] + '\r')
-
- def testIACEscape(self):
- # Send a bunch of bytes and a couple quoted \xFFs. Unquoted,
- # \xFF is a telnet command. Quoted, one of them from each pair
- # should be passed through to the application layer.
- h = self.p.protocol
-
- L = ["here are some bytes\xff\xff with an embedded IAC",
- "and here is a test of a border escape\xff",
- "\xff did you get that IAC?"]
-
- for b in L:
- self.p.dataReceived(b)
-
- self.assertEqual(h.bytes, ''.join(L).replace('\xff\xff', '\xff'))
-
- def _simpleCommandTest(self, cmdName):
- # Send a single simple telnet command and make sure
- # it gets noticed and the appropriate method gets
- # called.
- h = self.p.protocol
-
- cmd = telnet.IAC + getattr(telnet, cmdName)
- L = ["Here's some bytes, tra la la",
- "But ono!" + cmd + " an interrupt"]
-
- for b in L:
- self.p.dataReceived(b)
-
- self.assertEqual(h.calls, [cmdName])
- self.assertEqual(h.bytes, ''.join(L).replace(cmd, ''))
-
- def testInterrupt(self):
- self._simpleCommandTest("IP")
-
- def testNoOperation(self):
- self._simpleCommandTest("NOP")
-
- def testDataMark(self):
- self._simpleCommandTest("DM")
-
- def testBreak(self):
- self._simpleCommandTest("BRK")
-
- def testAbortOutput(self):
- self._simpleCommandTest("AO")
-
- def testAreYouThere(self):
- self._simpleCommandTest("AYT")
-
- def testEraseCharacter(self):
- self._simpleCommandTest("EC")
-
- def testEraseLine(self):
- self._simpleCommandTest("EL")
-
- def testGoAhead(self):
- self._simpleCommandTest("GA")
-
- def testSubnegotiation(self):
- # Send a subnegotiation command and make sure it gets
- # parsed and that the correct method is called.
- h = self.p.protocol
-
- cmd = telnet.IAC + telnet.SB + '\x12hello world' + telnet.IAC + telnet.SE
- L = ["These are some bytes but soon" + cmd,
- "there will be some more"]
-
- for b in L:
- self.p.dataReceived(b)
-
- self.assertEqual(h.bytes, ''.join(L).replace(cmd, ''))
- self.assertEqual(h.subcmd, list("hello world"))
-
- def testSubnegotiationWithEmbeddedSE(self):
- # Send a subnegotiation command with an embedded SE. Make sure
- # that SE gets passed to the correct method.
- h = self.p.protocol
-
- cmd = (telnet.IAC + telnet.SB +
- '\x12' + telnet.SE +
- telnet.IAC + telnet.SE)
-
- L = ["Some bytes are here" + cmd + "and here",
- "and here"]
-
- for b in L:
- self.p.dataReceived(b)
-
- self.assertEqual(h.bytes, ''.join(L).replace(cmd, ''))
- self.assertEqual(h.subcmd, [telnet.SE])
-
- def testBoundarySubnegotiation(self):
- # Send a subnegotiation command. Split it at every possible byte boundary
- # and make sure it always gets parsed and that it is passed to the correct
- # method.
- cmd = (telnet.IAC + telnet.SB +
- '\x12' + telnet.SE + 'hello' +
- telnet.IAC + telnet.SE)
-
- for i in range(len(cmd)):
- h = self.p.protocol = TestProtocol()
- h.makeConnection(self.p)
-
- a, b = cmd[:i], cmd[i:]
- L = ["first part" + a,
- b + "last part"]
-
- for bytes in L:
- self.p.dataReceived(bytes)
-
- self.assertEqual(h.bytes, ''.join(L).replace(cmd, ''))
- self.assertEqual(h.subcmd, [telnet.SE] + list('hello'))
-
- def _enabledHelper(self, o, eL=[], eR=[], dL=[], dR=[]):
- self.assertEqual(o.enabledLocal, eL)
- self.assertEqual(o.enabledRemote, eR)
- self.assertEqual(o.disabledLocal, dL)
- self.assertEqual(o.disabledRemote, dR)
-
- def testRefuseWill(self):
- # Try to enable an option. The server should refuse to enable it.
- cmd = telnet.IAC + telnet.WILL + '\x12'
-
- bytes = "surrounding bytes" + cmd + "to spice things up"
- self.p.dataReceived(bytes)
-
- self.assertEqual(self.p.protocol.bytes, bytes.replace(cmd, ''))
- self.assertEqual(self.t.value(), telnet.IAC + telnet.DONT + '\x12')
- self._enabledHelper(self.p.protocol)
-
- def testRefuseDo(self):
- # Try to enable an option. The server should refuse to enable it.
- cmd = telnet.IAC + telnet.DO + '\x12'
-
- bytes = "surrounding bytes" + cmd + "to spice things up"
- self.p.dataReceived(bytes)
-
- self.assertEqual(self.p.protocol.bytes, bytes.replace(cmd, ''))
- self.assertEqual(self.t.value(), telnet.IAC + telnet.WONT + '\x12')
- self._enabledHelper(self.p.protocol)
-
- def testAcceptDo(self):
- # Try to enable an option. The option is in our allowEnable
- # list, so we will allow it to be enabled.
- cmd = telnet.IAC + telnet.DO + '\x19'
- bytes = 'padding' + cmd + 'trailer'
-
- h = self.p.protocol
- h.localEnableable = ('\x19',)
- self.p.dataReceived(bytes)
-
- self.assertEqual(self.t.value(), telnet.IAC + telnet.WILL + '\x19')
- self._enabledHelper(h, eL=['\x19'])
-
- def testAcceptWill(self):
- # Same as testAcceptDo, but reversed.
- cmd = telnet.IAC + telnet.WILL + '\x91'
- bytes = 'header' + cmd + 'padding'
-
- h = self.p.protocol
- h.remoteEnableable = ('\x91',)
- self.p.dataReceived(bytes)
-
- self.assertEqual(self.t.value(), telnet.IAC + telnet.DO + '\x91')
- self._enabledHelper(h, eR=['\x91'])
-
- def testAcceptWont(self):
- # Try to disable an option. The server must allow any option to
- # be disabled at any time. Make sure it disables it and sends
- # back an acknowledgement of this.
- cmd = telnet.IAC + telnet.WONT + '\x29'
-
- # Jimmy it - after these two lines, the server will be in a state
- # such that it believes the option to have been previously enabled
- # via normal negotiation.
- s = self.p.getOptionState('\x29')
- s.him.state = 'yes'
-
- bytes = "fiddle dee" + cmd
- self.p.dataReceived(bytes)
-
- self.assertEqual(self.p.protocol.bytes, bytes.replace(cmd, ''))
- self.assertEqual(self.t.value(), telnet.IAC + telnet.DONT + '\x29')
- self.assertEqual(s.him.state, 'no')
- self._enabledHelper(self.p.protocol, dR=['\x29'])
-
- def testAcceptDont(self):
- # Try to disable an option. The server must allow any option to
- # be disabled at any time. Make sure it disables it and sends
- # back an acknowledgement of this.
- cmd = telnet.IAC + telnet.DONT + '\x29'
-
- # Jimmy it - after these two lines, the server will be in a state
- # such that it believes the option to have beenp previously enabled
- # via normal negotiation.
- s = self.p.getOptionState('\x29')
- s.us.state = 'yes'
-
- bytes = "fiddle dum " + cmd
- self.p.dataReceived(bytes)
-
- self.assertEqual(self.p.protocol.bytes, bytes.replace(cmd, ''))
- self.assertEqual(self.t.value(), telnet.IAC + telnet.WONT + '\x29')
- self.assertEqual(s.us.state, 'no')
- self._enabledHelper(self.p.protocol, dL=['\x29'])
-
- def testIgnoreWont(self):
- # Try to disable an option. The option is already disabled. The
- # server should send nothing in response to this.
- cmd = telnet.IAC + telnet.WONT + '\x47'
-
- bytes = "dum de dum" + cmd + "tra la la"
- self.p.dataReceived(bytes)
-
- self.assertEqual(self.p.protocol.bytes, bytes.replace(cmd, ''))
- self.assertEqual(self.t.value(), '')
- self._enabledHelper(self.p.protocol)
-
- def testIgnoreDont(self):
- # Try to disable an option. The option is already disabled. The
- # server should send nothing in response to this. Doing so could
- # lead to a negotiation loop.
- cmd = telnet.IAC + telnet.DONT + '\x47'
-
- bytes = "dum de dum" + cmd + "tra la la"
- self.p.dataReceived(bytes)
-
- self.assertEqual(self.p.protocol.bytes, bytes.replace(cmd, ''))
- self.assertEqual(self.t.value(), '')
- self._enabledHelper(self.p.protocol)
-
- def testIgnoreWill(self):
- # Try to enable an option. The option is already enabled. The
- # server should send nothing in response to this. Doing so could
- # lead to a negotiation loop.
- cmd = telnet.IAC + telnet.WILL + '\x56'
-
- # Jimmy it - after these two lines, the server will be in a state
- # such that it believes the option to have been previously enabled
- # via normal negotiation.
- s = self.p.getOptionState('\x56')
- s.him.state = 'yes'
-
- bytes = "tra la la" + cmd + "dum de dum"
- self.p.dataReceived(bytes)
-
- self.assertEqual(self.p.protocol.bytes, bytes.replace(cmd, ''))
- self.assertEqual(self.t.value(), '')
- self._enabledHelper(self.p.protocol)
-
- def testIgnoreDo(self):
- # Try to enable an option. The option is already enabled. The
- # server should send nothing in response to this. Doing so could
- # lead to a negotiation loop.
- cmd = telnet.IAC + telnet.DO + '\x56'
-
- # Jimmy it - after these two lines, the server will be in a state
- # such that it believes the option to have been previously enabled
- # via normal negotiation.
- s = self.p.getOptionState('\x56')
- s.us.state = 'yes'
-
- bytes = "tra la la" + cmd + "dum de dum"
- self.p.dataReceived(bytes)
-
- self.assertEqual(self.p.protocol.bytes, bytes.replace(cmd, ''))
- self.assertEqual(self.t.value(), '')
- self._enabledHelper(self.p.protocol)
-
- def testAcceptedEnableRequest(self):
- # Try to enable an option through the user-level API. This
- # returns a Deferred that fires when negotiation about the option
- # finishes. Make sure it fires, make sure state gets updated
- # properly, make sure the result indicates the option was enabled.
- d = self.p.do('\x42')
-
- h = self.p.protocol
- h.remoteEnableable = ('\x42',)
-
- self.assertEqual(self.t.value(), telnet.IAC + telnet.DO + '\x42')
-
- self.p.dataReceived(telnet.IAC + telnet.WILL + '\x42')
-
- d.addCallback(self.assertEqual, True)
- d.addCallback(lambda _: self._enabledHelper(h, eR=['\x42']))
- return d
-
-
- def test_refusedEnableRequest(self):
- """
- If the peer refuses to enable an option we request it to enable, the
- L{Deferred} returned by L{TelnetProtocol.do} fires with an
- L{OptionRefused} L{Failure}.
- """
- # Try to enable an option through the user-level API. This returns a
- # Deferred that fires when negotiation about the option finishes. Make
- # sure it fires, make sure state gets updated properly, make sure the
- # result indicates the option was enabled.
- self.p.protocol.remoteEnableable = ('\x42',)
- d = self.p.do('\x42')
-
- self.assertEqual(self.t.value(), telnet.IAC + telnet.DO + '\x42')
-
- s = self.p.getOptionState('\x42')
- self.assertEqual(s.him.state, 'no')
- self.assertEqual(s.us.state, 'no')
- self.assertEqual(s.him.negotiating, True)
- self.assertEqual(s.us.negotiating, False)
-
- self.p.dataReceived(telnet.IAC + telnet.WONT + '\x42')
-
- d = self.assertFailure(d, telnet.OptionRefused)
- d.addCallback(lambda ignored: self._enabledHelper(self.p.protocol))
- d.addCallback(
- lambda ignored: self.assertEqual(s.him.negotiating, False))
- return d
-
-
- def test_refusedEnableOffer(self):
- """
- If the peer refuses to allow us to enable an option, the L{Deferred}
- returned by L{TelnetProtocol.will} fires with an L{OptionRefused}
- L{Failure}.
- """
- # Try to offer an option through the user-level API. This returns a
- # Deferred that fires when negotiation about the option finishes. Make
- # sure it fires, make sure state gets updated properly, make sure the
- # result indicates the option was enabled.
- self.p.protocol.localEnableable = ('\x42',)
- d = self.p.will('\x42')
-
- self.assertEqual(self.t.value(), telnet.IAC + telnet.WILL + '\x42')
-
- s = self.p.getOptionState('\x42')
- self.assertEqual(s.him.state, 'no')
- self.assertEqual(s.us.state, 'no')
- self.assertEqual(s.him.negotiating, False)
- self.assertEqual(s.us.negotiating, True)
-
- self.p.dataReceived(telnet.IAC + telnet.DONT + '\x42')
-
- d = self.assertFailure(d, telnet.OptionRefused)
- d.addCallback(lambda ignored: self._enabledHelper(self.p.protocol))
- d.addCallback(
- lambda ignored: self.assertEqual(s.us.negotiating, False))
- return d
-
-
- def testAcceptedDisableRequest(self):
- # Try to disable an option through the user-level API. This
- # returns a Deferred that fires when negotiation about the option
- # finishes. Make sure it fires, make sure state gets updated
- # properly, make sure the result indicates the option was enabled.
- s = self.p.getOptionState('\x42')
- s.him.state = 'yes'
-
- d = self.p.dont('\x42')
-
- self.assertEqual(self.t.value(), telnet.IAC + telnet.DONT + '\x42')
-
- self.p.dataReceived(telnet.IAC + telnet.WONT + '\x42')
-
- d.addCallback(self.assertEqual, True)
- d.addCallback(lambda _: self._enabledHelper(self.p.protocol,
- dR=['\x42']))
- return d
-
- def testNegotiationBlocksFurtherNegotiation(self):
- # Try to disable an option, then immediately try to enable it, then
- # immediately try to disable it. Ensure that the 2nd and 3rd calls
- # fail quickly with the right exception.
- s = self.p.getOptionState('\x24')
- s.him.state = 'yes'
- d2 = self.p.dont('\x24') # fires after the first line of _final
-
- def _do(x):
- d = self.p.do('\x24')
- return self.assertFailure(d, telnet.AlreadyNegotiating)
-
- def _dont(x):
- d = self.p.dont('\x24')
- return self.assertFailure(d, telnet.AlreadyNegotiating)
-
- def _final(x):
- self.p.dataReceived(telnet.IAC + telnet.WONT + '\x24')
- # an assertion that only passes if d2 has fired
- self._enabledHelper(self.p.protocol, dR=['\x24'])
- # Make sure we allow this
- self.p.protocol.remoteEnableable = ('\x24',)
- d = self.p.do('\x24')
- self.p.dataReceived(telnet.IAC + telnet.WILL + '\x24')
- d.addCallback(self.assertEqual, True)
- d.addCallback(lambda _: self._enabledHelper(self.p.protocol,
- eR=['\x24'],
- dR=['\x24']))
- return d
-
- d = _do(None)
- d.addCallback(_dont)
- d.addCallback(_final)
- return d
-
- def testSuperfluousDisableRequestRaises(self):
- # Try to disable a disabled option. Make sure it fails properly.
- d = self.p.dont('\xab')
- return self.assertFailure(d, telnet.AlreadyDisabled)
-
- def testSuperfluousEnableRequestRaises(self):
- # Try to disable a disabled option. Make sure it fails properly.
- s = self.p.getOptionState('\xab')
- s.him.state = 'yes'
- d = self.p.do('\xab')
- return self.assertFailure(d, telnet.AlreadyEnabled)
-
- def testLostConnectionFailsDeferreds(self):
- d1 = self.p.do('\x12')
- d2 = self.p.do('\x23')
- d3 = self.p.do('\x34')
-
- class TestException(Exception):
- pass
-
- self.p.connectionLost(TestException("Total failure!"))
-
- d1 = self.assertFailure(d1, TestException)
- d2 = self.assertFailure(d2, TestException)
- d3 = self.assertFailure(d3, TestException)
- return defer.gatherResults([d1, d2, d3])
-
-
-class TestTelnet(telnet.Telnet):
- """
- A trivial extension of the telnet protocol class useful to unit tests.
- """
- def __init__(self):
- telnet.Telnet.__init__(self)
- self.events = []
-
-
- def applicationDataReceived(self, bytes):
- """
- Record the given data in C{self.events}.
- """
- self.events.append(('bytes', bytes))
-
-
- def unhandledCommand(self, command, bytes):
- """
- Record the given command in C{self.events}.
- """
- self.events.append(('command', command, bytes))
-
-
- def unhandledSubnegotiation(self, command, bytes):
- """
- Record the given subnegotiation command in C{self.events}.
- """
- self.events.append(('negotiate', command, bytes))
-
-
-
-class TelnetTests(unittest.TestCase):
- """
- Tests for L{telnet.Telnet}.
-
- L{telnet.Telnet} implements the TELNET protocol (RFC 854), including option
- and suboption negotiation, and option state tracking.
- """
- def setUp(self):
- """
- Create an unconnected L{telnet.Telnet} to be used by tests.
- """
- self.protocol = TestTelnet()
-
-
- def test_enableLocal(self):
- """
- L{telnet.Telnet.enableLocal} should reject all options, since
- L{telnet.Telnet} does not know how to implement any options.
- """
- self.assertFalse(self.protocol.enableLocal('\0'))
-
-
- def test_enableRemote(self):
- """
- L{telnet.Telnet.enableRemote} should reject all options, since
- L{telnet.Telnet} does not know how to implement any options.
- """
- self.assertFalse(self.protocol.enableRemote('\0'))
-
-
- def test_disableLocal(self):
- """
- It is an error for L{telnet.Telnet.disableLocal} to be called, since
- L{telnet.Telnet.enableLocal} will never allow any options to be enabled
- locally. If a subclass overrides enableLocal, it must also override
- disableLocal.
- """
- self.assertRaises(NotImplementedError, self.protocol.disableLocal, '\0')
-
-
- def test_disableRemote(self):
- """
- It is an error for L{telnet.Telnet.disableRemote} to be called, since
- L{telnet.Telnet.enableRemote} will never allow any options to be
- enabled remotely. If a subclass overrides enableRemote, it must also
- override disableRemote.
- """
- self.assertRaises(NotImplementedError, self.protocol.disableRemote, '\0')
-
-
- def test_requestNegotiation(self):
- """
- L{telnet.Telnet.requestNegotiation} formats the feature byte and the
- payload bytes into the subnegotiation format and sends them.
-
- See RFC 855.
- """
- transport = proto_helpers.StringTransport()
- self.protocol.makeConnection(transport)
- self.protocol.requestNegotiation('\x01', '\x02\x03')
- self.assertEqual(
- transport.value(),
- # IAC SB feature bytes IAC SE
- '\xff\xfa\x01\x02\x03\xff\xf0')
-
-
- def test_requestNegotiationEscapesIAC(self):
- """
- If the payload for a subnegotiation includes I{IAC}, it is escaped by
- L{telnet.Telnet.requestNegotiation} with another I{IAC}.
-
- See RFC 855.
- """
- transport = proto_helpers.StringTransport()
- self.protocol.makeConnection(transport)
- self.protocol.requestNegotiation('\x01', '\xff')
- self.assertEqual(
- transport.value(),
- '\xff\xfa\x01\xff\xff\xff\xf0')
-
-
- def _deliver(self, bytes, *expected):
- """
- Pass the given bytes to the protocol's C{dataReceived} method and
- assert that the given events occur.
- """
- received = self.protocol.events = []
- self.protocol.dataReceived(bytes)
- self.assertEqual(received, list(expected))
-
-
- def test_oneApplicationDataByte(self):
- """
- One application-data byte in the default state gets delivered right
- away.
- """
- self._deliver('a', ('bytes', 'a'))
-
-
- def test_twoApplicationDataBytes(self):
- """
- Two application-data bytes in the default state get delivered
- together.
- """
- self._deliver('bc', ('bytes', 'bc'))
-
-
- def test_threeApplicationDataBytes(self):
- """
- Three application-data bytes followed by a control byte get
- delivered, but the control byte doesn't.
- """
- self._deliver('def' + telnet.IAC, ('bytes', 'def'))
-
-
- def test_escapedControl(self):
- """
- IAC in the escaped state gets delivered and so does another
- application-data byte following it.
- """
- self._deliver(telnet.IAC)
- self._deliver(telnet.IAC + 'g', ('bytes', telnet.IAC + 'g'))
-
-
- def test_carriageReturn(self):
- """
- A carriage return only puts the protocol into the newline state. A
- linefeed in the newline state causes just the newline to be
- delivered. A nul in the newline state causes a carriage return to
- be delivered. An IAC in the newline state causes a carriage return
- to be delivered and puts the protocol into the escaped state.
- Anything else causes a carriage return and that thing to be
- delivered.
- """
- self._deliver('\r')
- self._deliver('\n', ('bytes', '\n'))
- self._deliver('\r\n', ('bytes', '\n'))
-
- self._deliver('\r')
- self._deliver('\0', ('bytes', '\r'))
- self._deliver('\r\0', ('bytes', '\r'))
-
- self._deliver('\r')
- self._deliver('a', ('bytes', '\ra'))
- self._deliver('\ra', ('bytes', '\ra'))
-
- self._deliver('\r')
- self._deliver(
- telnet.IAC + telnet.IAC + 'x', ('bytes', '\r' + telnet.IAC + 'x'))
-
-
- def test_applicationDataBeforeSimpleCommand(self):
- """
- Application bytes received before a command are delivered before the
- command is processed.
- """
- self._deliver(
- 'x' + telnet.IAC + telnet.NOP,
- ('bytes', 'x'), ('command', telnet.NOP, None))
-
-
- def test_applicationDataBeforeCommand(self):
- """
- Application bytes received before a WILL/WONT/DO/DONT are delivered
- before the command is processed.
- """
- self.protocol.commandMap = {}
- self._deliver(
- 'y' + telnet.IAC + telnet.WILL + '\x00',
- ('bytes', 'y'), ('command', telnet.WILL, '\x00'))
-
-
- def test_applicationDataBeforeSubnegotiation(self):
- """
- Application bytes received before a subnegotiation command are
- delivered before the negotiation is processed.
- """
- self._deliver(
- 'z' + telnet.IAC + telnet.SB + 'Qx' + telnet.IAC + telnet.SE,
- ('bytes', 'z'), ('negotiate', 'Q', ['x']))
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_text.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_text.py
deleted file mode 100644
index 220f8fa..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_text.py
+++ /dev/null
@@ -1,161 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_text -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-from twisted.trial import unittest
-
-from twisted.conch.insults import helper, text
-from twisted.conch.insults.text import attributes as A
-
-
-
-class FormattedTextTests(unittest.TestCase):
- """
- Tests for assembling formatted text.
- """
- def test_trivial(self):
- """
- Using no formatting attributes produces no VT102 control sequences in
- the flattened output.
- """
- self.assertEqual(
- text.assembleFormattedText(A.normal['Hello, world.']),
- 'Hello, world.')
-
-
- def test_bold(self):
- """
- The bold formatting attribute, L{A.bold}, emits the VT102 control
- sequence to enable bold when flattened.
- """
- self.assertEqual(
- text.assembleFormattedText(A.bold['Hello, world.']),
- '\x1b[1mHello, world.')
-
-
- def test_underline(self):
- """
- The underline formatting attribute, L{A.underline}, emits the VT102
- control sequence to enable underlining when flattened.
- """
- self.assertEqual(
- text.assembleFormattedText(A.underline['Hello, world.']),
- '\x1b[4mHello, world.')
-
-
- def test_blink(self):
- """
- The blink formatting attribute, L{A.blink}, emits the VT102 control
- sequence to enable blinking when flattened.
- """
- self.assertEqual(
- text.assembleFormattedText(A.blink['Hello, world.']),
- '\x1b[5mHello, world.')
-
-
- def test_reverseVideo(self):
- """
- The reverse-video formatting attribute, L{A.reverseVideo}, emits the
- VT102 control sequence to enable reversed video when flattened.
- """
- self.assertEqual(
- text.assembleFormattedText(A.reverseVideo['Hello, world.']),
- '\x1b[7mHello, world.')
-
-
- def test_minus(self):
- """
- Formatting attributes prefixed with a minus (C{-}) temporarily disable
- the prefixed attribute, emitting no VT102 control sequence to enable
- it in the flattened output.
- """
- self.assertEqual(
- text.assembleFormattedText(
- A.bold[A.blink['Hello', -A.bold[' world'], '.']]),
- '\x1b[1;5mHello\x1b[0;5m world\x1b[1;5m.')
-
-
- def test_foreground(self):
- """
- The foreground color formatting attribute, L{A.fg}, emits the VT102
- control sequence to set the selected foreground color when flattened.
- """
- self.assertEqual(
- text.assembleFormattedText(
- A.normal[A.fg.red['Hello, '], A.fg.green['world!']]),
- '\x1b[31mHello, \x1b[32mworld!')
-
-
- def test_background(self):
- """
- The background color formatting attribute, L{A.bg}, emits the VT102
- control sequence to set the selected background color when flattened.
- """
- self.assertEqual(
- text.assembleFormattedText(
- A.normal[A.bg.red['Hello, '], A.bg.green['world!']]),
- '\x1b[41mHello, \x1b[42mworld!')
-
-
- def test_flattenDeprecated(self):
- """
- L{twisted.conch.insults.text.flatten} emits a deprecation warning when
- imported or accessed.
- """
- warningsShown = self.flushWarnings([self.test_flattenDeprecated])
- self.assertEqual(len(warningsShown), 0)
-
- # Trigger the deprecation warning.
- text.flatten
-
- warningsShown = self.flushWarnings([self.test_flattenDeprecated])
- self.assertEqual(len(warningsShown), 1)
- self.assertEqual(warningsShown[0]['category'], DeprecationWarning)
- self.assertEqual(
- warningsShown[0]['message'],
- 'twisted.conch.insults.text.flatten was deprecated in Twisted '
- '13.1.0: Use twisted.conch.insults.text.assembleFormattedText '
- 'instead.')
-
-
-
-class EfficiencyTestCase(unittest.TestCase):
- todo = ("flatten() isn't quite stateful enough to avoid emitting a few extra bytes in "
- "certain circumstances, so these tests fail. The failures take the form of "
- "additional elements in the ;-delimited character attribute lists. For example, "
- "\\x1b[0;31;46m might be emitted instead of \\x[46m, even if 31 has already been "
- "activated and no conflicting attributes are set which need to be cleared.")
-
- def setUp(self):
- self.attrs = helper._FormattingState()
-
- def testComplexStructure(self):
- output = A.normal[
- A.bold[
- A.bg.cyan[
- A.fg.red[
- "Foreground Red, Background Cyan, Bold",
- A.blink[
- "Blinking"],
- -A.bold[
- "Foreground Red, Background Cyan, normal"]],
- A.fg.green[
- "Foreground Green, Background Cyan, Bold"]]]]
-
- self.assertEqual(
- text.flatten(output, self.attrs),
- "\x1b[1;31;46mForeground Red, Background Cyan, Bold"
- "\x1b[5mBlinking"
- "\x1b[0;31;46mForeground Red, Background Cyan, normal"
- "\x1b[1;32;46mForeground Green, Background Cyan, Bold")
-
- def testNesting(self):
- self.assertEqual(
- text.flatten(A.bold['Hello, ', A.underline['world.']], self.attrs),
- '\x1b[1mHello, \x1b[4mworld.')
-
- self.assertEqual(
- text.flatten(
- A.bold[A.reverseVideo['Hello, ', A.normal['world'], '.']],
- self.attrs),
- '\x1b[1;7mHello, \x1b[0mworld\x1b[1;7m.')
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_transport.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_transport.py
deleted file mode 100644
index 70e116c..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_transport.py
+++ /dev/null
@@ -1,2195 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for ssh/transport.py and the classes therein.
-"""
-
-import struct
-
-try:
- import pyasn1
-except ImportError:
- pyasn1 = None
-
-try:
- import Crypto.Cipher.DES3
-except ImportError:
- Crypto = None
-
-if pyasn1 is not None and Crypto is not None:
- dependencySkip = None
- from twisted.conch.ssh import transport, keys, factory
- from twisted.conch.test import keydata
-else:
- if pyasn1 is None:
- dependencySkip = "Cannot run without PyASN1"
- elif Crypto is None:
- dependencySkip = "can't run w/o PyCrypto"
-
- class transport: # fictional modules to make classes work
- class SSHTransportBase: pass
- class SSHServerTransport: pass
- class SSHClientTransport: pass
- class factory:
- class SSHFactory:
- pass
-
-from hashlib import md5, sha1
-
-from twisted.trial import unittest
-from twisted.internet import defer
-from twisted.protocols import loopback
-from twisted.python import randbytes
-from twisted.python.reflect import getClass
-from twisted.conch.ssh import address, service, common
-from twisted.test import proto_helpers
-
-from twisted.conch.error import ConchError
-
-
-class MockTransportBase(transport.SSHTransportBase):
- """
- A base class for the client and server protocols. Stores the messages
- it receieves instead of ignoring them.
-
- @ivar errors: a list of tuples: (reasonCode, description)
- @ivar unimplementeds: a list of integers: sequence number
- @ivar debugs: a list of tuples: (alwaysDisplay, message, lang)
- @ivar ignoreds: a list of strings: ignored data
- """
-
- def connectionMade(self):
- """
- Set up instance variables.
- """
- transport.SSHTransportBase.connectionMade(self)
- self.errors = []
- self.unimplementeds = []
- self.debugs = []
- self.ignoreds = []
- self.gotUnsupportedVersion = None
-
-
- def _unsupportedVersionReceived(self, remoteVersion):
- """
- Intercept unsupported version call.
-
- @type remoteVersion: C{str}
- """
- self.gotUnsupportedVersion = remoteVersion
- return transport.SSHTransportBase._unsupportedVersionReceived(
- self, remoteVersion)
-
-
- def receiveError(self, reasonCode, description):
- """
- Store any errors received.
-
- @type reasonCode: C{int}
- @type description: C{str}
- """
- self.errors.append((reasonCode, description))
-
-
- def receiveUnimplemented(self, seqnum):
- """
- Store any unimplemented packet messages.
-
- @type seqnum: C{int}
- """
- self.unimplementeds.append(seqnum)
-
-
- def receiveDebug(self, alwaysDisplay, message, lang):
- """
- Store any debug messages.
-
- @type alwaysDisplay: C{bool}
- @type message: C{str}
- @type lang: C{str}
- """
- self.debugs.append((alwaysDisplay, message, lang))
-
-
- def ssh_IGNORE(self, packet):
- """
- Store any ignored data.
-
- @type packet: C{str}
- """
- self.ignoreds.append(packet)
-
-
-class MockCipher(object):
- """
- A mocked-up version of twisted.conch.ssh.transport.SSHCiphers.
- """
- outCipType = 'test'
- encBlockSize = 6
- inCipType = 'test'
- decBlockSize = 6
- inMACType = 'test'
- outMACType = 'test'
- verifyDigestSize = 1
- usedEncrypt = False
- usedDecrypt = False
- outMAC = (None, '', '', 1)
- inMAC = (None, '', '', 1)
- keys = ()
-
-
- def encrypt(self, x):
- """
- Called to encrypt the packet. Simply record that encryption was used
- and return the data unchanged.
- """
- self.usedEncrypt = True
- if (len(x) % self.encBlockSize) != 0:
- raise RuntimeError("length %i modulo blocksize %i is not 0: %i" %
- (len(x), self.encBlockSize, len(x) % self.encBlockSize))
- return x
-
-
- def decrypt(self, x):
- """
- Called to decrypt the packet. Simply record that decryption was used
- and return the data unchanged.
- """
- self.usedDecrypt = True
- if (len(x) % self.encBlockSize) != 0:
- raise RuntimeError("length %i modulo blocksize %i is not 0: %i" %
- (len(x), self.decBlockSize, len(x) % self.decBlockSize))
- return x
-
-
- def makeMAC(self, outgoingPacketSequence, payload):
- """
- Make a Message Authentication Code by sending the character value of
- the outgoing packet.
- """
- return chr(outgoingPacketSequence)
-
-
- def verify(self, incomingPacketSequence, packet, macData):
- """
- Verify the Message Authentication Code by checking that the packet
- sequence number is the same.
- """
- return chr(incomingPacketSequence) == macData
-
-
- def setKeys(self, ivOut, keyOut, ivIn, keyIn, macIn, macOut):
- """
- Record the keys.
- """
- self.keys = (ivOut, keyOut, ivIn, keyIn, macIn, macOut)
-
-
-
-class MockCompression:
- """
- A mocked-up compression, based on the zlib interface. Instead of
- compressing, it reverses the data and adds a 0x66 byte to the end.
- """
-
-
- def compress(self, payload):
- return payload[::-1] # reversed
-
-
- def decompress(self, payload):
- return payload[:-1][::-1]
-
-
- def flush(self, kind):
- return '\x66'
-
-
-
-class MockService(service.SSHService):
- """
- A mocked-up service, based on twisted.conch.ssh.service.SSHService.
-
- @ivar started: True if this service has been started.
- @ivar stopped: True if this service has been stopped.
- """
- name = "MockService"
- started = False
- stopped = False
- protocolMessages = {0xff: "MSG_TEST", 71: "MSG_fiction"}
-
-
- def logPrefix(self):
- return "MockService"
-
-
- def serviceStarted(self):
- """
- Record that the service was started.
- """
- self.started = True
-
-
- def serviceStopped(self):
- """
- Record that the service was stopped.
- """
- self.stopped = True
-
-
- def ssh_TEST(self, packet):
- """
- A message that this service responds to.
- """
- self.transport.sendPacket(0xff, packet)
-
-
-class MockFactory(factory.SSHFactory):
- """
- A mocked-up factory based on twisted.conch.ssh.factory.SSHFactory.
- """
- services = {
- 'ssh-userauth': MockService}
-
-
- def getPublicKeys(self):
- """
- Return the public keys that authenticate this server.
- """
- return {
- 'ssh-rsa': keys.Key.fromString(keydata.publicRSA_openssh),
- 'ssh-dsa': keys.Key.fromString(keydata.publicDSA_openssh)}
-
-
- def getPrivateKeys(self):
- """
- Return the private keys that authenticate this server.
- """
- return {
- 'ssh-rsa': keys.Key.fromString(keydata.privateRSA_openssh),
- 'ssh-dsa': keys.Key.fromString(keydata.privateDSA_openssh)}
-
-
- def getPrimes(self):
- """
- Return the Diffie-Hellman primes that can be used for the
- diffie-hellman-group-exchange-sha1 key exchange.
- """
- return {
- 1024: ((2, transport.DH_PRIME),),
- 2048: ((3, transport.DH_PRIME),),
- 4096: ((5, 7),)}
-
-
-
-class MockOldFactoryPublicKeys(MockFactory):
- """
- The old SSHFactory returned mappings from key names to strings from
- getPublicKeys(). We return those here for testing.
- """
-
-
- def getPublicKeys(self):
- """
- We used to map key types to public key blobs as strings.
- """
- keys = MockFactory.getPublicKeys(self)
- for name, key in keys.items()[:]:
- keys[name] = key.blob()
- return keys
-
-
-
-class MockOldFactoryPrivateKeys(MockFactory):
- """
- The old SSHFactory returned mappings from key names to PyCrypto key
- objects from getPrivateKeys(). We return those here for testing.
- """
-
-
- def getPrivateKeys(self):
- """
- We used to map key types to PyCrypto key objects.
- """
- keys = MockFactory.getPrivateKeys(self)
- for name, key in keys.items()[:]:
- keys[name] = key.keyObject
- return keys
-
-
-class TransportTestCase(unittest.TestCase):
- """
- Base class for transport test cases.
- """
- klass = None
-
- if dependencySkip:
- skip = dependencySkip
-
- def setUp(self):
- self.transport = proto_helpers.StringTransport()
- self.proto = self.klass()
- self.packets = []
- def secureRandom(len):
- """
- Return a consistent entropy value
- """
- return '\x99' * len
- self.oldSecureRandom = randbytes.secureRandom
- randbytes.secureRandom = secureRandom
- def stubSendPacket(messageType, payload):
- self.packets.append((messageType, payload))
- self.proto.makeConnection(self.transport)
- # we just let the kex packet go into the transport
- self.proto.sendPacket = stubSendPacket
-
-
- def finishKeyExchange(self, proto):
- """
- Deliver enough additional messages to C{proto} so that the key exchange
- which is started in L{SSHTransportBase.connectionMade} completes and
- non-key exchange messages can be sent and received.
- """
- proto.dataReceived("SSH-2.0-BogoClient-1.2i\r\n")
- proto.dispatchMessage(
- transport.MSG_KEXINIT, self._A_KEXINIT_MESSAGE)
- proto._keySetup("foo", "bar")
- # SSHTransportBase can't handle MSG_NEWKEYS, or it would be the right
- # thing to deliver next. _newKeys won't work either, because
- # sendKexInit (probably) hasn't been called. sendKexInit is
- # responsible for setting up certain state _newKeys relies on. So,
- # just change the key exchange state to what it would be when key
- # exchange is finished.
- proto._keyExchangeState = proto._KEY_EXCHANGE_NONE
-
-
- def tearDown(self):
- randbytes.secureRandom = self.oldSecureRandom
- self.oldSecureRandom = None
-
-
- def simulateKeyExchange(self, sharedSecret, exchangeHash):
- """
- Finish a key exchange by calling C{_keySetup} with the given arguments.
- Also do extra whitebox stuff to satisfy that method's assumption that
- some kind of key exchange has actually taken place.
- """
- self.proto._keyExchangeState = self.proto._KEY_EXCHANGE_REQUESTED
- self.proto._blockedByKeyExchange = []
- self.proto._keySetup(sharedSecret, exchangeHash)
-
-
-
-class BaseSSHTransportTestCase(TransportTestCase):
- """
- Test TransportBase. It implements the non-server/client specific
- parts of the SSH transport protocol.
- """
-
- klass = MockTransportBase
-
- _A_KEXINIT_MESSAGE = (
- "\xAA" * 16 +
- common.NS('diffie-hellman-group1-sha1') +
- common.NS('ssh-rsa') +
- common.NS('aes256-ctr') +
- common.NS('aes256-ctr') +
- common.NS('hmac-sha1') +
- common.NS('hmac-sha1') +
- common.NS('none') +
- common.NS('none') +
- common.NS('') +
- common.NS('') +
- '\x00' + '\x00\x00\x00\x00')
-
- def test_sendVersion(self):
- """
- Test that the first thing sent over the connection is the version
- string.
- """
- # the other setup was done in the setup method
- self.assertEqual(self.transport.value().split('\r\n', 1)[0],
- "SSH-2.0-Twisted")
-
-
- def test_sendPacketPlain(self):
- """
- Test that plain (unencrypted, uncompressed) packets are sent
- correctly. The format is::
- uint32 length (including type and padding length)
- byte padding length
- byte type
- bytes[length-padding length-2] data
- bytes[padding length] padding
- """
- proto = MockTransportBase()
- proto.makeConnection(self.transport)
- self.finishKeyExchange(proto)
- self.transport.clear()
- message = ord('A')
- payload = 'BCDEFG'
- proto.sendPacket(message, payload)
- value = self.transport.value()
- self.assertEqual(value, '\x00\x00\x00\x0c\x04ABCDEFG\x99\x99\x99\x99')
-
-
- def test_sendPacketEncrypted(self):
- """
- Test that packets sent while encryption is enabled are sent
- correctly. The whole packet should be encrypted.
- """
- proto = MockTransportBase()
- proto.makeConnection(self.transport)
- self.finishKeyExchange(proto)
- proto.currentEncryptions = testCipher = MockCipher()
- message = ord('A')
- payload = 'BC'
- self.transport.clear()
- proto.sendPacket(message, payload)
- self.assertTrue(testCipher.usedEncrypt)
- value = self.transport.value()
- self.assertEqual(
- value,
- # Four byte length prefix
- '\x00\x00\x00\x08'
- # One byte padding length
- '\x04'
- # The actual application data
- 'ABC'
- # "Random" padding - see the secureRandom monkeypatch in setUp
- '\x99\x99\x99\x99'
- # The MAC
- '\x02')
-
-
- def test_sendPacketCompressed(self):
- """
- Test that packets sent while compression is enabled are sent
- correctly. The packet type and data should be encrypted.
- """
- proto = MockTransportBase()
- proto.makeConnection(self.transport)
- self.finishKeyExchange(proto)
- proto.outgoingCompression = MockCompression()
- self.transport.clear()
- proto.sendPacket(ord('A'), 'B')
- value = self.transport.value()
- self.assertEqual(
- value,
- '\x00\x00\x00\x0c\x08BA\x66\x99\x99\x99\x99\x99\x99\x99\x99')
-
-
- def test_sendPacketBoth(self):
- """
- Test that packets sent while compression and encryption are
- enabled are sent correctly. The packet type and data should be
- compressed and then the whole packet should be encrypted.
- """
- proto = MockTransportBase()
- proto.makeConnection(self.transport)
- self.finishKeyExchange(proto)
- proto.currentEncryptions = testCipher = MockCipher()
- proto.outgoingCompression = MockCompression()
- message = ord('A')
- payload = 'BC'
- self.transport.clear()
- proto.sendPacket(message, payload)
- self.assertTrue(testCipher.usedEncrypt)
- value = self.transport.value()
- self.assertEqual(
- value,
- # Four byte length prefix
- '\x00\x00\x00\x0e'
- # One byte padding length
- '\x09'
- # Compressed application data
- 'CBA\x66'
- # "Random" padding - see the secureRandom monkeypatch in setUp
- '\x99\x99\x99\x99\x99\x99\x99\x99\x99'
- # The MAC
- '\x02')
-
-
- def test_getPacketPlain(self):
- """
- Test that packets are retrieved correctly out of the buffer when
- no encryption is enabled.
- """
- proto = MockTransportBase()
- proto.makeConnection(self.transport)
- self.finishKeyExchange(proto)
- self.transport.clear()
- proto.sendPacket(ord('A'), 'BC')
- proto.buf = self.transport.value() + 'extra'
- self.assertEqual(proto.getPacket(), 'ABC')
- self.assertEqual(proto.buf, 'extra')
-
-
- def test_getPacketEncrypted(self):
- """
- Test that encrypted packets are retrieved correctly.
- See test_sendPacketEncrypted.
- """
- proto = MockTransportBase()
- proto.sendKexInit = lambda: None # don't send packets
- proto.makeConnection(self.transport)
- self.transport.clear()
- proto.currentEncryptions = testCipher = MockCipher()
- proto.sendPacket(ord('A'), 'BCD')
- value = self.transport.value()
- proto.buf = value[:MockCipher.decBlockSize]
- self.assertEqual(proto.getPacket(), None)
- self.assertTrue(testCipher.usedDecrypt)
- self.assertEqual(proto.first, '\x00\x00\x00\x0e\x09A')
- proto.buf += value[MockCipher.decBlockSize:]
- self.assertEqual(proto.getPacket(), 'ABCD')
- self.assertEqual(proto.buf, '')
-
-
- def test_getPacketCompressed(self):
- """
- Test that compressed packets are retrieved correctly. See
- test_sendPacketCompressed.
- """
- proto = MockTransportBase()
- proto.makeConnection(self.transport)
- self.finishKeyExchange(proto)
- self.transport.clear()
- proto.outgoingCompression = MockCompression()
- proto.incomingCompression = proto.outgoingCompression
- proto.sendPacket(ord('A'), 'BCD')
- proto.buf = self.transport.value()
- self.assertEqual(proto.getPacket(), 'ABCD')
-
-
- def test_getPacketBoth(self):
- """
- Test that compressed and encrypted packets are retrieved correctly.
- See test_sendPacketBoth.
- """
- proto = MockTransportBase()
- proto.sendKexInit = lambda: None
- proto.makeConnection(self.transport)
- self.transport.clear()
- proto.currentEncryptions = MockCipher()
- proto.outgoingCompression = MockCompression()
- proto.incomingCompression = proto.outgoingCompression
- proto.sendPacket(ord('A'), 'BCDEFG')
- proto.buf = self.transport.value()
- self.assertEqual(proto.getPacket(), 'ABCDEFG')
-
-
- def test_ciphersAreValid(self):
- """
- Test that all the supportedCiphers are valid.
- """
- ciphers = transport.SSHCiphers('A', 'B', 'C', 'D')
- iv = key = '\x00' * 16
- for cipName in self.proto.supportedCiphers:
- self.assertTrue(ciphers._getCipher(cipName, iv, key))
-
-
- def test_sendKexInit(self):
- """
- Test that the KEXINIT (key exchange initiation) message is sent
- correctly. Payload::
- bytes[16] cookie
- string key exchange algorithms
- string public key algorithms
- string outgoing ciphers
- string incoming ciphers
- string outgoing MACs
- string incoming MACs
- string outgoing compressions
- string incoming compressions
- bool first packet follows
- uint32 0
- """
- value = self.transport.value().split('\r\n', 1)[1]
- self.proto.buf = value
- packet = self.proto.getPacket()
- self.assertEqual(packet[0], chr(transport.MSG_KEXINIT))
- self.assertEqual(packet[1:17], '\x99' * 16)
- (kex, pubkeys, ciphers1, ciphers2, macs1, macs2, compressions1,
- compressions2, languages1, languages2,
- buf) = common.getNS(packet[17:], 10)
-
- self.assertEqual(kex, ','.join(self.proto.supportedKeyExchanges))
- self.assertEqual(pubkeys, ','.join(self.proto.supportedPublicKeys))
- self.assertEqual(ciphers1, ','.join(self.proto.supportedCiphers))
- self.assertEqual(ciphers2, ','.join(self.proto.supportedCiphers))
- self.assertEqual(macs1, ','.join(self.proto.supportedMACs))
- self.assertEqual(macs2, ','.join(self.proto.supportedMACs))
- self.assertEqual(compressions1,
- ','.join(self.proto.supportedCompressions))
- self.assertEqual(compressions2,
- ','.join(self.proto.supportedCompressions))
- self.assertEqual(languages1, ','.join(self.proto.supportedLanguages))
- self.assertEqual(languages2, ','.join(self.proto.supportedLanguages))
- self.assertEqual(buf, '\x00' * 5)
-
-
- def test_receiveKEXINITReply(self):
- """
- Immediately after connecting, the transport expects a KEXINIT message
- and does not reply to it.
- """
- self.transport.clear()
- self.proto.dispatchMessage(
- transport.MSG_KEXINIT, self._A_KEXINIT_MESSAGE)
- self.assertEqual(self.packets, [])
-
-
- def test_sendKEXINITReply(self):
- """
- When a KEXINIT message is received which is not a reply to an earlier
- KEXINIT message which was sent, a KEXINIT reply is sent.
- """
- self.finishKeyExchange(self.proto)
- del self.packets[:]
-
- self.proto.dispatchMessage(
- transport.MSG_KEXINIT, self._A_KEXINIT_MESSAGE)
- self.assertEqual(len(self.packets), 1)
- self.assertEqual(self.packets[0][0], transport.MSG_KEXINIT)
-
-
- def test_sendKexInitTwiceFails(self):
- """
- A new key exchange cannot be started while a key exchange is already in
- progress. If an attempt is made to send a I{KEXINIT} message using
- L{SSHTransportBase.sendKexInit} while a key exchange is in progress
- causes that method to raise a L{RuntimeError}.
- """
- self.assertRaises(RuntimeError, self.proto.sendKexInit)
-
-
- def test_sendKexInitBlocksOthers(self):
- """
- After L{SSHTransportBase.sendKexInit} has been called, messages types
- other than the following are queued and not sent until after I{NEWKEYS}
- is sent by L{SSHTransportBase._keySetup}.
-
- RFC 4253, section 7.1.
- """
- # sendKexInit is called by connectionMade, which is called in setUp.
- # So we're in the state already.
- disallowedMessageTypes = [
- transport.MSG_SERVICE_REQUEST,
- transport.MSG_KEXINIT,
- ]
-
- # Drop all the bytes sent by setUp, they're not relevant to this test.
- self.transport.clear()
-
- # Get rid of the sendPacket monkey patch, we are testing the behavior
- # of sendPacket.
- del self.proto.sendPacket
-
- for messageType in disallowedMessageTypes:
- self.proto.sendPacket(messageType, 'foo')
- self.assertEqual(self.transport.value(), "")
-
- self.finishKeyExchange(self.proto)
- # Make the bytes written to the transport cleartext so it's easier to
- # make an assertion about them.
- self.proto.nextEncryptions = MockCipher()
-
- # Pseudo-deliver the peer's NEWKEYS message, which should flush the
- # messages which were queued above.
- self.proto._newKeys()
- self.assertEqual(self.transport.value().count("foo"), 2)
-
-
- def test_sendDebug(self):
- """
- Test that debug messages are sent correctly. Payload::
- bool always display
- string debug message
- string language
- """
- self.proto.sendDebug("test", True, 'en')
- self.assertEqual(
- self.packets,
- [(transport.MSG_DEBUG,
- "\x01\x00\x00\x00\x04test\x00\x00\x00\x02en")])
-
-
- def test_receiveDebug(self):
- """
- Test that debug messages are received correctly. See test_sendDebug.
- """
- self.proto.dispatchMessage(
- transport.MSG_DEBUG,
- '\x01\x00\x00\x00\x04test\x00\x00\x00\x02en')
- self.assertEqual(self.proto.debugs, [(True, 'test', 'en')])
-
-
- def test_sendIgnore(self):
- """
- Test that ignored messages are sent correctly. Payload::
- string ignored data
- """
- self.proto.sendIgnore("test")
- self.assertEqual(
- self.packets, [(transport.MSG_IGNORE,
- '\x00\x00\x00\x04test')])
-
-
- def test_receiveIgnore(self):
- """
- Test that ignored messages are received correctly. See
- test_sendIgnore.
- """
- self.proto.dispatchMessage(transport.MSG_IGNORE, 'test')
- self.assertEqual(self.proto.ignoreds, ['test'])
-
-
- def test_sendUnimplemented(self):
- """
- Test that unimplemented messages are sent correctly. Payload::
- uint32 sequence number
- """
- self.proto.sendUnimplemented()
- self.assertEqual(
- self.packets, [(transport.MSG_UNIMPLEMENTED,
- '\x00\x00\x00\x00')])
-
-
- def test_receiveUnimplemented(self):
- """
- Test that unimplemented messages are received correctly. See
- test_sendUnimplemented.
- """
- self.proto.dispatchMessage(transport.MSG_UNIMPLEMENTED,
- '\x00\x00\x00\xff')
- self.assertEqual(self.proto.unimplementeds, [255])
-
-
- def test_sendDisconnect(self):
- """
- Test that disconnection messages are sent correctly. Payload::
- uint32 reason code
- string reason description
- string language
- """
- disconnected = [False]
- def stubLoseConnection():
- disconnected[0] = True
- self.transport.loseConnection = stubLoseConnection
- self.proto.sendDisconnect(0xff, "test")
- self.assertEqual(
- self.packets,
- [(transport.MSG_DISCONNECT,
- "\x00\x00\x00\xff\x00\x00\x00\x04test\x00\x00\x00\x00")])
- self.assertTrue(disconnected[0])
-
-
- def test_receiveDisconnect(self):
- """
- Test that disconnection messages are received correctly. See
- test_sendDisconnect.
- """
- disconnected = [False]
- def stubLoseConnection():
- disconnected[0] = True
- self.transport.loseConnection = stubLoseConnection
- self.proto.dispatchMessage(transport.MSG_DISCONNECT,
- '\x00\x00\x00\xff\x00\x00\x00\x04test')
- self.assertEqual(self.proto.errors, [(255, 'test')])
- self.assertTrue(disconnected[0])
-
-
- def test_dataReceived(self):
- """
- Test that dataReceived parses packets and dispatches them to
- ssh_* methods.
- """
- kexInit = [False]
- def stubKEXINIT(packet):
- kexInit[0] = True
- self.proto.ssh_KEXINIT = stubKEXINIT
- self.proto.dataReceived(self.transport.value())
- self.assertTrue(self.proto.gotVersion)
- self.assertEqual(self.proto.ourVersionString,
- self.proto.otherVersionString)
- self.assertTrue(kexInit[0])
-
-
- def test_service(self):
- """
- Test that the transport can set the running service and dispatches
- packets to the service's packetReceived method.
- """
- service = MockService()
- self.proto.setService(service)
- self.assertEqual(self.proto.service, service)
- self.assertTrue(service.started)
- self.proto.dispatchMessage(0xff, "test")
- self.assertEqual(self.packets, [(0xff, "test")])
-
- service2 = MockService()
- self.proto.setService(service2)
- self.assertTrue(service2.started)
- self.assertTrue(service.stopped)
-
- self.proto.connectionLost(None)
- self.assertTrue(service2.stopped)
-
-
- def test_avatar(self):
- """
- Test that the transport notifies the avatar of disconnections.
- """
- disconnected = [False]
- def logout():
- disconnected[0] = True
- self.proto.logoutFunction = logout
- self.proto.avatar = True
-
- self.proto.connectionLost(None)
- self.assertTrue(disconnected[0])
-
-
- def test_isEncrypted(self):
- """
- Test that the transport accurately reflects its encrypted status.
- """
- self.assertFalse(self.proto.isEncrypted('in'))
- self.assertFalse(self.proto.isEncrypted('out'))
- self.assertFalse(self.proto.isEncrypted('both'))
- self.proto.currentEncryptions = MockCipher()
- self.assertTrue(self.proto.isEncrypted('in'))
- self.assertTrue(self.proto.isEncrypted('out'))
- self.assertTrue(self.proto.isEncrypted('both'))
- self.proto.currentEncryptions = transport.SSHCiphers('none', 'none',
- 'none', 'none')
- self.assertFalse(self.proto.isEncrypted('in'))
- self.assertFalse(self.proto.isEncrypted('out'))
- self.assertFalse(self.proto.isEncrypted('both'))
-
- self.assertRaises(TypeError, self.proto.isEncrypted, 'bad')
-
-
- def test_isVerified(self):
- """
- Test that the transport accurately reflects its verified status.
- """
- self.assertFalse(self.proto.isVerified('in'))
- self.assertFalse(self.proto.isVerified('out'))
- self.assertFalse(self.proto.isVerified('both'))
- self.proto.currentEncryptions = MockCipher()
- self.assertTrue(self.proto.isVerified('in'))
- self.assertTrue(self.proto.isVerified('out'))
- self.assertTrue(self.proto.isVerified('both'))
- self.proto.currentEncryptions = transport.SSHCiphers('none', 'none',
- 'none', 'none')
- self.assertFalse(self.proto.isVerified('in'))
- self.assertFalse(self.proto.isVerified('out'))
- self.assertFalse(self.proto.isVerified('both'))
-
- self.assertRaises(TypeError, self.proto.isVerified, 'bad')
-
-
- def test_loseConnection(self):
- """
- Test that loseConnection sends a disconnect message and closes the
- connection.
- """
- disconnected = [False]
- def stubLoseConnection():
- disconnected[0] = True
- self.transport.loseConnection = stubLoseConnection
- self.proto.loseConnection()
- self.assertEqual(self.packets[0][0], transport.MSG_DISCONNECT)
- self.assertEqual(self.packets[0][1][3],
- chr(transport.DISCONNECT_CONNECTION_LOST))
-
-
- def test_badVersion(self):
- """
- Test that the transport disconnects when it receives a bad version.
- """
- def testBad(version):
- self.packets = []
- self.proto.gotVersion = False
- disconnected = [False]
- def stubLoseConnection():
- disconnected[0] = True
- self.transport.loseConnection = stubLoseConnection
- for c in version + '\r\n':
- self.proto.dataReceived(c)
- self.assertTrue(disconnected[0])
- self.assertEqual(self.packets[0][0], transport.MSG_DISCONNECT)
- self.assertEqual(
- self.packets[0][1][3],
- chr(transport.DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED))
- testBad('SSH-1.5-OpenSSH')
- testBad('SSH-3.0-Twisted')
- testBad('GET / HTTP/1.1')
-
-
- def test_dataBeforeVersion(self):
- """
- Test that the transport ignores data sent before the version string.
- """
- proto = MockTransportBase()
- proto.makeConnection(proto_helpers.StringTransport())
- data = ("""here's some stuff beforehand
-here's some other stuff
-""" + proto.ourVersionString + "\r\n")
- [proto.dataReceived(c) for c in data]
- self.assertTrue(proto.gotVersion)
- self.assertEqual(proto.otherVersionString, proto.ourVersionString)
-
-
- def test_compatabilityVersion(self):
- """
- Test that the transport treats the compatbility version (1.99)
- as equivalent to version 2.0.
- """
- proto = MockTransportBase()
- proto.makeConnection(proto_helpers.StringTransport())
- proto.dataReceived("SSH-1.99-OpenSSH\n")
- self.assertTrue(proto.gotVersion)
- self.assertEqual(proto.otherVersionString, "SSH-1.99-OpenSSH")
-
-
- def test_supportedVersionsAreAllowed(self):
- """
- If an unusual SSH version is received and is included in
- C{supportedVersions}, an unsupported version error is not emitted.
- """
- proto = MockTransportBase()
- proto.supportedVersions = ("9.99", )
- proto.makeConnection(proto_helpers.StringTransport())
- proto.dataReceived("SSH-9.99-OpenSSH\n")
- self.assertFalse(proto.gotUnsupportedVersion)
-
-
- def test_unsupportedVersionsCallUnsupportedVersionReceived(self):
- """
- If an unusual SSH version is received and is not included in
- C{supportedVersions}, an unsupported version error is emitted.
- """
- proto = MockTransportBase()
- proto.supportedVersions = ("2.0", )
- proto.makeConnection(proto_helpers.StringTransport())
- proto.dataReceived("SSH-9.99-OpenSSH\n")
- self.assertEqual("9.99", proto.gotUnsupportedVersion)
-
-
- def test_badPackets(self):
- """
- Test that the transport disconnects with an error when it receives
- bad packets.
- """
- def testBad(packet, error=transport.DISCONNECT_PROTOCOL_ERROR):
- self.packets = []
- self.proto.buf = packet
- self.assertEqual(self.proto.getPacket(), None)
- self.assertEqual(len(self.packets), 1)
- self.assertEqual(self.packets[0][0], transport.MSG_DISCONNECT)
- self.assertEqual(self.packets[0][1][3], chr(error))
-
- testBad('\xff' * 8) # big packet
- testBad('\x00\x00\x00\x05\x00BCDE') # length not modulo blocksize
- oldEncryptions = self.proto.currentEncryptions
- self.proto.currentEncryptions = MockCipher()
- testBad('\x00\x00\x00\x08\x06AB123456', # bad MAC
- transport.DISCONNECT_MAC_ERROR)
- self.proto.currentEncryptions.decrypt = lambda x: x[:-1]
- testBad('\x00\x00\x00\x08\x06BCDEFGHIJK') # bad decryption
- self.proto.currentEncryptions = oldEncryptions
- self.proto.incomingCompression = MockCompression()
- def stubDecompress(payload):
- raise Exception('bad compression')
- self.proto.incomingCompression.decompress = stubDecompress
- testBad('\x00\x00\x00\x04\x00BCDE', # bad decompression
- transport.DISCONNECT_COMPRESSION_ERROR)
- self.flushLoggedErrors()
-
-
- def test_unimplementedPackets(self):
- """
- Test that unimplemented packet types cause MSG_UNIMPLEMENTED packets
- to be sent.
- """
- seqnum = self.proto.incomingPacketSequence
- def checkUnimplemented(seqnum=seqnum):
- self.assertEqual(self.packets[0][0],
- transport.MSG_UNIMPLEMENTED)
- self.assertEqual(self.packets[0][1][3], chr(seqnum))
- self.proto.packets = []
- seqnum += 1
-
- self.proto.dispatchMessage(40, '')
- checkUnimplemented()
- transport.messages[41] = 'MSG_fiction'
- self.proto.dispatchMessage(41, '')
- checkUnimplemented()
- self.proto.dispatchMessage(60, '')
- checkUnimplemented()
- self.proto.setService(MockService())
- self.proto.dispatchMessage(70, '')
- checkUnimplemented()
- self.proto.dispatchMessage(71, '')
- checkUnimplemented()
-
-
- def test_getKey(self):
- """
- Test that _getKey generates the correct keys.
- """
- self.proto.sessionID = 'EF'
-
- k1 = sha1('AB' + 'CD' + 'K' + self.proto.sessionID).digest()
- k2 = sha1('ABCD' + k1).digest()
- self.assertEqual(self.proto._getKey('K', 'AB', 'CD'), k1 + k2)
-
-
- def test_multipleClasses(self):
- """
- Test that multiple instances have distinct states.
- """
- proto = self.proto
- proto.dataReceived(self.transport.value())
- proto.currentEncryptions = MockCipher()
- proto.outgoingCompression = MockCompression()
- proto.incomingCompression = MockCompression()
- proto.setService(MockService())
- proto2 = MockTransportBase()
- proto2.makeConnection(proto_helpers.StringTransport())
- proto2.sendIgnore('')
- self.assertNotEqual(proto.gotVersion, proto2.gotVersion)
- self.assertNotEqual(proto.transport, proto2.transport)
- self.assertNotEqual(proto.outgoingPacketSequence,
- proto2.outgoingPacketSequence)
- self.assertNotEqual(proto.incomingPacketSequence,
- proto2.incomingPacketSequence)
- self.assertNotEqual(proto.currentEncryptions,
- proto2.currentEncryptions)
- self.assertNotEqual(proto.service, proto2.service)
-
-
-
-class ServerAndClientSSHTransportBaseCase:
- """
- Tests that need to be run on both the server and the client.
- """
-
-
- def checkDisconnected(self, kind=None):
- """
- Helper function to check if the transport disconnected.
- """
- if kind is None:
- kind = transport.DISCONNECT_PROTOCOL_ERROR
- self.assertEqual(self.packets[-1][0], transport.MSG_DISCONNECT)
- self.assertEqual(self.packets[-1][1][3], chr(kind))
-
-
- def connectModifiedProtocol(self, protoModification,
- kind=None):
- """
- Helper function to connect a modified protocol to the test protocol
- and test for disconnection.
- """
- if kind is None:
- kind = transport.DISCONNECT_KEY_EXCHANGE_FAILED
- proto2 = self.klass()
- protoModification(proto2)
- proto2.makeConnection(proto_helpers.StringTransport())
- self.proto.dataReceived(proto2.transport.value())
- if kind:
- self.checkDisconnected(kind)
- return proto2
-
-
- def test_disconnectIfCantMatchKex(self):
- """
- Test that the transport disconnects if it can't match the key
- exchange
- """
- def blankKeyExchanges(proto2):
- proto2.supportedKeyExchanges = []
- self.connectModifiedProtocol(blankKeyExchanges)
-
-
- def test_disconnectIfCantMatchKeyAlg(self):
- """
- Like test_disconnectIfCantMatchKex, but for the key algorithm.
- """
- def blankPublicKeys(proto2):
- proto2.supportedPublicKeys = []
- self.connectModifiedProtocol(blankPublicKeys)
-
-
- def test_disconnectIfCantMatchCompression(self):
- """
- Like test_disconnectIfCantMatchKex, but for the compression.
- """
- def blankCompressions(proto2):
- proto2.supportedCompressions = []
- self.connectModifiedProtocol(blankCompressions)
-
-
- def test_disconnectIfCantMatchCipher(self):
- """
- Like test_disconnectIfCantMatchKex, but for the encryption.
- """
- def blankCiphers(proto2):
- proto2.supportedCiphers = []
- self.connectModifiedProtocol(blankCiphers)
-
-
- def test_disconnectIfCantMatchMAC(self):
- """
- Like test_disconnectIfCantMatchKex, but for the MAC.
- """
- def blankMACs(proto2):
- proto2.supportedMACs = []
- self.connectModifiedProtocol(blankMACs)
-
- def test_getPeer(self):
- """
- Test that the transport's L{getPeer} method returns an
- L{SSHTransportAddress} with the L{IAddress} of the peer.
- """
- self.assertEqual(self.proto.getPeer(),
- address.SSHTransportAddress(
- self.proto.transport.getPeer()))
-
- def test_getHost(self):
- """
- Test that the transport's L{getHost} method returns an
- L{SSHTransportAddress} with the L{IAddress} of the host.
- """
- self.assertEqual(self.proto.getHost(),
- address.SSHTransportAddress(
- self.proto.transport.getHost()))
-
-
-
-class ServerSSHTransportTestCase(ServerAndClientSSHTransportBaseCase,
- TransportTestCase):
- """
- Tests for the SSHServerTransport.
- """
-
- klass = transport.SSHServerTransport
-
-
- def setUp(self):
- TransportTestCase.setUp(self)
- self.proto.factory = MockFactory()
- self.proto.factory.startFactory()
-
-
- def tearDown(self):
- TransportTestCase.tearDown(self)
- self.proto.factory.stopFactory()
- del self.proto.factory
-
-
- def test_KEXINIT(self):
- """
- Test that receiving a KEXINIT packet sets up the correct values on the
- server.
- """
- self.proto.dataReceived( 'SSH-2.0-Twisted\r\n\x00\x00\x01\xd4\t\x14'
- '\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99'
- '\x99\x00\x00\x00=diffie-hellman-group1-sha1,diffie-hellman-g'
- 'roup-exchange-sha1\x00\x00\x00\x0fssh-dss,ssh-rsa\x00\x00\x00'
- '\x85aes128-ctr,aes128-cbc,aes192-ctr,aes192-cbc,aes256-ctr,ae'
- 's256-cbc,cast128-ctr,cast128-cbc,blowfish-ctr,blowfish-cbc,3d'
- 'es-ctr,3des-cbc\x00\x00\x00\x85aes128-ctr,aes128-cbc,aes192-c'
- 'tr,aes192-cbc,aes256-ctr,aes256-cbc,cast128-ctr,cast128-cbc,b'
- 'lowfish-ctr,blowfish-cbc,3des-ctr,3des-cbc\x00\x00\x00\x12hma'
- 'c-md5,hmac-sha1\x00\x00\x00\x12hmac-md5,hmac-sha1\x00\x00\x00'
- '\tnone,zlib\x00\x00\x00\tnone,zlib\x00\x00\x00\x00\x00\x00'
- '\x00\x00\x00\x00\x00\x00\x00\x99\x99\x99\x99\x99\x99\x99\x99'
- '\x99')
- self.assertEqual(self.proto.kexAlg,
- 'diffie-hellman-group1-sha1')
- self.assertEqual(self.proto.keyAlg,
- 'ssh-dss')
- self.assertEqual(self.proto.outgoingCompressionType,
- 'none')
- self.assertEqual(self.proto.incomingCompressionType,
- 'none')
- ne = self.proto.nextEncryptions
- self.assertEqual(ne.outCipType, 'aes128-ctr')
- self.assertEqual(ne.inCipType, 'aes128-ctr')
- self.assertEqual(ne.outMACType, 'hmac-md5')
- self.assertEqual(ne.inMACType, 'hmac-md5')
-
-
- def test_ignoreGuessPacketKex(self):
- """
- The client is allowed to send a guessed key exchange packet
- after it sends the KEXINIT packet. However, if the key exchanges
- do not match, that guess packet must be ignored. This tests that
- the packet is ignored in the case of the key exchange method not
- matching.
- """
- kexInitPacket = '\x00' * 16 + (
- ''.join([common.NS(x) for x in
- [','.join(y) for y in
- [self.proto.supportedKeyExchanges[::-1],
- self.proto.supportedPublicKeys,
- self.proto.supportedCiphers,
- self.proto.supportedCiphers,
- self.proto.supportedMACs,
- self.proto.supportedMACs,
- self.proto.supportedCompressions,
- self.proto.supportedCompressions,
- self.proto.supportedLanguages,
- self.proto.supportedLanguages]]])) + (
- '\xff\x00\x00\x00\x00')
- self.proto.ssh_KEXINIT(kexInitPacket)
- self.assertTrue(self.proto.ignoreNextPacket)
- self.proto.ssh_DEBUG("\x01\x00\x00\x00\x04test\x00\x00\x00\x00")
- self.assertTrue(self.proto.ignoreNextPacket)
-
-
- self.proto.ssh_KEX_DH_GEX_REQUEST_OLD('\x00\x00\x08\x00')
- self.assertFalse(self.proto.ignoreNextPacket)
- self.assertEqual(self.packets, [])
- self.proto.ignoreNextPacket = True
-
- self.proto.ssh_KEX_DH_GEX_REQUEST('\x00\x00\x08\x00' * 3)
- self.assertFalse(self.proto.ignoreNextPacket)
- self.assertEqual(self.packets, [])
-
-
- def test_ignoreGuessPacketKey(self):
- """
- Like test_ignoreGuessPacketKex, but for an incorrectly guessed
- public key format.
- """
- kexInitPacket = '\x00' * 16 + (
- ''.join([common.NS(x) for x in
- [','.join(y) for y in
- [self.proto.supportedKeyExchanges,
- self.proto.supportedPublicKeys[::-1],
- self.proto.supportedCiphers,
- self.proto.supportedCiphers,
- self.proto.supportedMACs,
- self.proto.supportedMACs,
- self.proto.supportedCompressions,
- self.proto.supportedCompressions,
- self.proto.supportedLanguages,
- self.proto.supportedLanguages]]])) + (
- '\xff\x00\x00\x00\x00')
- self.proto.ssh_KEXINIT(kexInitPacket)
- self.assertTrue(self.proto.ignoreNextPacket)
- self.proto.ssh_DEBUG("\x01\x00\x00\x00\x04test\x00\x00\x00\x00")
- self.assertTrue(self.proto.ignoreNextPacket)
-
- self.proto.ssh_KEX_DH_GEX_REQUEST_OLD('\x00\x00\x08\x00')
- self.assertFalse(self.proto.ignoreNextPacket)
- self.assertEqual(self.packets, [])
- self.proto.ignoreNextPacket = True
-
- self.proto.ssh_KEX_DH_GEX_REQUEST('\x00\x00\x08\x00' * 3)
- self.assertFalse(self.proto.ignoreNextPacket)
- self.assertEqual(self.packets, [])
-
-
- def test_KEXDH_INIT(self):
- """
- Test that the KEXDH_INIT packet causes the server to send a
- KEXDH_REPLY with the server's public key and a signature.
- """
- self.proto.supportedKeyExchanges = ['diffie-hellman-group1-sha1']
- self.proto.supportedPublicKeys = ['ssh-rsa']
- self.proto.dataReceived(self.transport.value())
- e = pow(transport.DH_GENERATOR, 5000,
- transport.DH_PRIME)
-
- self.proto.ssh_KEX_DH_GEX_REQUEST_OLD(common.MP(e))
- y = common.getMP('\x00\x00\x00\x40' + '\x99' * 64)[0]
- f = common._MPpow(transport.DH_GENERATOR, y, transport.DH_PRIME)
- sharedSecret = common._MPpow(e, y, transport.DH_PRIME)
-
- h = sha1()
- h.update(common.NS(self.proto.ourVersionString) * 2)
- h.update(common.NS(self.proto.ourKexInitPayload) * 2)
- h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
- h.update(common.MP(e))
- h.update(f)
- h.update(sharedSecret)
- exchangeHash = h.digest()
-
- signature = self.proto.factory.privateKeys['ssh-rsa'].sign(
- exchangeHash)
-
- self.assertEqual(
- self.packets,
- [(transport.MSG_KEXDH_REPLY,
- common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob())
- + f + common.NS(signature)),
- (transport.MSG_NEWKEYS, '')])
-
-
- def test_KEX_DH_GEX_REQUEST_OLD(self):
- """
- Test that the KEX_DH_GEX_REQUEST_OLD message causes the server
- to reply with a KEX_DH_GEX_GROUP message with the correct
- Diffie-Hellman group.
- """
- self.proto.supportedKeyExchanges = [
- 'diffie-hellman-group-exchange-sha1']
- self.proto.supportedPublicKeys = ['ssh-rsa']
- self.proto.dataReceived(self.transport.value())
- self.proto.ssh_KEX_DH_GEX_REQUEST_OLD('\x00\x00\x04\x00')
- self.assertEqual(
- self.packets,
- [(transport.MSG_KEX_DH_GEX_GROUP,
- common.MP(transport.DH_PRIME) + '\x00\x00\x00\x01\x02')])
- self.assertEqual(self.proto.g, 2)
- self.assertEqual(self.proto.p, transport.DH_PRIME)
-
-
- def test_KEX_DH_GEX_REQUEST_OLD_badKexAlg(self):
- """
- Test that if the server recieves a KEX_DH_GEX_REQUEST_OLD message
- and the key exchange algorithm is not 'diffie-hellman-group1-sha1' or
- 'diffie-hellman-group-exchange-sha1', we raise a ConchError.
- """
- self.proto.kexAlg = None
- self.assertRaises(ConchError, self.proto.ssh_KEX_DH_GEX_REQUEST_OLD,
- None)
-
-
- def test_KEX_DH_GEX_REQUEST(self):
- """
- Test that the KEX_DH_GEX_REQUEST message causes the server to reply
- with a KEX_DH_GEX_GROUP message with the correct Diffie-Hellman
- group.
- """
- self.proto.supportedKeyExchanges = [
- 'diffie-hellman-group-exchange-sha1']
- self.proto.supportedPublicKeys = ['ssh-rsa']
- self.proto.dataReceived(self.transport.value())
- self.proto.ssh_KEX_DH_GEX_REQUEST('\x00\x00\x04\x00\x00\x00\x08\x00' +
- '\x00\x00\x0c\x00')
- self.assertEqual(
- self.packets,
- [(transport.MSG_KEX_DH_GEX_GROUP,
- common.MP(transport.DH_PRIME) + '\x00\x00\x00\x01\x03')])
- self.assertEqual(self.proto.g, 3)
- self.assertEqual(self.proto.p, transport.DH_PRIME)
-
-
- def test_KEX_DH_GEX_INIT_after_REQUEST(self):
- """
- Test that the KEX_DH_GEX_INIT message after the client sends
- KEX_DH_GEX_REQUEST causes the server to send a KEX_DH_GEX_INIT message
- with a public key and signature.
- """
- self.test_KEX_DH_GEX_REQUEST()
- e = pow(self.proto.g, 3, self.proto.p)
- y = common.getMP('\x00\x00\x00\x80' + '\x99' * 128)[0]
- f = common._MPpow(self.proto.g, y, self.proto.p)
- sharedSecret = common._MPpow(e, y, self.proto.p)
- h = sha1()
- h.update(common.NS(self.proto.ourVersionString) * 2)
- h.update(common.NS(self.proto.ourKexInitPayload) * 2)
- h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
- h.update('\x00\x00\x04\x00\x00\x00\x08\x00\x00\x00\x0c\x00')
- h.update(common.MP(self.proto.p))
- h.update(common.MP(self.proto.g))
- h.update(common.MP(e))
- h.update(f)
- h.update(sharedSecret)
- exchangeHash = h.digest()
- self.proto.ssh_KEX_DH_GEX_INIT(common.MP(e))
- self.assertEqual(
- self.packets[1],
- (transport.MSG_KEX_DH_GEX_REPLY,
- common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()) +
- f + common.NS(self.proto.factory.privateKeys['ssh-rsa'].sign(
- exchangeHash))))
-
-
- def test_KEX_DH_GEX_INIT_after_REQUEST_OLD(self):
- """
- Test that the KEX_DH_GEX_INIT message after the client sends
- KEX_DH_GEX_REQUEST_OLD causes the server to sent a KEX_DH_GEX_INIT
- message with a public key and signature.
- """
- self.test_KEX_DH_GEX_REQUEST_OLD()
- e = pow(self.proto.g, 3, self.proto.p)
- y = common.getMP('\x00\x00\x00\x80' + '\x99' * 128)[0]
- f = common._MPpow(self.proto.g, y, self.proto.p)
- sharedSecret = common._MPpow(e, y, self.proto.p)
- h = sha1()
- h.update(common.NS(self.proto.ourVersionString) * 2)
- h.update(common.NS(self.proto.ourKexInitPayload) * 2)
- h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
- h.update('\x00\x00\x04\x00')
- h.update(common.MP(self.proto.p))
- h.update(common.MP(self.proto.g))
- h.update(common.MP(e))
- h.update(f)
- h.update(sharedSecret)
- exchangeHash = h.digest()
- self.proto.ssh_KEX_DH_GEX_INIT(common.MP(e))
- self.assertEqual(
- self.packets[1:],
- [(transport.MSG_KEX_DH_GEX_REPLY,
- common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()) +
- f + common.NS(self.proto.factory.privateKeys['ssh-rsa'].sign(
- exchangeHash))),
- (transport.MSG_NEWKEYS, '')])
-
-
- def test_keySetup(self):
- """
- Test that _keySetup sets up the next encryption keys.
- """
- self.proto.nextEncryptions = MockCipher()
- self.simulateKeyExchange('AB', 'CD')
- self.assertEqual(self.proto.sessionID, 'CD')
- self.simulateKeyExchange('AB', 'EF')
- self.assertEqual(self.proto.sessionID, 'CD')
- self.assertEqual(self.packets[-1], (transport.MSG_NEWKEYS, ''))
- newKeys = [self.proto._getKey(c, 'AB', 'EF') for c in 'ABCDEF']
- self.assertEqual(
- self.proto.nextEncryptions.keys,
- (newKeys[1], newKeys[3], newKeys[0], newKeys[2], newKeys[5],
- newKeys[4]))
-
-
- def test_NEWKEYS(self):
- """
- Test that NEWKEYS transitions the keys in nextEncryptions to
- currentEncryptions.
- """
- self.test_KEXINIT()
-
- self.proto.nextEncryptions = transport.SSHCiphers('none', 'none',
- 'none', 'none')
- self.proto.ssh_NEWKEYS('')
- self.assertIs(self.proto.currentEncryptions,
- self.proto.nextEncryptions)
- self.assertIs(self.proto.outgoingCompression, None)
- self.assertIs(self.proto.incomingCompression, None)
- self.proto.outgoingCompressionType = 'zlib'
- self.simulateKeyExchange('AB', 'CD')
- self.proto.ssh_NEWKEYS('')
- self.assertIsNot(self.proto.outgoingCompression, None)
- self.proto.incomingCompressionType = 'zlib'
- self.simulateKeyExchange('AB', 'EF')
- self.proto.ssh_NEWKEYS('')
- self.assertIsNot(self.proto.incomingCompression, None)
-
-
- def test_SERVICE_REQUEST(self):
- """
- Test that the SERVICE_REQUEST message requests and starts a
- service.
- """
- self.proto.ssh_SERVICE_REQUEST(common.NS('ssh-userauth'))
- self.assertEqual(self.packets, [(transport.MSG_SERVICE_ACCEPT,
- common.NS('ssh-userauth'))])
- self.assertEqual(self.proto.service.name, 'MockService')
-
-
- def test_disconnectNEWKEYSData(self):
- """
- Test that NEWKEYS disconnects if it receives data.
- """
- self.proto.ssh_NEWKEYS("bad packet")
- self.checkDisconnected()
-
-
- def test_disconnectSERVICE_REQUESTBadService(self):
- """
- Test that SERVICE_REQUESTS disconnects if an unknown service is
- requested.
- """
- self.proto.ssh_SERVICE_REQUEST(common.NS('no service'))
- self.checkDisconnected(transport.DISCONNECT_SERVICE_NOT_AVAILABLE)
-
-
-
-class ClientSSHTransportTestCase(ServerAndClientSSHTransportBaseCase,
- TransportTestCase):
- """
- Tests for SSHClientTransport.
- """
-
- klass = transport.SSHClientTransport
-
-
- def test_KEXINIT(self):
- """
- Test that receiving a KEXINIT packet sets up the correct values on the
- client. The way algorithms are picks is that the first item in the
- client's list that is also in the server's list is chosen.
- """
- self.proto.dataReceived( 'SSH-2.0-Twisted\r\n\x00\x00\x01\xd4\t\x14'
- '\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99'
- '\x99\x00\x00\x00=diffie-hellman-group1-sha1,diffie-hellman-g'
- 'roup-exchange-sha1\x00\x00\x00\x0fssh-dss,ssh-rsa\x00\x00\x00'
- '\x85aes128-ctr,aes128-cbc,aes192-ctr,aes192-cbc,aes256-ctr,ae'
- 's256-cbc,cast128-ctr,cast128-cbc,blowfish-ctr,blowfish-cbc,3d'
- 'es-ctr,3des-cbc\x00\x00\x00\x85aes128-ctr,aes128-cbc,aes192-c'
- 'tr,aes192-cbc,aes256-ctr,aes256-cbc,cast128-ctr,cast128-cbc,b'
- 'lowfish-ctr,blowfish-cbc,3des-ctr,3des-cbc\x00\x00\x00\x12hma'
- 'c-md5,hmac-sha1\x00\x00\x00\x12hmac-md5,hmac-sha1\x00\x00\x00'
- '\tzlib,none\x00\x00\x00\tzlib,none\x00\x00\x00\x00\x00\x00'
- '\x00\x00\x00\x00\x00\x00\x00\x99\x99\x99\x99\x99\x99\x99\x99'
- '\x99')
- self.assertEqual(self.proto.kexAlg,
- 'diffie-hellman-group-exchange-sha1')
- self.assertEqual(self.proto.keyAlg,
- 'ssh-rsa')
- self.assertEqual(self.proto.outgoingCompressionType,
- 'none')
- self.assertEqual(self.proto.incomingCompressionType,
- 'none')
- ne = self.proto.nextEncryptions
- self.assertEqual(ne.outCipType, 'aes256-ctr')
- self.assertEqual(ne.inCipType, 'aes256-ctr')
- self.assertEqual(ne.outMACType, 'hmac-sha1')
- self.assertEqual(ne.inMACType, 'hmac-sha1')
-
-
- def verifyHostKey(self, pubKey, fingerprint):
- """
- Mock version of SSHClientTransport.verifyHostKey.
- """
- self.calledVerifyHostKey = True
- self.assertEqual(pubKey, self.blob)
- self.assertEqual(fingerprint.replace(':', ''),
- md5(pubKey).hexdigest())
- return defer.succeed(True)
-
-
- def setUp(self):
- TransportTestCase.setUp(self)
- self.blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
- self.privObj = keys.Key.fromString(keydata.privateRSA_openssh)
- self.calledVerifyHostKey = False
- self.proto.verifyHostKey = self.verifyHostKey
-
-
- def test_notImplementedClientMethods(self):
- """
- verifyHostKey() should return a Deferred which fails with a
- NotImplementedError exception. connectionSecure() should raise
- NotImplementedError().
- """
- self.assertRaises(NotImplementedError, self.klass().connectionSecure)
- def _checkRaises(f):
- f.trap(NotImplementedError)
- d = self.klass().verifyHostKey(None, None)
- return d.addCallback(self.fail).addErrback(_checkRaises)
-
-
- def test_KEXINIT_groupexchange(self):
- """
- Test that a KEXINIT packet with a group-exchange key exchange results
- in a KEX_DH_GEX_REQUEST_OLD message..
- """
- self.proto.supportedKeyExchanges = [
- 'diffie-hellman-group-exchange-sha1']
- self.proto.dataReceived(self.transport.value())
- self.assertEqual(self.packets, [(transport.MSG_KEX_DH_GEX_REQUEST_OLD,
- '\x00\x00\x08\x00')])
-
-
- def test_KEXINIT_group1(self):
- """
- Like test_KEXINIT_groupexchange, but for the group-1 key exchange.
- """
- self.proto.supportedKeyExchanges = ['diffie-hellman-group1-sha1']
- self.proto.dataReceived(self.transport.value())
- self.assertEqual(common.MP(self.proto.x)[5:], '\x99' * 64)
- self.assertEqual(self.packets,
- [(transport.MSG_KEXDH_INIT, self.proto.e)])
-
-
- def test_KEXINIT_badKexAlg(self):
- """
- Test that the client raises a ConchError if it receives a
- KEXINIT message bug doesn't have a key exchange algorithm that we
- understand.
- """
- self.proto.supportedKeyExchanges = ['diffie-hellman-group2-sha1']
- data = self.transport.value().replace('group1', 'group2')
- self.assertRaises(ConchError, self.proto.dataReceived, data)
-
-
- def test_KEXDH_REPLY(self):
- """
- Test that the KEXDH_REPLY message verifies the server.
- """
- self.test_KEXINIT_group1()
-
- sharedSecret = common._MPpow(transport.DH_GENERATOR,
- self.proto.x, transport.DH_PRIME)
- h = sha1()
- h.update(common.NS(self.proto.ourVersionString) * 2)
- h.update(common.NS(self.proto.ourKexInitPayload) * 2)
- h.update(common.NS(self.blob))
- h.update(self.proto.e)
- h.update('\x00\x00\x00\x01\x02') # f
- h.update(sharedSecret)
- exchangeHash = h.digest()
-
- def _cbTestKEXDH_REPLY(value):
- self.assertIs(value, None)
- self.assertEqual(self.calledVerifyHostKey, True)
- self.assertEqual(self.proto.sessionID, exchangeHash)
-
- signature = self.privObj.sign(exchangeHash)
-
- d = self.proto.ssh_KEX_DH_GEX_GROUP(
- (common.NS(self.blob) + '\x00\x00\x00\x01\x02' +
- common.NS(signature)))
- d.addCallback(_cbTestKEXDH_REPLY)
-
- return d
-
-
- def test_KEX_DH_GEX_GROUP(self):
- """
- Test that the KEX_DH_GEX_GROUP message results in a
- KEX_DH_GEX_INIT message with the client's Diffie-Hellman public key.
- """
- self.test_KEXINIT_groupexchange()
- self.proto.ssh_KEX_DH_GEX_GROUP(
- '\x00\x00\x00\x01\x0f\x00\x00\x00\x01\x02')
- self.assertEqual(self.proto.p, 15)
- self.assertEqual(self.proto.g, 2)
- self.assertEqual(common.MP(self.proto.x)[5:], '\x99' * 40)
- self.assertEqual(self.proto.e,
- common.MP(pow(2, self.proto.x, 15)))
- self.assertEqual(self.packets[1:], [(transport.MSG_KEX_DH_GEX_INIT,
- self.proto.e)])
-
-
- def test_KEX_DH_GEX_REPLY(self):
- """
- Test that the KEX_DH_GEX_REPLY message results in a verified
- server.
- """
-
- self.test_KEX_DH_GEX_GROUP()
- sharedSecret = common._MPpow(3, self.proto.x, self.proto.p)
- h = sha1()
- h.update(common.NS(self.proto.ourVersionString) * 2)
- h.update(common.NS(self.proto.ourKexInitPayload) * 2)
- h.update(common.NS(self.blob))
- h.update('\x00\x00\x08\x00\x00\x00\x00\x01\x0f\x00\x00\x00\x01\x02')
- h.update(self.proto.e)
- h.update('\x00\x00\x00\x01\x03') # f
- h.update(sharedSecret)
- exchangeHash = h.digest()
-
- def _cbTestKEX_DH_GEX_REPLY(value):
- self.assertIs(value, None)
- self.assertEqual(self.calledVerifyHostKey, True)
- self.assertEqual(self.proto.sessionID, exchangeHash)
-
- signature = self.privObj.sign(exchangeHash)
-
- d = self.proto.ssh_KEX_DH_GEX_REPLY(
- common.NS(self.blob) +
- '\x00\x00\x00\x01\x03' +
- common.NS(signature))
- d.addCallback(_cbTestKEX_DH_GEX_REPLY)
- return d
-
-
- def test_keySetup(self):
- """
- Test that _keySetup sets up the next encryption keys.
- """
- self.proto.nextEncryptions = MockCipher()
- self.simulateKeyExchange('AB', 'CD')
- self.assertEqual(self.proto.sessionID, 'CD')
- self.simulateKeyExchange('AB', 'EF')
- self.assertEqual(self.proto.sessionID, 'CD')
- self.assertEqual(self.packets[-1], (transport.MSG_NEWKEYS, ''))
- newKeys = [self.proto._getKey(c, 'AB', 'EF') for c in 'ABCDEF']
- self.assertEqual(self.proto.nextEncryptions.keys,
- (newKeys[0], newKeys[2], newKeys[1], newKeys[3],
- newKeys[4], newKeys[5]))
-
-
- def test_NEWKEYS(self):
- """
- Test that NEWKEYS transitions the keys from nextEncryptions to
- currentEncryptions.
- """
- self.test_KEXINIT()
- secure = [False]
- def stubConnectionSecure():
- secure[0] = True
- self.proto.connectionSecure = stubConnectionSecure
-
- self.proto.nextEncryptions = transport.SSHCiphers(
- 'none', 'none', 'none', 'none')
- self.simulateKeyExchange('AB', 'CD')
- self.assertIsNot(self.proto.currentEncryptions,
- self.proto.nextEncryptions)
-
- self.proto.nextEncryptions = MockCipher()
- self.proto.ssh_NEWKEYS('')
- self.assertIs(self.proto.outgoingCompression, None)
- self.assertIs(self.proto.incomingCompression, None)
- self.assertIs(self.proto.currentEncryptions,
- self.proto.nextEncryptions)
- self.assertTrue(secure[0])
- self.proto.outgoingCompressionType = 'zlib'
- self.simulateKeyExchange('AB', 'GH')
- self.proto.ssh_NEWKEYS('')
- self.assertIsNot(self.proto.outgoingCompression, None)
- self.proto.incomingCompressionType = 'zlib'
- self.simulateKeyExchange('AB', 'IJ')
- self.proto.ssh_NEWKEYS('')
- self.assertIsNot(self.proto.incomingCompression, None)
-
-
- def test_SERVICE_ACCEPT(self):
- """
- Test that the SERVICE_ACCEPT packet starts the requested service.
- """
- self.proto.instance = MockService()
- self.proto.ssh_SERVICE_ACCEPT('\x00\x00\x00\x0bMockService')
- self.assertTrue(self.proto.instance.started)
-
-
- def test_requestService(self):
- """
- Test that requesting a service sends a SERVICE_REQUEST packet.
- """
- self.proto.requestService(MockService())
- self.assertEqual(self.packets, [(transport.MSG_SERVICE_REQUEST,
- '\x00\x00\x00\x0bMockService')])
-
-
- def test_disconnectKEXDH_REPLYBadSignature(self):
- """
- Test that KEXDH_REPLY disconnects if the signature is bad.
- """
- self.test_KEXDH_REPLY()
- self.proto._continueKEXDH_REPLY(None, self.blob, 3, "bad signature")
- self.checkDisconnected(transport.DISCONNECT_KEY_EXCHANGE_FAILED)
-
-
- def test_disconnectGEX_REPLYBadSignature(self):
- """
- Like test_disconnectKEXDH_REPLYBadSignature, but for DH_GEX_REPLY.
- """
- self.test_KEX_DH_GEX_REPLY()
- self.proto._continueGEX_REPLY(None, self.blob, 3, "bad signature")
- self.checkDisconnected(transport.DISCONNECT_KEY_EXCHANGE_FAILED)
-
-
- def test_disconnectNEWKEYSData(self):
- """
- Test that NEWKEYS disconnects if it receives data.
- """
- self.proto.ssh_NEWKEYS("bad packet")
- self.checkDisconnected()
-
-
- def test_disconnectSERVICE_ACCEPT(self):
- """
- Test that SERVICE_ACCEPT disconnects if the accepted protocol is
- differet from the asked-for protocol.
- """
- self.proto.instance = MockService()
- self.proto.ssh_SERVICE_ACCEPT('\x00\x00\x00\x03bad')
- self.checkDisconnected()
-
-
- def test_noPayloadSERVICE_ACCEPT(self):
- """
- Some commercial SSH servers don't send a payload with the
- SERVICE_ACCEPT message. Conch pretends that it got the correct
- name of the service.
- """
- self.proto.instance = MockService()
- self.proto.ssh_SERVICE_ACCEPT('') # no payload
- self.assertTrue(self.proto.instance.started)
- self.assertEqual(len(self.packets), 0) # not disconnected
-
-
-
-class GetMACTestCase(unittest.TestCase):
- """
- Tests for L{SSHCiphers._getMAC}.
- """
- if dependencySkip:
- skip = dependencySkip
-
- def setUp(self):
- self.ciphers = transport.SSHCiphers(b'A', b'B', b'C', b'D')
-
- # MD5 digest is 16 bytes. Put some non-zero bytes into that part of
- # the key. Maybe varying the bytes a little bit means a bug in the
- # implementation is more likely to be caught by the assertions below.
- # The remaining 48 bytes of NULs are to pad the key out to 64 bytes.
- # It doesn't seem to matter that SHA1 produces a larger digest. The
- # material seems always to need to be truncated at 16 bytes.
- self.key = '\x55\xaa' * 8 + '\x00' * 48
-
- self.ipad = b''.join(chr(ord(b) ^ 0x36) for b in self.key)
- self.opad = b''.join(chr(ord(b) ^ 0x5c) for b in self.key)
-
-
- def test_hmacsha1(self):
- """
- When L{SSHCiphers._getMAC} is called with the C{b"hmac-sha1"} MAC
- algorithm name it returns a tuple of (sha1 digest object, inner pad,
- outer pad, sha1 digest size) with a C{key} attribute set to the value
- of the key supplied.
- """
- params = self.ciphers._getMAC(b"hmac-sha1", self.key)
- self.assertEqual(
- (sha1, self.ipad, self.opad, sha1().digest_size, self.key),
- params + (params.key,))
-
-
- def test_md5sha1(self):
- """
- When L{SSHCiphers._getMAC} is called with the C{b"hmac-md5"} MAC
- algorithm name it returns a tuple of (md5 digest object, inner pad,
- outer pad, md5 digest size) with a C{key} attribute set to the value of
- the key supplied.
- """
- params = self.ciphers._getMAC(b"hmac-md5", self.key)
- self.assertEqual(
- (md5, self.ipad, self.opad, md5().digest_size, self.key),
- params + (params.key,))
-
-
- def test_none(self):
- """
- When L{SSHCiphers._getMAC} is called with the C{b"none"} MAC algorithm
- name it returns a tuple of (None, "", "", 0)
- """
- params = self.ciphers._getMAC(b"none", self.key)
- self.assertEqual((None, b"", b"", 0), params)
-
-
-
-class SSHCiphersTestCase(unittest.TestCase):
- """
- Tests for the SSHCiphers helper class.
- """
- if dependencySkip:
- skip = dependencySkip
-
- def test_init(self):
- """
- Test that the initializer sets up the SSHCiphers object.
- """
- ciphers = transport.SSHCiphers('A', 'B', 'C', 'D')
- self.assertEqual(ciphers.outCipType, 'A')
- self.assertEqual(ciphers.inCipType, 'B')
- self.assertEqual(ciphers.outMACType, 'C')
- self.assertEqual(ciphers.inMACType, 'D')
-
-
- def test_getCipher(self):
- """
- Test that the _getCipher method returns the correct cipher.
- """
- ciphers = transport.SSHCiphers('A', 'B', 'C', 'D')
- iv = key = '\x00' * 16
- for cipName, (modName, keySize, counter) in ciphers.cipherMap.items():
- cip = ciphers._getCipher(cipName, iv, key)
- if cipName == 'none':
- self.assertIsInstance(cip, transport._DummyCipher)
- else:
- self.assertTrue(getClass(cip).__name__.startswith(modName))
-
-
- def test_setKeysCiphers(self):
- """
- Test that setKeys sets up the ciphers.
- """
- key = '\x00' * 64
- cipherItems = transport.SSHCiphers.cipherMap.items()
- for cipName, (modName, keySize, counter) in cipherItems:
- encCipher = transport.SSHCiphers(cipName, 'none', 'none', 'none')
- decCipher = transport.SSHCiphers('none', cipName, 'none', 'none')
- cip = encCipher._getCipher(cipName, key, key)
- bs = cip.block_size
- encCipher.setKeys(key, key, '', '', '', '')
- decCipher.setKeys('', '', key, key, '', '')
- self.assertEqual(encCipher.encBlockSize, bs)
- self.assertEqual(decCipher.decBlockSize, bs)
- enc = cip.encrypt(key[:bs])
- enc2 = cip.encrypt(key[:bs])
- if counter:
- self.assertNotEqual(enc, enc2)
- self.assertEqual(encCipher.encrypt(key[:bs]), enc)
- self.assertEqual(encCipher.encrypt(key[:bs]), enc2)
- self.assertEqual(decCipher.decrypt(enc), key[:bs])
- self.assertEqual(decCipher.decrypt(enc2), key[:bs])
-
-
- def test_setKeysMACs(self):
- """
- Test that setKeys sets up the MACs.
- """
- key = '\x00' * 64
- for macName, mod in transport.SSHCiphers.macMap.items():
- outMac = transport.SSHCiphers('none', 'none', macName, 'none')
- inMac = transport.SSHCiphers('none', 'none', 'none', macName)
- outMac.setKeys('', '', '', '', key, '')
- inMac.setKeys('', '', '', '', '', key)
- if mod:
- ds = mod().digest_size
- else:
- ds = 0
- self.assertEqual(inMac.verifyDigestSize, ds)
- if mod:
- mod, i, o, ds = outMac._getMAC(macName, key)
- seqid = 0
- data = key
- packet = '\x00' * 4 + key
- if mod:
- mac = mod(o + mod(i + packet).digest()).digest()
- else:
- mac = ''
- self.assertEqual(outMac.makeMAC(seqid, data), mac)
- self.assertTrue(inMac.verify(seqid, data, mac))
-
-
- def test_makeMAC(self):
- """
- L{SSHCiphers.makeMAC} computes the HMAC of an outgoing SSH message with
- a particular sequence id and content data.
- """
- # Use the test vectors given in the appendix of RFC 2104.
- vectors = [
- (b"\x0b" * 16, b"Hi There",
- b"9294727a3638bb1c13f48ef8158bfc9d"),
- (b"Jefe", b"what do ya want for nothing?",
- b"750c783e6ab0b503eaa86e310a5db738"),
- (b"\xAA" * 16, b"\xDD" * 50,
- b"56be34521d144c88dbb8c733f0e8b3f6"),
- ]
-
- for key, data, mac in vectors:
- outMAC = transport.SSHCiphers('none', 'none', 'hmac-md5', 'none')
- outMAC.outMAC = outMAC._getMAC("hmac-md5", key)
- (seqid,) = struct.unpack('>L', data[:4])
- shortened = data[4:]
- self.assertEqual(
- mac, outMAC.makeMAC(seqid, shortened).encode("hex"),
- "Failed HMAC test vector; key=%r data=%r" % (key, data))
-
-
-
-class CounterTestCase(unittest.TestCase):
- """
- Tests for the _Counter helper class.
- """
- if dependencySkip:
- skip = dependencySkip
-
- def test_init(self):
- """
- Test that the counter is initialized correctly.
- """
- counter = transport._Counter('\x00' * 8 + '\xff' * 8, 8)
- self.assertEqual(counter.blockSize, 8)
- self.assertEqual(counter.count.tostring(), '\x00' * 8)
-
-
- def test_count(self):
- """
- Test that the counter counts incrementally and wraps at the top.
- """
- counter = transport._Counter('\x00', 1)
- self.assertEqual(counter(), '\x01')
- self.assertEqual(counter(), '\x02')
- [counter() for i in range(252)]
- self.assertEqual(counter(), '\xff')
- self.assertEqual(counter(), '\x00')
-
-
-
-class TransportLoopbackTestCase(unittest.TestCase):
- """
- Test the server transport and client transport against each other,
- """
- if dependencySkip:
- skip = dependencySkip
-
- def _runClientServer(self, mod):
- """
- Run an async client and server, modifying each using the mod function
- provided. Returns a Deferred called back when both Protocols have
- disconnected.
-
- @type mod: C{func}
- @rtype: C{defer.Deferred}
- """
- factory = MockFactory()
- server = transport.SSHServerTransport()
- server.factory = factory
- factory.startFactory()
- server.errors = []
- server.receiveError = lambda code, desc: server.errors.append((
- code, desc))
- client = transport.SSHClientTransport()
- client.verifyHostKey = lambda x, y: defer.succeed(None)
- client.errors = []
- client.receiveError = lambda code, desc: client.errors.append((
- code, desc))
- client.connectionSecure = lambda: client.loseConnection()
- server = mod(server)
- client = mod(client)
- def check(ignored, server, client):
- name = repr([server.supportedCiphers[0],
- server.supportedMACs[0],
- server.supportedKeyExchanges[0],
- server.supportedCompressions[0]])
- self.assertEqual(client.errors, [])
- self.assertEqual(server.errors, [(
- transport.DISCONNECT_CONNECTION_LOST,
- "user closed connection")])
- if server.supportedCiphers[0] == 'none':
- self.assertFalse(server.isEncrypted(), name)
- self.assertFalse(client.isEncrypted(), name)
- else:
- self.assertTrue(server.isEncrypted(), name)
- self.assertTrue(client.isEncrypted(), name)
- if server.supportedMACs[0] == 'none':
- self.assertFalse(server.isVerified(), name)
- self.assertFalse(client.isVerified(), name)
- else:
- self.assertTrue(server.isVerified(), name)
- self.assertTrue(client.isVerified(), name)
-
- d = loopback.loopbackAsync(server, client)
- d.addCallback(check, server, client)
- return d
-
-
- def test_ciphers(self):
- """
- Test that the client and server play nicely together, in all
- the various combinations of ciphers.
- """
- deferreds = []
- for cipher in transport.SSHTransportBase.supportedCiphers + ['none']:
- def setCipher(proto):
- proto.supportedCiphers = [cipher]
- return proto
- deferreds.append(self._runClientServer(setCipher))
- return defer.DeferredList(deferreds, fireOnOneErrback=True)
-
-
- def test_macs(self):
- """
- Like test_ciphers, but for the various MACs.
- """
- deferreds = []
- for mac in transport.SSHTransportBase.supportedMACs + ['none']:
- def setMAC(proto):
- proto.supportedMACs = [mac]
- return proto
- deferreds.append(self._runClientServer(setMAC))
- return defer.DeferredList(deferreds, fireOnOneErrback=True)
-
-
- def test_keyexchanges(self):
- """
- Like test_ciphers, but for the various key exchanges.
- """
- deferreds = []
- for kex in transport.SSHTransportBase.supportedKeyExchanges:
- def setKeyExchange(proto):
- proto.supportedKeyExchanges = [kex]
- return proto
- deferreds.append(self._runClientServer(setKeyExchange))
- return defer.DeferredList(deferreds, fireOnOneErrback=True)
-
-
- def test_compressions(self):
- """
- Like test_ciphers, but for the various compressions.
- """
- deferreds = []
- for compression in transport.SSHTransportBase.supportedCompressions:
- def setCompression(proto):
- proto.supportedCompressions = [compression]
- return proto
- deferreds.append(self._runClientServer(setCompression))
- return defer.DeferredList(deferreds, fireOnOneErrback=True)
-
-
-class RandomNumberTestCase(unittest.TestCase):
- """
- Tests for the random number generator L{_getRandomNumber} and private
- key generator L{_generateX}.
- """
- if dependencySkip:
- skip = dependencySkip
-
- def test_usesSuppliedRandomFunction(self):
- """
- L{_getRandomNumber} returns an integer constructed directly from the
- bytes returned by the random byte generator passed to it.
- """
- def random(bytes):
- # The number of bytes requested will be the value of each byte
- # we return.
- return chr(bytes) * bytes
- self.assertEqual(
- transport._getRandomNumber(random, 32),
- 4 << 24 | 4 << 16 | 4 << 8 | 4)
-
-
- def test_rejectsNonByteMultiples(self):
- """
- L{_getRandomNumber} raises L{ValueError} if the number of bits
- passed to L{_getRandomNumber} is not a multiple of 8.
- """
- self.assertRaises(
- ValueError,
- transport._getRandomNumber, None, 9)
-
-
- def test_excludesSmall(self):
- """
- If the random byte generator passed to L{_generateX} produces bytes
- which would result in 0 or 1 being returned, these bytes are
- discarded and another attempt is made to produce a larger value.
- """
- results = [chr(0), chr(1), chr(127)]
- def random(bytes):
- return results.pop(0) * bytes
- self.assertEqual(
- transport._generateX(random, 8),
- 127)
-
-
- def test_excludesLarge(self):
- """
- If the random byte generator passed to L{_generateX} produces bytes
- which would result in C{(2 ** bits) - 1} being returned, these bytes
- are discarded and another attempt is made to produce a smaller
- value.
- """
- results = [chr(255), chr(64)]
- def random(bytes):
- return results.pop(0) * bytes
- self.assertEqual(
- transport._generateX(random, 8),
- 64)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_userauth.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_userauth.py
deleted file mode 100644
index 6f4ae5a..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_userauth.py
+++ /dev/null
@@ -1,1036 +0,0 @@
-# -*- test-case-name: twisted.conch.test.test_userauth -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Tests for the implementation of the ssh-userauth service.
-
-Maintainer: Paul Swartz
-"""
-
-from zope.interface import implements
-
-from twisted.cred.checkers import ICredentialsChecker
-from twisted.cred.credentials import IUsernamePassword, ISSHPrivateKey
-from twisted.cred.credentials import IPluggableAuthenticationModules
-from twisted.cred.credentials import IAnonymous
-from twisted.cred.error import UnauthorizedLogin
-from twisted.cred.portal import IRealm, Portal
-from twisted.conch.error import ConchError, ValidPublicKey
-from twisted.internet import defer, task
-from twisted.protocols import loopback
-from twisted.trial import unittest
-
-try:
- import Crypto.Cipher.DES3
- import pyasn1
-except ImportError:
- keys = None
-
-
- class transport:
- class SSHTransportBase:
- """
- A stub class so that later class definitions won't die.
- """
-
- class userauth:
- class SSHUserAuthClient:
- """
- A stub class so that later class definitions won't die.
- """
-else:
- from twisted.conch.ssh.common import NS
- from twisted.conch.checkers import SSHProtocolChecker
- from twisted.conch.ssh import keys, userauth, transport
- from twisted.conch.test import keydata
-
-
-
-class ClientUserAuth(userauth.SSHUserAuthClient):
- """
- A mock user auth client.
- """
-
-
- def getPublicKey(self):
- """
- If this is the first time we've been called, return a blob for
- the DSA key. Otherwise, return a blob
- for the RSA key.
- """
- if self.lastPublicKey:
- return keys.Key.fromString(keydata.publicRSA_openssh)
- else:
- return defer.succeed(keys.Key.fromString(keydata.publicDSA_openssh))
-
-
- def getPrivateKey(self):
- """
- Return the private key object for the RSA key.
- """
- return defer.succeed(keys.Key.fromString(keydata.privateRSA_openssh))
-
-
- def getPassword(self, prompt=None):
- """
- Return 'foo' as the password.
- """
- return defer.succeed('foo')
-
-
- def getGenericAnswers(self, name, information, answers):
- """
- Return 'foo' as the answer to two questions.
- """
- return defer.succeed(('foo', 'foo'))
-
-
-
-class OldClientAuth(userauth.SSHUserAuthClient):
- """
- The old SSHUserAuthClient returned a PyCrypto key object from
- getPrivateKey() and a string from getPublicKey
- """
-
-
- def getPrivateKey(self):
- return defer.succeed(keys.Key.fromString(
- keydata.privateRSA_openssh).keyObject)
-
-
- def getPublicKey(self):
- return keys.Key.fromString(keydata.publicRSA_openssh).blob()
-
-class ClientAuthWithoutPrivateKey(userauth.SSHUserAuthClient):
- """
- This client doesn't have a private key, but it does have a public key.
- """
-
-
- def getPrivateKey(self):
- return
-
-
- def getPublicKey(self):
- return keys.Key.fromString(keydata.publicRSA_openssh)
-
-
-
-class FakeTransport(transport.SSHTransportBase):
- """
- L{userauth.SSHUserAuthServer} expects an SSH transport which has a factory
- attribute which has a portal attribute. Because the portal is important for
- testing authentication, we need to be able to provide an interesting portal
- object to the L{SSHUserAuthServer}.
-
- In addition, we want to be able to capture any packets sent over the
- transport.
-
- @ivar packets: a list of 2-tuples: (messageType, data). Each 2-tuple is
- a sent packet.
- @type packets: C{list}
- @param lostConnecion: True if loseConnection has been called on us.
- @type lostConnection: C{bool}
- """
-
-
- class Service(object):
- """
- A mock service, representing the other service offered by the server.
- """
- name = 'nancy'
-
-
- def serviceStarted(self):
- pass
-
-
-
- class Factory(object):
- """
- A mock factory, representing the factory that spawned this user auth
- service.
- """
-
-
- def getService(self, transport, service):
- """
- Return our fake service.
- """
- if service == 'none':
- return FakeTransport.Service
-
-
-
- def __init__(self, portal):
- self.factory = self.Factory()
- self.factory.portal = portal
- self.lostConnection = False
- self.transport = self
- self.packets = []
-
-
-
- def sendPacket(self, messageType, message):
- """
- Record the packet sent by the service.
- """
- self.packets.append((messageType, message))
-
-
- def isEncrypted(self, direction):
- """
- Pretend that this transport encrypts traffic in both directions. The
- SSHUserAuthServer disables password authentication if the transport
- isn't encrypted.
- """
- return True
-
-
- def loseConnection(self):
- self.lostConnection = True
-
-
-
-class Realm(object):
- """
- A mock realm for testing L{userauth.SSHUserAuthServer}.
-
- This realm is not actually used in the course of testing, so it returns the
- simplest thing that could possibly work.
- """
- implements(IRealm)
-
-
- def requestAvatar(self, avatarId, mind, *interfaces):
- return defer.succeed((interfaces[0], None, lambda: None))
-
-
-
-class PasswordChecker(object):
- """
- A very simple username/password checker which authenticates anyone whose
- password matches their username and rejects all others.
- """
- credentialInterfaces = (IUsernamePassword,)
- implements(ICredentialsChecker)
-
-
- def requestAvatarId(self, creds):
- if creds.username == creds.password:
- return defer.succeed(creds.username)
- return defer.fail(UnauthorizedLogin("Invalid username/password pair"))
-
-
-
-class PrivateKeyChecker(object):
- """
- A very simple public key checker which authenticates anyone whose
- public/private keypair is the same keydata.public/privateRSA_openssh.
- """
- credentialInterfaces = (ISSHPrivateKey,)
- implements(ICredentialsChecker)
-
-
-
- def requestAvatarId(self, creds):
- if creds.blob == keys.Key.fromString(keydata.publicRSA_openssh).blob():
- if creds.signature is not None:
- obj = keys.Key.fromString(creds.blob)
- if obj.verify(creds.signature, creds.sigData):
- return creds.username
- else:
- raise ValidPublicKey()
- raise UnauthorizedLogin()
-
-
-
-class PAMChecker(object):
- """
- A simple PAM checker which asks the user for a password, verifying them
- if the password is the same as their username.
- """
- credentialInterfaces = (IPluggableAuthenticationModules,)
- implements(ICredentialsChecker)
-
-
- def requestAvatarId(self, creds):
- d = creds.pamConversion([('Name: ', 2), ("Password: ", 1)])
- def check(values):
- if values == [(creds.username, 0), (creds.username, 0)]:
- return creds.username
- raise UnauthorizedLogin()
- return d.addCallback(check)
-
-
-
-class AnonymousChecker(object):
- """
- A simple checker which isn't supported by L{SSHUserAuthServer}.
- """
- credentialInterfaces = (IAnonymous,)
- implements(ICredentialsChecker)
-
-
-
-class SSHUserAuthServerTestCase(unittest.TestCase):
- """
- Tests for SSHUserAuthServer.
- """
-
-
- if keys is None:
- skip = "cannot run w/o PyCrypto"
-
-
- def setUp(self):
- self.realm = Realm()
- self.portal = Portal(self.realm)
- self.portal.registerChecker(PasswordChecker())
- self.portal.registerChecker(PrivateKeyChecker())
- self.portal.registerChecker(PAMChecker())
- self.authServer = userauth.SSHUserAuthServer()
- self.authServer.transport = FakeTransport(self.portal)
- self.authServer.serviceStarted()
- self.authServer.supportedAuthentications.sort() # give a consistent
- # order
-
-
- def tearDown(self):
- self.authServer.serviceStopped()
- self.authServer = None
-
-
- def _checkFailed(self, ignored):
- """
- Check that the authentication has failed.
- """
- self.assertEqual(self.authServer.transport.packets[-1],
- (userauth.MSG_USERAUTH_FAILURE,
- NS('keyboard-interactive,password,publickey') + '\x00'))
-
-
- def test_noneAuthentication(self):
- """
- A client may request a list of authentication 'method name' values
- that may continue by using the "none" authentication 'method name'.
-
- See RFC 4252 Section 5.2.
- """
- d = self.authServer.ssh_USERAUTH_REQUEST(NS('foo') + NS('service') +
- NS('none'))
- return d.addCallback(self._checkFailed)
-
-
- def test_successfulPasswordAuthentication(self):
- """
- When provided with correct password authentication information, the
- server should respond by sending a MSG_USERAUTH_SUCCESS message with
- no other data.
-
- See RFC 4252, Section 5.1.
- """
- packet = NS('foo') + NS('none') + NS('password') + chr(0) + NS('foo')
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- def check(ignored):
- self.assertEqual(
- self.authServer.transport.packets,
- [(userauth.MSG_USERAUTH_SUCCESS, '')])
- return d.addCallback(check)
-
-
- def test_failedPasswordAuthentication(self):
- """
- When provided with invalid authentication details, the server should
- respond by sending a MSG_USERAUTH_FAILURE message which states whether
- the authentication was partially successful, and provides other, open
- options for authentication.
-
- See RFC 4252, Section 5.1.
- """
- # packet = username, next_service, authentication type, FALSE, password
- packet = NS('foo') + NS('none') + NS('password') + chr(0) + NS('bar')
- self.authServer.clock = task.Clock()
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- self.assertEqual(self.authServer.transport.packets, [])
- self.authServer.clock.advance(2)
- return d.addCallback(self._checkFailed)
-
-
- def test_successfulPrivateKeyAuthentication(self):
- """
- Test that private key authentication completes sucessfully,
- """
- blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
- obj = keys.Key.fromString(keydata.privateRSA_openssh)
- packet = (NS('foo') + NS('none') + NS('publickey') + '\xff'
- + NS(obj.sshType()) + NS(blob))
- self.authServer.transport.sessionID = 'test'
- signature = obj.sign(NS('test') + chr(userauth.MSG_USERAUTH_REQUEST)
- + packet)
- packet += NS(signature)
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- def check(ignored):
- self.assertEqual(self.authServer.transport.packets,
- [(userauth.MSG_USERAUTH_SUCCESS, '')])
- return d.addCallback(check)
-
-
- def test_requestRaisesConchError(self):
- """
- ssh_USERAUTH_REQUEST should raise a ConchError if tryAuth returns
- None. Added to catch a bug noticed by pyflakes.
- """
- d = defer.Deferred()
-
- def mockCbFinishedAuth(self, ignored):
- self.fail('request should have raised ConochError')
-
- def mockTryAuth(kind, user, data):
- return None
-
- def mockEbBadAuth(reason):
- d.errback(reason.value)
-
- self.patch(self.authServer, 'tryAuth', mockTryAuth)
- self.patch(self.authServer, '_cbFinishedAuth', mockCbFinishedAuth)
- self.patch(self.authServer, '_ebBadAuth', mockEbBadAuth)
-
- packet = NS('user') + NS('none') + NS('public-key') + NS('data')
- # If an error other than ConchError is raised, this will trigger an
- # exception.
- self.authServer.ssh_USERAUTH_REQUEST(packet)
- return self.assertFailure(d, ConchError)
-
-
- def test_verifyValidPrivateKey(self):
- """
- Test that verifying a valid private key works.
- """
- blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
- packet = (NS('foo') + NS('none') + NS('publickey') + '\x00'
- + NS('ssh-rsa') + NS(blob))
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- def check(ignored):
- self.assertEqual(self.authServer.transport.packets,
- [(userauth.MSG_USERAUTH_PK_OK, NS('ssh-rsa') + NS(blob))])
- return d.addCallback(check)
-
-
- def test_failedPrivateKeyAuthenticationWithoutSignature(self):
- """
- Test that private key authentication fails when the public key
- is invalid.
- """
- blob = keys.Key.fromString(keydata.publicDSA_openssh).blob()
- packet = (NS('foo') + NS('none') + NS('publickey') + '\x00'
- + NS('ssh-dsa') + NS(blob))
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- return d.addCallback(self._checkFailed)
-
-
- def test_failedPrivateKeyAuthenticationWithSignature(self):
- """
- Test that private key authentication fails when the public key
- is invalid.
- """
- blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
- obj = keys.Key.fromString(keydata.privateRSA_openssh)
- packet = (NS('foo') + NS('none') + NS('publickey') + '\xff'
- + NS('ssh-rsa') + NS(blob) + NS(obj.sign(blob)))
- self.authServer.transport.sessionID = 'test'
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- return d.addCallback(self._checkFailed)
-
-
- def test_successfulPAMAuthentication(self):
- """
- Test that keyboard-interactive authentication succeeds.
- """
- packet = (NS('foo') + NS('none') + NS('keyboard-interactive')
- + NS('') + NS(''))
- response = '\x00\x00\x00\x02' + NS('foo') + NS('foo')
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- self.authServer.ssh_USERAUTH_INFO_RESPONSE(response)
- def check(ignored):
- self.assertEqual(self.authServer.transport.packets,
- [(userauth.MSG_USERAUTH_INFO_REQUEST, (NS('') + NS('')
- + NS('') + '\x00\x00\x00\x02' + NS('Name: ') + '\x01'
- + NS('Password: ') + '\x00')),
- (userauth.MSG_USERAUTH_SUCCESS, '')])
-
- return d.addCallback(check)
-
-
- def test_failedPAMAuthentication(self):
- """
- Test that keyboard-interactive authentication fails.
- """
- packet = (NS('foo') + NS('none') + NS('keyboard-interactive')
- + NS('') + NS(''))
- response = '\x00\x00\x00\x02' + NS('bar') + NS('bar')
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- self.authServer.ssh_USERAUTH_INFO_RESPONSE(response)
- def check(ignored):
- self.assertEqual(self.authServer.transport.packets[0],
- (userauth.MSG_USERAUTH_INFO_REQUEST, (NS('') + NS('')
- + NS('') + '\x00\x00\x00\x02' + NS('Name: ') + '\x01'
- + NS('Password: ') + '\x00')))
- return d.addCallback(check).addCallback(self._checkFailed)
-
-
- def test_invalid_USERAUTH_INFO_RESPONSE_not_enough_data(self):
- """
- If ssh_USERAUTH_INFO_RESPONSE gets an invalid packet,
- the user authentication should fail.
- """
- packet = (NS('foo') + NS('none') + NS('keyboard-interactive')
- + NS('') + NS(''))
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- self.authServer.ssh_USERAUTH_INFO_RESPONSE(NS('\x00\x00\x00\x00' +
- NS('hi')))
- return d.addCallback(self._checkFailed)
-
-
- def test_invalid_USERAUTH_INFO_RESPONSE_too_much_data(self):
- """
- If ssh_USERAUTH_INFO_RESPONSE gets too much data, the user
- authentication should fail.
- """
- packet = (NS('foo') + NS('none') + NS('keyboard-interactive')
- + NS('') + NS(''))
- response = '\x00\x00\x00\x02' + NS('foo') + NS('foo') + NS('foo')
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- self.authServer.ssh_USERAUTH_INFO_RESPONSE(response)
- return d.addCallback(self._checkFailed)
-
-
- def test_onlyOnePAMAuthentication(self):
- """
- Because it requires an intermediate message, one can't send a second
- keyboard-interactive request while the first is still pending.
- """
- packet = (NS('foo') + NS('none') + NS('keyboard-interactive')
- + NS('') + NS(''))
- self.authServer.ssh_USERAUTH_REQUEST(packet)
- self.authServer.ssh_USERAUTH_REQUEST(packet)
- self.assertEqual(self.authServer.transport.packets[-1][0],
- transport.MSG_DISCONNECT)
- self.assertEqual(self.authServer.transport.packets[-1][1][3],
- chr(transport.DISCONNECT_PROTOCOL_ERROR))
-
-
- def test_ignoreUnknownCredInterfaces(self):
- """
- L{SSHUserAuthServer} sets up
- C{SSHUserAuthServer.supportedAuthentications} by checking the portal's
- credentials interfaces and mapping them to SSH authentication method
- strings. If the Portal advertises an interface that
- L{SSHUserAuthServer} can't map, it should be ignored. This is a white
- box test.
- """
- server = userauth.SSHUserAuthServer()
- server.transport = FakeTransport(self.portal)
- self.portal.registerChecker(AnonymousChecker())
- server.serviceStarted()
- server.serviceStopped()
- server.supportedAuthentications.sort() # give a consistent order
- self.assertEqual(server.supportedAuthentications,
- ['keyboard-interactive', 'password', 'publickey'])
-
-
- def test_removePasswordIfUnencrypted(self):
- """
- Test that the userauth service does not advertise password
- authentication if the password would be send in cleartext.
- """
- self.assertIn('password', self.authServer.supportedAuthentications)
- # no encryption
- clearAuthServer = userauth.SSHUserAuthServer()
- clearAuthServer.transport = FakeTransport(self.portal)
- clearAuthServer.transport.isEncrypted = lambda x: False
- clearAuthServer.serviceStarted()
- clearAuthServer.serviceStopped()
- self.assertNotIn('password', clearAuthServer.supportedAuthentications)
- # only encrypt incoming (the direction the password is sent)
- halfAuthServer = userauth.SSHUserAuthServer()
- halfAuthServer.transport = FakeTransport(self.portal)
- halfAuthServer.transport.isEncrypted = lambda x: x == 'in'
- halfAuthServer.serviceStarted()
- halfAuthServer.serviceStopped()
- self.assertIn('password', halfAuthServer.supportedAuthentications)
-
-
- def test_removeKeyboardInteractiveIfUnencrypted(self):
- """
- Test that the userauth service does not advertise keyboard-interactive
- authentication if the password would be send in cleartext.
- """
- self.assertIn('keyboard-interactive',
- self.authServer.supportedAuthentications)
- # no encryption
- clearAuthServer = userauth.SSHUserAuthServer()
- clearAuthServer.transport = FakeTransport(self.portal)
- clearAuthServer.transport.isEncrypted = lambda x: False
- clearAuthServer.serviceStarted()
- clearAuthServer.serviceStopped()
- self.assertNotIn(
- 'keyboard-interactive', clearAuthServer.supportedAuthentications)
- # only encrypt incoming (the direction the password is sent)
- halfAuthServer = userauth.SSHUserAuthServer()
- halfAuthServer.transport = FakeTransport(self.portal)
- halfAuthServer.transport.isEncrypted = lambda x: x == 'in'
- halfAuthServer.serviceStarted()
- halfAuthServer.serviceStopped()
- self.assertIn('keyboard-interactive',
- halfAuthServer.supportedAuthentications)
-
-
- def test_unencryptedConnectionWithoutPasswords(self):
- """
- If the L{SSHUserAuthServer} is not advertising passwords, then an
- unencrypted connection should not cause any warnings or exceptions.
- This is a white box test.
- """
- # create a Portal without password authentication
- portal = Portal(self.realm)
- portal.registerChecker(PrivateKeyChecker())
-
- # no encryption
- clearAuthServer = userauth.SSHUserAuthServer()
- clearAuthServer.transport = FakeTransport(portal)
- clearAuthServer.transport.isEncrypted = lambda x: False
- clearAuthServer.serviceStarted()
- clearAuthServer.serviceStopped()
- self.assertEqual(clearAuthServer.supportedAuthentications,
- ['publickey'])
-
- # only encrypt incoming (the direction the password is sent)
- halfAuthServer = userauth.SSHUserAuthServer()
- halfAuthServer.transport = FakeTransport(portal)
- halfAuthServer.transport.isEncrypted = lambda x: x == 'in'
- halfAuthServer.serviceStarted()
- halfAuthServer.serviceStopped()
- self.assertEqual(clearAuthServer.supportedAuthentications,
- ['publickey'])
-
-
- def test_loginTimeout(self):
- """
- Test that the login times out.
- """
- timeoutAuthServer = userauth.SSHUserAuthServer()
- timeoutAuthServer.clock = task.Clock()
- timeoutAuthServer.transport = FakeTransport(self.portal)
- timeoutAuthServer.serviceStarted()
- timeoutAuthServer.clock.advance(11 * 60 * 60)
- timeoutAuthServer.serviceStopped()
- self.assertEqual(timeoutAuthServer.transport.packets,
- [(transport.MSG_DISCONNECT,
- '\x00' * 3 +
- chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
- NS("you took too long") + NS(''))])
- self.assertTrue(timeoutAuthServer.transport.lostConnection)
-
-
- def test_cancelLoginTimeout(self):
- """
- Test that stopping the service also stops the login timeout.
- """
- timeoutAuthServer = userauth.SSHUserAuthServer()
- timeoutAuthServer.clock = task.Clock()
- timeoutAuthServer.transport = FakeTransport(self.portal)
- timeoutAuthServer.serviceStarted()
- timeoutAuthServer.serviceStopped()
- timeoutAuthServer.clock.advance(11 * 60 * 60)
- self.assertEqual(timeoutAuthServer.transport.packets, [])
- self.assertFalse(timeoutAuthServer.transport.lostConnection)
-
-
- def test_tooManyAttempts(self):
- """
- Test that the server disconnects if the client fails authentication
- too many times.
- """
- packet = NS('foo') + NS('none') + NS('password') + chr(0) + NS('bar')
- self.authServer.clock = task.Clock()
- for i in range(21):
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- self.authServer.clock.advance(2)
- def check(ignored):
- self.assertEqual(self.authServer.transport.packets[-1],
- (transport.MSG_DISCONNECT,
- '\x00' * 3 +
- chr(transport.DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE) +
- NS("too many bad auths") + NS('')))
- return d.addCallback(check)
-
-
- def test_failIfUnknownService(self):
- """
- If the user requests a service that we don't support, the
- authentication should fail.
- """
- packet = NS('foo') + NS('') + NS('password') + chr(0) + NS('foo')
- self.authServer.clock = task.Clock()
- d = self.authServer.ssh_USERAUTH_REQUEST(packet)
- return d.addCallback(self._checkFailed)
-
-
- def test__pamConvErrors(self):
- """
- _pamConv should fail if it gets a message that's not 1 or 2.
- """
- def secondTest(ignored):
- d2 = self.authServer._pamConv([('', 90)])
- return self.assertFailure(d2, ConchError)
-
- d = self.authServer._pamConv([('', 3)])
- return self.assertFailure(d, ConchError).addCallback(secondTest)
-
-
- def test_tryAuthEdgeCases(self):
- """
- tryAuth() has two edge cases that are difficult to reach.
-
- 1) an authentication method auth_* returns None instead of a Deferred.
- 2) an authentication type that is defined does not have a matching
- auth_* method.
-
- Both these cases should return a Deferred which fails with a
- ConchError.
- """
- def mockAuth(packet):
- return None
-
- self.patch(self.authServer, 'auth_publickey', mockAuth) # first case
- self.patch(self.authServer, 'auth_password', None) # second case
-
- def secondTest(ignored):
- d2 = self.authServer.tryAuth('password', None, None)
- return self.assertFailure(d2, ConchError)
-
- d1 = self.authServer.tryAuth('publickey', None, None)
- return self.assertFailure(d1, ConchError).addCallback(secondTest)
-
-
-
-
-class SSHUserAuthClientTestCase(unittest.TestCase):
- """
- Tests for SSHUserAuthClient.
- """
-
-
- if keys is None:
- skip = "cannot run w/o PyCrypto"
-
-
- def setUp(self):
- self.authClient = ClientUserAuth('foo', FakeTransport.Service())
- self.authClient.transport = FakeTransport(None)
- self.authClient.transport.sessionID = 'test'
- self.authClient.serviceStarted()
-
-
- def tearDown(self):
- self.authClient.serviceStopped()
- self.authClient = None
-
-
- def test_init(self):
- """
- Test that client is initialized properly.
- """
- self.assertEqual(self.authClient.user, 'foo')
- self.assertEqual(self.authClient.instance.name, 'nancy')
- self.assertEqual(self.authClient.transport.packets,
- [(userauth.MSG_USERAUTH_REQUEST, NS('foo') + NS('nancy')
- + NS('none'))])
-
-
- def test_USERAUTH_SUCCESS(self):
- """
- Test that the client succeeds properly.
- """
- instance = [None]
- def stubSetService(service):
- instance[0] = service
- self.authClient.transport.setService = stubSetService
- self.authClient.ssh_USERAUTH_SUCCESS('')
- self.assertEqual(instance[0], self.authClient.instance)
-
-
- def test_publickey(self):
- """
- Test that the client can authenticate with a public key.
- """
- self.authClient.ssh_USERAUTH_FAILURE(NS('publickey') + '\x00')
- self.assertEqual(self.authClient.transport.packets[-1],
- (userauth.MSG_USERAUTH_REQUEST, NS('foo') + NS('nancy')
- + NS('publickey') + '\x00' + NS('ssh-dss')
- + NS(keys.Key.fromString(
- keydata.publicDSA_openssh).blob())))
- # that key isn't good
- self.authClient.ssh_USERAUTH_FAILURE(NS('publickey') + '\x00')
- blob = NS(keys.Key.fromString(keydata.publicRSA_openssh).blob())
- self.assertEqual(self.authClient.transport.packets[-1],
- (userauth.MSG_USERAUTH_REQUEST, (NS('foo') + NS('nancy')
- + NS('publickey') + '\x00'+ NS('ssh-rsa') + blob)))
- self.authClient.ssh_USERAUTH_PK_OK(NS('ssh-rsa')
- + NS(keys.Key.fromString(keydata.publicRSA_openssh).blob()))
- sigData = (NS(self.authClient.transport.sessionID)
- + chr(userauth.MSG_USERAUTH_REQUEST) + NS('foo')
- + NS('nancy') + NS('publickey') + '\x01' + NS('ssh-rsa')
- + blob)
- obj = keys.Key.fromString(keydata.privateRSA_openssh)
- self.assertEqual(self.authClient.transport.packets[-1],
- (userauth.MSG_USERAUTH_REQUEST, NS('foo') + NS('nancy')
- + NS('publickey') + '\x01' + NS('ssh-rsa') + blob
- + NS(obj.sign(sigData))))
-
-
- def test_publickey_without_privatekey(self):
- """
- If the SSHUserAuthClient doesn't return anything from signData,
- the client should start the authentication over again by requesting
- 'none' authentication.
- """
- authClient = ClientAuthWithoutPrivateKey('foo',
- FakeTransport.Service())
-
- authClient.transport = FakeTransport(None)
- authClient.transport.sessionID = 'test'
- authClient.serviceStarted()
- authClient.tryAuth('publickey')
- authClient.transport.packets = []
- self.assertIs(authClient.ssh_USERAUTH_PK_OK(''), None)
- self.assertEqual(authClient.transport.packets, [
- (userauth.MSG_USERAUTH_REQUEST, NS('foo') + NS('nancy') +
- NS('none'))])
-
-
- def test_no_publickey(self):
- """
- If there's no public key, auth_publickey should return a Deferred
- called back with a False value.
- """
- self.authClient.getPublicKey = lambda x: None
- d = self.authClient.tryAuth('publickey')
- def check(result):
- self.assertFalse(result)
- return d.addCallback(check)
-
- def test_password(self):
- """
- Test that the client can authentication with a password. This
- includes changing the password.
- """
- self.authClient.ssh_USERAUTH_FAILURE(NS('password') + '\x00')
- self.assertEqual(self.authClient.transport.packets[-1],
- (userauth.MSG_USERAUTH_REQUEST, NS('foo') + NS('nancy')
- + NS('password') + '\x00' + NS('foo')))
- self.authClient.ssh_USERAUTH_PK_OK(NS('') + NS(''))
- self.assertEqual(self.authClient.transport.packets[-1],
- (userauth.MSG_USERAUTH_REQUEST, NS('foo') + NS('nancy')
- + NS('password') + '\xff' + NS('foo') * 2))
-
-
- def test_no_password(self):
- """
- If getPassword returns None, tryAuth should return False.
- """
- self.authClient.getPassword = lambda: None
- self.assertFalse(self.authClient.tryAuth('password'))
-
-
- def test_keyboardInteractive(self):
- """
- Test that the client can authenticate using keyboard-interactive
- authentication.
- """
- self.authClient.ssh_USERAUTH_FAILURE(NS('keyboard-interactive')
- + '\x00')
- self.assertEqual(self.authClient.transport.packets[-1],
- (userauth.MSG_USERAUTH_REQUEST, NS('foo') + NS('nancy')
- + NS('keyboard-interactive') + NS('')*2))
- self.authClient.ssh_USERAUTH_PK_OK(NS('')*3 + '\x00\x00\x00\x02'
- + NS('Name: ') + '\xff' + NS('Password: ') + '\x00')
- self.assertEqual(self.authClient.transport.packets[-1],
- (userauth.MSG_USERAUTH_INFO_RESPONSE, '\x00\x00\x00\x02'
- + NS('foo')*2))
-
-
- def test_USERAUTH_PK_OK_unknown_method(self):
- """
- If C{SSHUserAuthClient} gets a MSG_USERAUTH_PK_OK packet when it's not
- expecting it, it should fail the current authentication and move on to
- the next type.
- """
- self.authClient.lastAuth = 'unknown'
- self.authClient.transport.packets = []
- self.authClient.ssh_USERAUTH_PK_OK('')
- self.assertEqual(self.authClient.transport.packets,
- [(userauth.MSG_USERAUTH_REQUEST, NS('foo') +
- NS('nancy') + NS('none'))])
-
-
- def test_USERAUTH_FAILURE_sorting(self):
- """
- ssh_USERAUTH_FAILURE should sort the methods by their position
- in SSHUserAuthClient.preferredOrder. Methods that are not in
- preferredOrder should be sorted at the end of that list.
- """
- def auth_firstmethod():
- self.authClient.transport.sendPacket(255, 'here is data')
- def auth_anothermethod():
- self.authClient.transport.sendPacket(254, 'other data')
- return True
- self.authClient.auth_firstmethod = auth_firstmethod
- self.authClient.auth_anothermethod = auth_anothermethod
-
- # although they shouldn't get called, method callbacks auth_* MUST
- # exist in order for the test to work properly.
- self.authClient.ssh_USERAUTH_FAILURE(NS('anothermethod,password') +
- '\x00')
- # should send password packet
- self.assertEqual(self.authClient.transport.packets[-1],
- (userauth.MSG_USERAUTH_REQUEST, NS('foo') + NS('nancy')
- + NS('password') + '\x00' + NS('foo')))
- self.authClient.ssh_USERAUTH_FAILURE(
- NS('firstmethod,anothermethod,password') + '\xff')
- self.assertEqual(self.authClient.transport.packets[-2:],
- [(255, 'here is data'), (254, 'other data')])
-
-
- def test_disconnectIfNoMoreAuthentication(self):
- """
- If there are no more available user authentication messages,
- the SSHUserAuthClient should disconnect with code
- DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE.
- """
- self.authClient.ssh_USERAUTH_FAILURE(NS('password') + '\x00')
- self.authClient.ssh_USERAUTH_FAILURE(NS('password') + '\xff')
- self.assertEqual(self.authClient.transport.packets[-1],
- (transport.MSG_DISCONNECT, '\x00\x00\x00\x0e' +
- NS('no more authentication methods available') +
- '\x00\x00\x00\x00'))
-
-
- def test_ebAuth(self):
- """
- _ebAuth (the generic authentication error handler) should send
- a request for the 'none' authentication method.
- """
- self.authClient.transport.packets = []
- self.authClient._ebAuth(None)
- self.assertEqual(self.authClient.transport.packets,
- [(userauth.MSG_USERAUTH_REQUEST, NS('foo') + NS('nancy')
- + NS('none'))])
-
-
- def test_defaults(self):
- """
- getPublicKey() should return None. getPrivateKey() should return a
- failed Deferred. getPassword() should return a failed Deferred.
- getGenericAnswers() should return a failed Deferred.
- """
- authClient = userauth.SSHUserAuthClient('foo', FakeTransport.Service())
- self.assertIs(authClient.getPublicKey(), None)
- def check(result):
- result.trap(NotImplementedError)
- d = authClient.getPassword()
- return d.addCallback(self.fail).addErrback(check2)
- def check2(result):
- result.trap(NotImplementedError)
- d = authClient.getGenericAnswers(None, None, None)
- return d.addCallback(self.fail).addErrback(check3)
- def check3(result):
- result.trap(NotImplementedError)
- d = authClient.getPrivateKey()
- return d.addCallback(self.fail).addErrback(check)
-
-
-
-class LoopbackTestCase(unittest.TestCase):
-
-
- if keys is None:
- skip = "cannot run w/o PyCrypto or PyASN1"
-
-
- class Factory:
- class Service:
- name = 'TestService'
-
-
- def serviceStarted(self):
- self.transport.loseConnection()
-
-
- def serviceStopped(self):
- pass
-
-
- def getService(self, avatar, name):
- return self.Service
-
-
- def test_loopback(self):
- """
- Test that the userauth server and client play nicely with each other.
- """
- server = userauth.SSHUserAuthServer()
- client = ClientUserAuth('foo', self.Factory.Service())
-
- # set up transports
- server.transport = transport.SSHTransportBase()
- server.transport.service = server
- server.transport.isEncrypted = lambda x: True
- client.transport = transport.SSHTransportBase()
- client.transport.service = client
- server.transport.sessionID = client.transport.sessionID = ''
- # don't send key exchange packet
- server.transport.sendKexInit = client.transport.sendKexInit = \
- lambda: None
-
- # set up server authentication
- server.transport.factory = self.Factory()
- server.passwordDelay = 0 # remove bad password delay
- realm = Realm()
- portal = Portal(realm)
- checker = SSHProtocolChecker()
- checker.registerChecker(PasswordChecker())
- checker.registerChecker(PrivateKeyChecker())
- checker.registerChecker(PAMChecker())
- checker.areDone = lambda aId: (
- len(checker.successfulCredentials[aId]) == 3)
- portal.registerChecker(checker)
- server.transport.factory.portal = portal
-
- d = loopback.loopbackAsync(server.transport, client.transport)
- server.transport.transport.logPrefix = lambda: '_ServerLoopback'
- client.transport.transport.logPrefix = lambda: '_ClientLoopback'
-
- server.serviceStarted()
- client.serviceStarted()
-
- def check(ignored):
- self.assertEqual(server.transport.service.name, 'TestService')
- return d.addCallback(check)
-
-
-
-class ModuleInitializationTestCase(unittest.TestCase):
- if keys is None:
- skip = "cannot run w/o PyCrypto or PyASN1"
-
-
- def test_messages(self):
- # Several message types have value 60, check that MSG_USERAUTH_PK_OK
- # is always the one which is mapped.
- self.assertEqual(userauth.SSHUserAuthServer.protocolMessages[60],
- 'MSG_USERAUTH_PK_OK')
- self.assertEqual(userauth.SSHUserAuthClient.protocolMessages[60],
- 'MSG_USERAUTH_PK_OK')
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_window.py b/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_window.py
deleted file mode 100644
index 0895cf9..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/test/test_window.py
+++ /dev/null
@@ -1,67 +0,0 @@
-
-"""
-Tests for the insults windowing module, L{twisted.conch.insults.window}.
-"""
-
-from twisted.trial.unittest import TestCase
-
-from twisted.conch.insults.window import TopWindow, ScrolledArea, TextOutput
-
-
-class TopWindowTests(TestCase):
- """
- Tests for L{TopWindow}, the root window container class.
- """
-
- def test_paintScheduling(self):
- """
- Verify that L{TopWindow.repaint} schedules an actual paint to occur
- using the scheduling object passed to its initializer.
- """
- paints = []
- scheduled = []
- root = TopWindow(lambda: paints.append(None), scheduled.append)
-
- # Nothing should have happened yet.
- self.assertEqual(paints, [])
- self.assertEqual(scheduled, [])
-
- # Cause a paint to be scheduled.
- root.repaint()
- self.assertEqual(paints, [])
- self.assertEqual(len(scheduled), 1)
-
- # Do another one to verify nothing else happens as long as the previous
- # one is still pending.
- root.repaint()
- self.assertEqual(paints, [])
- self.assertEqual(len(scheduled), 1)
-
- # Run the actual paint call.
- scheduled.pop()()
- self.assertEqual(len(paints), 1)
- self.assertEqual(scheduled, [])
-
- # Do one more to verify that now that the previous one is finished
- # future paints will succeed.
- root.repaint()
- self.assertEqual(len(paints), 1)
- self.assertEqual(len(scheduled), 1)
-
-
-
-class ScrolledAreaTests(TestCase):
- """
- Tests for L{ScrolledArea}, a widget which creates a viewport containing
- another widget and can reposition that viewport using scrollbars.
- """
- def test_parent(self):
- """
- The parent of the widget passed to L{ScrolledArea} is set to a new
- L{Viewport} created by the L{ScrolledArea} which itself has the
- L{ScrolledArea} instance as its parent.
- """
- widget = TextOutput()
- scrolled = ScrolledArea(widget)
- self.assertIs(widget.parent, scrolled._viewport)
- self.assertIs(scrolled._viewport.parent, scrolled)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/topfiles/NEWS b/Darwin/lib/python2.7/site-packages/twisted/conch/topfiles/NEWS
deleted file mode 100644
index ec4181e..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/topfiles/NEWS
+++ /dev/null
@@ -1,506 +0,0 @@
-Ticket numbers in this file can be looked up by visiting
-http://twistedmatrix.com/trac/ticket/
-
-Twisted Conch 14.0.0 (2014-05-08)
-=================================
-
-Improved Documentation
-----------------------
- - The docstring for twisted.conch.ssh.userauth.SSHUserAuthClient is
- now clearer on how the preferredOrder instance variable is handled.
- (#6850)
-
-Other
------
- - #6696, #6807, #7054
-
-
-Twisted Conch 13.2.0 (2013-10-29)
-=================================
-
-Features
---------
- - ckeygen now accepts --no-passphrase to generate unprotected keys.
- (#5998)
- - twisted.conch.endpoints.SSHCommandClientEndpoint.newConnection now
- supplies a convenient default for the `ui` parameter if a value is
- not passed in for it. (#6550)
-
-Bugfixes
---------
- - ckeygen --changepass now doesn't delete unencrypted keys or raise
- an exception on encrypted ones. (#5894)
- - twisted.conch.endpoints.SSHCommandClientEndpoint now doesn't try
- password authentication if there is no password specified. (#6553)
- - twisted.conch.endpoints.SSHCommandClientEndpoint now uses the
- standard SSH port if no port is specified. (#6631)
-
-Other
------
- - #5387, #6220
-
-
-Twisted Conch 13.1.0 (2013-06-23)
-=================================
-
-Features
---------
- - twisted.conch.endpoints.SSHCommandClientEndpoint is a new
- IStreamClientEndpoint which supports connecting a protocol to the
- stdio of a command running on a remote host via an SSH connection.
- (#4698)
- - twisted.conch.client.knownhosts.KnownHostsFile now has a public
- `savePath` attribute giving the filesystem path where the known
- hosts data is saved to and loaded from. (#6255)
- - twisted.conch.endpoints.SSHCommandClientEndpoint.connect() returns
- a cancellable Deferred when using new connections. (#6532)
-
-Other
------
- - #5386, #6342, #6386, #6405, #6541
-
-
-Twisted Conch 13.0.0 (2013-03-19)
-=================================
-
-Features
---------
- - twisted.conch.client.knownhosts.KnownHostsFile now takes care not
- to overwrite changes to its save file made behind its back, making
- it safer to use with the same known_hosts file as is being used by
- other software. (#6256)
-
-Other
------
- - #5864, #6257, #6297
-
-
-Twisted Conch 12.3.0 (2012-12-20)
-=================================
-
-Bugfixes
---------
- - Passing multiple --auth arguments to conch now correctly adds all
- the specified checkers to the conch server (#5881)
- - ckeygen --showpub now uses OPENSSH as default display, instead of
- breaking because no display type was passed. (#5889)
- - ckeygen --showpub catches EncryptedKeyError instead of BadKeyError
- to detect that a key needs to be decrypted with a passphrase.
- (#5890)
-
-Other
------
- - #5923
-
-
-Twisted Conch 12.2.0 (2012-08-26)
-=================================
-
-Features
---------
- - twisted.conch.ssh.transport.SSHTransport now returns an
- SSHTransportAddress from the getPeer() and getHost() methods.
- (#2997)
-
-Bugfixes
---------
- - twisted.conch now supports commercial SSH implementations which
- don't comply with the IETF standard (#1902)
- - twisted.conch.ssh.userauth now works correctly with hash
- randomization enabled. (#5776)
- - twisted.conch no longer relies on __builtins__ being a dict, which
- is a purely CPython implementation detail (#5779)
-
-Other
------
- - #5496, #5617, #5700, #5748, #5777
-
-
-Twisted Conch 12.1.0 (2012-06-02)
-=================================
-
-Features
---------
- - twisted.conch.tap now supports cred plugins (#4753)
-
-Bugfixes
---------
- - twisted.conch.client.knownhosts now handles errors encountered
- parsing hashed entries in a known hosts file. (#5616)
-
-Improved Documentation
-----------------------
- - Conch examples window.tac and telnet_echo.tac now have better
- explanations. (#5590)
-
-Other
------
- - #5580
-
-
-Twisted Conch 12.0.0 (2012-02-10)
-=================================
-
-Features
---------
- - use Python shadow module for authentication if it's available
- (#3242)
-
-Bugfixes
---------
- - twisted.conch.ssh.transport.messages no longer ends with with old
- message IDs on platforms with differing dict() orderings (#5352)
-
-Other
------
- - #5225
-
-
-Twisted Conch 11.1.0 (2011-11-15)
-=================================
-
-Features
---------
- - twisted.conch.ssh.filetransfer.FileTransferClient now handles short
- status messages, not strictly allowed by the RFC, but sent by some
- SSH implementations. (#3009)
- - twisted.conch.manhole now supports CTRL-A and CTRL-E to trigger
- HOME and END functions respectively. (#5252)
-
-Bugfixes
---------
- - When run from an unpacked source tarball or a VCS checkout, the
- bin/conch/ scripts will now use the version of Twisted they are
- part of. (#3526)
- - twisted.conch.insults.window.ScrolledArea now passes no extra
- arguments to object.__init__ (which works on more versions of
- Python). (#4197)
- - twisted.conch.telnet.ITelnetProtocol now has the correct signature
- for its unhandledSubnegotiation() method. (#4751)
- - twisted.conch.ssh.userauth.SSHUserAuthClient now more closely
- follows the RFC 4251 definition of boolean values when negotiating
- for key-based authentication, allowing better interoperability with
- other SSH implementations. (#5241)
- - twisted.conch.recvline.RecvLine now ignores certain function keys
- in its keystrokeReceived method instead of raising an exception.
- (#5246)
-
-Deprecations and Removals
--------------------------
- - The --user option to `twistd manhole' has been removed as it was
- dead code with no functionality associated with it. (#5283)
-
-Other
------
- - #5107, #5256, #5349
-
-
-Twisted Conch 11.0.0 (2011-04-01)
-=================================
-
-Bugfixes
---------
- - The transport for subsystem protocols now declares that it
- implements ITransport and implements the getHost and getPeer
- methods. (#2453)
- - twisted.conch.ssh.transport.SSHTransportBase now responds to key
- exchange messages at any time during a connection (instead of only
- at connection setup). It also queues non-key exchange messages
- sent during key exchange to avoid corrupting the connection state.
- (#4395)
- - Importing twisted.conch.ssh.common no longer breaks pow(base, exp[,
- modulus]) when the gmpy package is installed and base is not an
- integer. (#4803)
- - twisted.conch.ls.lsLine now returns a time string which does not
- consider the locale. (#4937)
-
-Improved Documentation
-----------------------
- - Changed the man page for ckeygen to accurately reflect what it
- does, and corrected its synposis so that a second "ckeygen" is not
- a required part of the ckeygen command line. (#4738)
-
-Other
------
- - #2112
-
-
-Twisted Conch 10.2.0 (2010-11-29)
-=================================
-
-Bugfixes
---------
- - twisted.conch.ssh.factory.SSHFactory no longer disables coredumps.
- (#2715)
- - The Deferred returned by twisted.conch.telnet.TelnetTransport.will
- now fires with an OptionRefused failure if the peer responds with a
- refusal for the option negotiation. (#4231)
- - SSHServerTransport and SSHClientTransport in
- twisted.conch.ssh.transport no longer use PyCrypto to generate
- random numbers for DH KEX. They also now generate values from the
- full valid range, rather than only half of it. (#4469)
- - twisted.conch.ssh.connection.SSHConnection now errbacks leftover
- request deferreds on connection shutdown. (#4483)
-
-Other
------
- - #4677
-
-
-Twisted Conch 10.1.0 (2010-06-27)
-=================================
-
-Features
---------
- - twisted.conch.ssh.transport.SSHTransportBase now allows supported
- ssh protocol versions to be overriden. (#4428)
-
-Bugfixes
---------
- - SSHSessionProcessProtocol now doesn't close the session when stdin
- is closed, but instead when both stdout and stderr are. (#4350)
- - The 'cftp' command-line tool will no longer encounter an
- intermittent error, crashing at startup with a ZeroDivisionError
- while trying to report progress. (#4463)
- - twisted.conch.ssh.connection.SSHConnection now replies to requests
- to open an unknown channel with a OPEN_UNKNOWN_CHANNEL_TYPE message
- instead of closing the connection. (#4490)
-
-Deprecations and Removals
--------------------------
- - twisted.conch.insults.client was deprecated. (#4095)
- - twisted.conch.insults.colors has been deprecated. Please use
- twisted.conch.insults.helper instead. (#4096)
- - Removed twisted.conch.ssh.asn1, which has been deprecated since
- Twisted 9.0. (#4097)
- - Removed twisted.conch.ssh.common.Entropy, as Entropy.get_bytes has
- been deprecated since 2007 and Entropy.get_bytes was the only
- attribute of Entropy. (#4098)
- - Removed twisted.conch.ssh.keys.getPublicKeyString, which has been
- deprecated since 2007. Also updated the conch examples
- sshsimpleserver.py and sshsimpleclient.py to reflect this removal.
- (#4099)
- - Removed twisted.conch.ssh.keys.makePublicKeyString, which has been
- deprecated since 2007. (#4100)
- - Removed twisted.conch.ssh.keys.getPublicKeyObject, which has been
- deprecated since 2007. (#4101)
- - Removed twisted.conch.ssh.keys.getPrivateKeyObject, which has been
- deprecated since 2007. Also updated the conch examples to reflect
- this removal. (#4102)
- - Removed twisted.conch.ssh.keys.makePrivateKeyString, which has been
- deprecated since 2007. (#4103)
- - Removed twisted.conch.ssh.keys.makePublicKeyBlob, which has been
- deprecated since 2007. (#4104)
- - Removed twisted.conch.ssh.keys.signData,
- twisted.conch.ssh.keys.verifySignature, and
- twisted.conch.ssh.keys.printKey, which have been deprecated since
- 2007. (#4105)
-
-Other
------
- - #3849, #4408, #4454
-
-
-Twisted Conch 10.0.0 (2010-03-01)
-=================================
-
-Bugfixes
---------
- - twisted.conch.checkers.SSHPublicKeyDatabase now looks in the
- correct user directory for authorized_keys files. (#3984)
-
- - twisted.conch.ssh.SSHUserAuthClient now honors preferredOrder when
- authenticating. (#4266)
-
-Other
------
- - #2391, #4203, #4265
-
-
-Twisted Conch 9.0.0 (2009-11-24)
-================================
-
-Fixes
------
- - The SSH key parser has been removed and conch now uses pyASN1 to parse keys.
- This should fix a number of cases where parsing a key would fail, but it now
- requires users to have pyASN1 installed (#3391)
- - The time field on SFTP file listings should now be correct (#3503)
- - The day field on SFTP file listings should now be correct on Windows (#3503)
- - The "cftp" sftp client now truncates files it is uploading over (#2519)
- - The telnet server protocol can now properly respond to subnegotiation
- requests (#3655)
- - Tests and factoring of the SSHv2 server implementation are now much better
- (#2682)
- - The SSHv2 server now sends "exit-signal" messages to the client, instead of
- raising an exception, when a process dies due to a signal (#2687)
- - cftp's client-side "exec" command now uses /bin/sh if the current user has
- no shell (#3914)
-
-Deprecations and Removals
--------------------------
- - The buggy SSH connection sharing feature of the SSHv2 client was removed
- (#3498)
- - Use of strings and PyCrypto objects to represent keys is deprecated in favor
- of using Conch Key objects (#2682)
-
-Other
------
- - #3548, #3537, #3551, #3220, #3568, #3689, #3709, #3809, #2763, #3540, #3750,
- #3897, #3813, #3871, #3916, #4047, #3940, #4050
-
-
-Conch 8.2.0 (2008-12-16)
-========================
-
-Features
---------
- - The type of the protocols instantiated by SSHFactory is now parameterized
- (#3443)
-
-Fixes
------
- - A file descriptor leak has been fixed (#3213, #1789)
- - "File Already Exists" errors are now handled more correctly (#3033)
- - Handling of CR IAC in TelnetClient is now improved (#3305)
- - SSHAgent is no longer completely unusable (#3332)
- - The performance of insults.ClientProtocol is now greatly increased by
- delivering more than one byte at a time to application code (#3386)
- - Manhole and the conch server no longer need to be run as root when not
- necessary (#2607)
- - The value of FILEXFER_ATTR_ACMODTIME has been corrected (#2902)
- - The management of known_hosts and host key verification has been overhauled
- (#1376, #1301, #3494, #3496, #1292, #3499)
-
-Other
------
- - #3193, #1633
-
-
-8.1.0 (2008-05-18)
-==================
-
-Fixes
------
- - A regression was fixed whereby the publicKeys and privateKeys attributes of
- SSHFactory would not be interpreted as strings (#3141)
- - The sshsimpleserver.py example had a minor bug fix (#3135)
- - The deprecated mktap API is no longer used (#3127)
- - An infelicity was fixed whereby a NameError would be raised in certain
- circumstances during authentication when a ConchError should have been
- (#3154)
- - A workaround was added to conch.insults for a bug in gnome-terminal whereby
- it would not scroll correctly (#3189)
-
-
-8.0.0 (2008-03-17)
-==================
-
-Features
---------
- - Add DEC private mode manipulation methods to ITerminalTransport. (#2403)
-
-Fixes
------
- - Parameterize the scheduler function used by the insults TopWindow widget.
- This change breaks backwards compatibility in the TopWindow initializer.
- (#2413)
- - Notify subsystems, like SFTP, of connection close. (#2421)
- - Change the process file descriptor "connection lost" code to reverse the
- setNonBlocking operation done during initialization. (#2371)
- - Change ConsoleManhole to wait for connectionLost notification before
- stopping the reactor. (#2123, #2371)
- - Make SSHUserAuthServer.ssh_USERAUTH_REQUEST return a Deferred. (#2528)
- - Manhole's initializer calls its parent class's initializer with its
- namespace argument. (#2587)
- - Handle ^C during input line continuation in manhole by updating the prompt
- and line buffer correctly. (#2663)
- - Make twisted.conch.telnet.Telnet by default reject all attempts to enable
- options. (#1967)
- - Reduce the number of calls into application code to deliver application-level
- data in twisted.conch.telnet.Telnet.dataReceived (#2107)
- - Fix definition and management of extended attributes in conch file transfer.
- (#3010)
- - Fix parsing of OpenSSH-generated RSA keys with differing ASN.1 packing style.
- (#3008)
- - Fix handling of missing $HOME in twisted.conch.client.unix. (#3061)
-
-Misc
-----
- - #2267, #2378, #2604, #2707, #2341, #2685, #2679, #2912, #2977, #2678, #2709
- #2063, #2847
-
-
-0.8.0 (2007-01-06)
-==================
-
-Features
---------
- - Manhole now supports Ctrl-l to emulate the same behavior in the
- Python interactive interpreter (#1565)
- - Python 2.5 is now supported (#1867)
-
-Misc
-----
- - #1673, #1636, #1892, #1943, #2057, #1180, #1185, #2148, #2159, #2291,
-
-Deprecations and Removals
--------------------------
-
- - The old twisted.cred API (Identities, Authorizers, etc) is no
- longer supported (#1440)
-
-
-0.7.0 (2006-05-21)
-==================
-
-Features
---------
- - Timeout support for ExpectableBuffer.expect()
-
-Fixes
------
- - ~5x speedup for bulk data transfer (#1325)
- - Misc: #1428
-
-0.6.0:
-
- Bugfixes and improvements in SSH support and Insults:
- - PAM authenticator support factored out into twisted.cred
- - Poorly supported next-line terminal operation replaced with simple \r\n
-
- New functionality:
- - An ITerminalTransport implementation with expect-like features
- - Support for the "none" SSH cipher
- - Insults support for handling more keystrokes and more methods for
- terminal manipulation
- - New, simple insults-based widget library added
-
- Better test coverage:
- - Dependence on `localhost' name removed
- - Some timing-sensitive tests changed to be more reliable
- - Process spawning tests initialize environment more robustly
-
-0.5.0:
-
- Many improvements to SSH support. Here's some in particular:
- - Add --reconnect option to conch binary
- - utmp/wtmp logging
- - Unix login improvements, PAM support
- - Add "cftp" -- Conch SFTP.
- - Deferred retrieval of public keys is supported
- - PAM support for client and server
- - Bugfixes:
- - fix conch failing to exit, and hangs.
- - Remote->Local forwarding
- - Channel closing
- - Invalid known_host writing
- - Many others
-
- New functionality:
- - twisted.conch.telnet: new, much improved telnet implementation.
- - twisted.conch.insults: Basic curses-like terminal support (server-side).
- - twisted.conch.manhole: new interactive python interactive interpreter,
- can be used with conch's telnet, ssh, or on the console.
- - Main features: Syntax coloring, line editing, and useful interactive
- handling of Deferreds.
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/topfiles/README b/Darwin/lib/python2.7/site-packages/twisted/conch/topfiles/README
deleted file mode 100644
index 6219c04..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/topfiles/README
+++ /dev/null
@@ -1,11 +0,0 @@
-Twisted Conch 14.0.0
-
-Twisted Conch depends on Twisted Core and on Python Crypto extensions
-().
-
-The pyasn1 module () is also required.
-
-gmpy () is strongly recommended to improve
-performance.
-
-Twisted Conch includes a couple simple GUI applications which depend on Tkinter.
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ttymodes.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ttymodes.py
deleted file mode 100644
index 00b4495..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ttymodes.py
+++ /dev/null
@@ -1,121 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-import tty
-# this module was autogenerated.
-
-VINTR = 1
-VQUIT = 2
-VERASE = 3
-VKILL = 4
-VEOF = 5
-VEOL = 6
-VEOL2 = 7
-VSTART = 8
-VSTOP = 9
-VSUSP = 10
-VDSUSP = 11
-VREPRINT = 12
-VWERASE = 13
-VLNEXT = 14
-VFLUSH = 15
-VSWTCH = 16
-VSTATUS = 17
-VDISCARD = 18
-IGNPAR = 30
-PARMRK = 31
-INPCK = 32
-ISTRIP = 33
-INLCR = 34
-IGNCR = 35
-ICRNL = 36
-IUCLC = 37
-IXON = 38
-IXANY = 39
-IXOFF = 40
-IMAXBEL = 41
-ISIG = 50
-ICANON = 51
-XCASE = 52
-ECHO = 53
-ECHOE = 54
-ECHOK = 55
-ECHONL = 56
-NOFLSH = 57
-TOSTOP = 58
-IEXTEN = 59
-ECHOCTL = 60
-ECHOKE = 61
-PENDIN = 62
-OPOST = 70
-OLCUC = 71
-ONLCR = 72
-OCRNL = 73
-ONOCR = 74
-ONLRET = 75
-CS7 = 90
-CS8 = 91
-PARENB = 92
-PARODD = 93
-TTY_OP_ISPEED = 128
-TTY_OP_OSPEED = 129
-
-TTYMODES = {
- 1 : 'VINTR',
- 2 : 'VQUIT',
- 3 : 'VERASE',
- 4 : 'VKILL',
- 5 : 'VEOF',
- 6 : 'VEOL',
- 7 : 'VEOL2',
- 8 : 'VSTART',
- 9 : 'VSTOP',
- 10 : 'VSUSP',
- 11 : 'VDSUSP',
- 12 : 'VREPRINT',
- 13 : 'VWERASE',
- 14 : 'VLNEXT',
- 15 : 'VFLUSH',
- 16 : 'VSWTCH',
- 17 : 'VSTATUS',
- 18 : 'VDISCARD',
- 30 : (tty.IFLAG, 'IGNPAR'),
- 31 : (tty.IFLAG, 'PARMRK'),
- 32 : (tty.IFLAG, 'INPCK'),
- 33 : (tty.IFLAG, 'ISTRIP'),
- 34 : (tty.IFLAG, 'INLCR'),
- 35 : (tty.IFLAG, 'IGNCR'),
- 36 : (tty.IFLAG, 'ICRNL'),
- 37 : (tty.IFLAG, 'IUCLC'),
- 38 : (tty.IFLAG, 'IXON'),
- 39 : (tty.IFLAG, 'IXANY'),
- 40 : (tty.IFLAG, 'IXOFF'),
- 41 : (tty.IFLAG, 'IMAXBEL'),
- 50 : (tty.LFLAG, 'ISIG'),
- 51 : (tty.LFLAG, 'ICANON'),
- 52 : (tty.LFLAG, 'XCASE'),
- 53 : (tty.LFLAG, 'ECHO'),
- 54 : (tty.LFLAG, 'ECHOE'),
- 55 : (tty.LFLAG, 'ECHOK'),
- 56 : (tty.LFLAG, 'ECHONL'),
- 57 : (tty.LFLAG, 'NOFLSH'),
- 58 : (tty.LFLAG, 'TOSTOP'),
- 59 : (tty.LFLAG, 'IEXTEN'),
- 60 : (tty.LFLAG, 'ECHOCTL'),
- 61 : (tty.LFLAG, 'ECHOKE'),
- 62 : (tty.LFLAG, 'PENDIN'),
- 70 : (tty.OFLAG, 'OPOST'),
- 71 : (tty.OFLAG, 'OLCUC'),
- 72 : (tty.OFLAG, 'ONLCR'),
- 73 : (tty.OFLAG, 'OCRNL'),
- 74 : (tty.OFLAG, 'ONOCR'),
- 75 : (tty.OFLAG, 'ONLRET'),
-# 90 : (tty.CFLAG, 'CS7'),
-# 91 : (tty.CFLAG, 'CS8'),
- 92 : (tty.CFLAG, 'PARENB'),
- 93 : (tty.CFLAG, 'PARODD'),
- 128 : 'ISPEED',
- 129 : 'OSPEED'
-}
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ui/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ui/__init__.py
deleted file mode 100644
index ea0eea8..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ui/__init__.py
+++ /dev/null
@@ -1,11 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-
-"""
-twisted.conch.ui is home to the UI elements for tkconch.
-
-Maintainer: Paul Swartz
-"""
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ui/ansi.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ui/ansi.py
deleted file mode 100644
index 9d5e616..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ui/ansi.py
+++ /dev/null
@@ -1,240 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-"""Module to parse ANSI escape sequences
-
-Maintainer: Jean-Paul Calderone
-"""
-
-import string
-
-# Twisted imports
-from twisted.python import log
-
-class ColorText:
- """
- Represents an element of text along with the texts colors and
- additional attributes.
- """
-
- # The colors to use
- COLORS = ('b', 'r', 'g', 'y', 'l', 'm', 'c', 'w')
- BOLD_COLORS = tuple([x.upper() for x in COLORS])
- BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(len(COLORS))
-
- # Color names
- COLOR_NAMES = (
- 'Black', 'Red', 'Green', 'Yellow', 'Blue', 'Magenta', 'Cyan', 'White'
- )
-
- def __init__(self, text, fg, bg, display, bold, underline, flash, reverse):
- self.text, self.fg, self.bg = text, fg, bg
- self.display = display
- self.bold = bold
- self.underline = underline
- self.flash = flash
- self.reverse = reverse
- if self.reverse:
- self.fg, self.bg = self.bg, self.fg
-
-
-class AnsiParser:
- """
- Parser class for ANSI codes.
- """
-
- # Terminators for cursor movement ansi controls - unsupported
- CURSOR_SET = ('H', 'f', 'A', 'B', 'C', 'D', 'R', 's', 'u', 'd','G')
-
- # Terminators for erasure ansi controls - unsupported
- ERASE_SET = ('J', 'K', 'P')
-
- # Terminators for mode change ansi controls - unsupported
- MODE_SET = ('h', 'l')
-
- # Terminators for keyboard assignment ansi controls - unsupported
- ASSIGN_SET = ('p',)
-
- # Terminators for color change ansi controls - supported
- COLOR_SET = ('m',)
-
- SETS = (CURSOR_SET, ERASE_SET, MODE_SET, ASSIGN_SET, COLOR_SET)
-
- def __init__(self, defaultFG, defaultBG):
- self.defaultFG, self.defaultBG = defaultFG, defaultBG
- self.currentFG, self.currentBG = self.defaultFG, self.defaultBG
- self.bold, self.flash, self.underline, self.reverse = 0, 0, 0, 0
- self.display = 1
- self.prepend = ''
-
-
- def stripEscapes(self, string):
- """
- Remove all ANSI color escapes from the given string.
- """
- result = ''
- show = 1
- i = 0
- L = len(string)
- while i < L:
- if show == 0 and string[i] in _sets:
- show = 1
- elif show:
- n = string.find('\x1B', i)
- if n == -1:
- return result + string[i:]
- else:
- result = result + string[i:n]
- i = n
- show = 0
- i = i + 1
- return result
-
- def writeString(self, colorstr):
- pass
-
- def parseString(self, str):
- """
- Turn a string input into a list of L{ColorText} elements.
- """
-
- if self.prepend:
- str = self.prepend + str
- self.prepend = ''
- parts = str.split('\x1B')
-
- if len(parts) == 1:
- self.writeString(self.formatText(parts[0]))
- else:
- self.writeString(self.formatText(parts[0]))
- for s in parts[1:]:
- L = len(s)
- i = 0
- type = None
- while i < L:
- if s[i] not in string.digits+'[;?':
- break
- i+=1
- if not s:
- self.prepend = '\x1b'
- return
- if s[0]!='[':
- self.writeString(self.formatText(s[i+1:]))
- continue
- else:
- s=s[1:]
- i-=1
- if i==L-1:
- self.prepend = '\x1b['
- return
- type = _setmap.get(s[i], None)
- if type is None:
- continue
-
- if type == AnsiParser.COLOR_SET:
- self.parseColor(s[:i + 1])
- s = s[i + 1:]
- self.writeString(self.formatText(s))
- elif type == AnsiParser.CURSOR_SET:
- cursor, s = s[:i+1], s[i+1:]
- self.parseCursor(cursor)
- self.writeString(self.formatText(s))
- elif type == AnsiParser.ERASE_SET:
- erase, s = s[:i+1], s[i+1:]
- self.parseErase(erase)
- self.writeString(self.formatText(s))
- elif type == AnsiParser.MODE_SET:
- mode, s = s[:i+1], s[i+1:]
- #self.parseErase('2J')
- self.writeString(self.formatText(s))
- elif i == L:
- self.prepend = '\x1B[' + s
- else:
- log.msg('Unhandled ANSI control type: %c' % (s[i],))
- s = s[i + 1:]
- self.writeString(self.formatText(s))
-
- def parseColor(self, str):
- """
- Handle a single ANSI color sequence
- """
- # Drop the trailing 'm'
- str = str[:-1]
-
- if not str:
- str = '0'
-
- try:
- parts = map(int, str.split(';'))
- except ValueError:
- log.msg('Invalid ANSI color sequence (%d): %s' % (len(str), str))
- self.currentFG, self.currentBG = self.defaultFG, self.defaultBG
- return
-
- for x in parts:
- if x == 0:
- self.currentFG, self.currentBG = self.defaultFG, self.defaultBG
- self.bold, self.flash, self.underline, self.reverse = 0, 0, 0, 0
- self.display = 1
- elif x == 1:
- self.bold = 1
- elif 30 <= x <= 37:
- self.currentFG = x - 30
- elif 40 <= x <= 47:
- self.currentBG = x - 40
- elif x == 39:
- self.currentFG = self.defaultFG
- elif x == 49:
- self.currentBG = self.defaultBG
- elif x == 4:
- self.underline = 1
- elif x == 5:
- self.flash = 1
- elif x == 7:
- self.reverse = 1
- elif x == 8:
- self.display = 0
- elif x == 22:
- self.bold = 0
- elif x == 24:
- self.underline = 0
- elif x == 25:
- self.blink = 0
- elif x == 27:
- self.reverse = 0
- elif x == 28:
- self.display = 1
- else:
- log.msg('Unrecognised ANSI color command: %d' % (x,))
-
- def parseCursor(self, cursor):
- pass
-
- def parseErase(self, erase):
- pass
-
-
- def pickColor(self, value, mode, BOLD = ColorText.BOLD_COLORS):
- if mode:
- return ColorText.COLORS[value]
- else:
- return self.bold and BOLD[value] or ColorText.COLORS[value]
-
-
- def formatText(self, text):
- return ColorText(
- text,
- self.pickColor(self.currentFG, 0),
- self.pickColor(self.currentBG, 1),
- self.display, self.bold, self.underline, self.flash, self.reverse
- )
-
-
-_sets = ''.join(map(''.join, AnsiParser.SETS))
-
-_setmap = {}
-for s in AnsiParser.SETS:
- for r in s:
- _setmap[r] = s
-del s
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/ui/tkvt100.py b/Darwin/lib/python2.7/site-packages/twisted/conch/ui/tkvt100.py
deleted file mode 100644
index cd7581d..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/ui/tkvt100.py
+++ /dev/null
@@ -1,197 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-"""Module to emulate a VT100 terminal in Tkinter.
-
-Maintainer: Paul Swartz
-"""
-
-import Tkinter, tkFont
-import ansi
-import string
-
-ttyFont = None#tkFont.Font(family = 'Courier', size = 10)
-fontWidth, fontHeight = None,None#max(map(ttyFont.measure, string.letters+string.digits)), int(ttyFont.metrics()['linespace'])
-
-colorKeys = (
- 'b', 'r', 'g', 'y', 'l', 'm', 'c', 'w',
- 'B', 'R', 'G', 'Y', 'L', 'M', 'C', 'W'
-)
-
-colorMap = {
- 'b': '#000000', 'r': '#c40000', 'g': '#00c400', 'y': '#c4c400',
- 'l': '#000080', 'm': '#c400c4', 'c': '#00c4c4', 'w': '#c4c4c4',
- 'B': '#626262', 'R': '#ff0000', 'G': '#00ff00', 'Y': '#ffff00',
- 'L': '#0000ff', 'M': '#ff00ff', 'C': '#00ffff', 'W': '#ffffff',
-}
-
-class VT100Frame(Tkinter.Frame):
- def __init__(self, *args, **kw):
- global ttyFont, fontHeight, fontWidth
- ttyFont = tkFont.Font(family = 'Courier', size = 10)
- fontWidth, fontHeight = max(map(ttyFont.measure, string.letters+string.digits)), int(ttyFont.metrics()['linespace'])
- self.width = kw.get('width', 80)
- self.height = kw.get('height', 25)
- self.callback = kw['callback']
- del kw['callback']
- kw['width'] = w = fontWidth * self.width
- kw['height'] = h = fontHeight * self.height
- Tkinter.Frame.__init__(self, *args, **kw)
- self.canvas = Tkinter.Canvas(bg='#000000', width=w, height=h)
- self.canvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)
- self.canvas.bind('', self.keyPressed)
- self.canvas.bind('<1>', lambda x: 'break')
- self.canvas.bind('', self.upPressed)
- self.canvas.bind('', self.downPressed)
- self.canvas.bind('', self.leftPressed)
- self.canvas.bind('', self.rightPressed)
- self.canvas.focus()
-
- self.ansiParser = ansi.AnsiParser(ansi.ColorText.WHITE, ansi.ColorText.BLACK)
- self.ansiParser.writeString = self.writeString
- self.ansiParser.parseCursor = self.parseCursor
- self.ansiParser.parseErase = self.parseErase
- #for (a, b) in colorMap.items():
- # self.canvas.tag_config(a, foreground=b)
- # self.canvas.tag_config('b'+a, background=b)
- #self.canvas.tag_config('underline', underline=1)
-
- self.x = 0
- self.y = 0
- self.cursor = self.canvas.create_rectangle(0,0,fontWidth-1,fontHeight-1,fill='green',outline='green')
-
- def _delete(self, sx, sy, ex, ey):
- csx = sx*fontWidth + 1
- csy = sy*fontHeight + 1
- cex = ex*fontWidth + 3
- cey = ey*fontHeight + 3
- items = self.canvas.find_overlapping(csx,csy, cex,cey)
- for item in items:
- self.canvas.delete(item)
-
- def _write(self, ch, fg, bg):
- if self.x == self.width:
- self.x = 0
- self.y+=1
- if self.y == self.height:
- [self.canvas.move(x,0,-fontHeight) for x in self.canvas.find_all()]
- self.y-=1
- canvasX = self.x*fontWidth + 1
- canvasY = self.y*fontHeight + 1
- items = self.canvas.find_overlapping(canvasX, canvasY, canvasX+2, canvasY+2)
- if items:
- [self.canvas.delete(item) for item in items]
- if bg:
- self.canvas.create_rectangle(canvasX, canvasY, canvasX+fontWidth-1, canvasY+fontHeight-1, fill=bg, outline=bg)
- self.canvas.create_text(canvasX, canvasY, anchor=Tkinter.NW, font=ttyFont, text=ch, fill=fg)
- self.x+=1
-
- def write(self, data):
- #print self.x,self.y,repr(data)
- #if len(data)>5: raw_input()
- self.ansiParser.parseString(data)
- self.canvas.delete(self.cursor)
- canvasX = self.x*fontWidth + 1
- canvasY = self.y*fontHeight + 1
- self.cursor = self.canvas.create_rectangle(canvasX,canvasY,canvasX+fontWidth-1,canvasY+fontHeight-1, fill='green', outline='green')
- self.canvas.lower(self.cursor)
-
- def writeString(self, i):
- if not i.display:
- return
- fg = colorMap[i.fg]
- bg = i.bg != 'b' and colorMap[i.bg]
- for ch in i.text:
- b = ord(ch)
- if b == 7: # bell
- self.bell()
- elif b == 8: # BS
- if self.x:
- self.x-=1
- elif b == 9: # TAB
- [self._write(' ',fg,bg) for i in range(8)]
- elif b == 10:
- if self.y == self.height-1:
- self._delete(0,0,self.width,0)
- [self.canvas.move(x,0,-fontHeight) for x in self.canvas.find_all()]
- else:
- self.y+=1
- elif b == 13:
- self.x = 0
- elif 32 <= b < 127:
- self._write(ch, fg, bg)
-
- def parseErase(self, erase):
- if ';' in erase:
- end = erase[-1]
- parts = erase[:-1].split(';')
- [self.parseErase(x+end) for x in parts]
- return
- start = 0
- x,y = self.x, self.y
- if len(erase) > 1:
- start = int(erase[:-1])
- if erase[-1] == 'J':
- if start == 0:
- self._delete(x,y,self.width,self.height)
- else:
- self._delete(0,0,self.width,self.height)
- self.x = 0
- self.y = 0
- elif erase[-1] == 'K':
- if start == 0:
- self._delete(x,y,self.width,y)
- elif start == 1:
- self._delete(0,y,x,y)
- self.x = 0
- else:
- self._delete(0,y,self.width,y)
- self.x = 0
- elif erase[-1] == 'P':
- self._delete(x,y,x+start,y)
-
- def parseCursor(self, cursor):
- #if ';' in cursor and cursor[-1]!='H':
- # end = cursor[-1]
- # parts = cursor[:-1].split(';')
- # [self.parseCursor(x+end) for x in parts]
- # return
- start = 1
- if len(cursor) > 1 and cursor[-1]!='H':
- start = int(cursor[:-1])
- if cursor[-1] == 'C':
- self.x+=start
- elif cursor[-1] == 'D':
- self.x-=start
- elif cursor[-1]=='d':
- self.y=start-1
- elif cursor[-1]=='G':
- self.x=start-1
- elif cursor[-1]=='H':
- if len(cursor)>1:
- y,x = map(int, cursor[:-1].split(';'))
- y-=1
- x-=1
- else:
- x,y=0,0
- self.x = x
- self.y = y
-
- def keyPressed(self, event):
- if self.callback and event.char:
- self.callback(event.char)
- return 'break'
-
- def upPressed(self, event):
- self.callback('\x1bOA')
-
- def downPressed(self, event):
- self.callback('\x1bOB')
-
- def rightPressed(self, event):
- self.callback('\x1bOC')
-
- def leftPressed(self, event):
- self.callback('\x1bOD')
diff --git a/Darwin/lib/python2.7/site-packages/twisted/conch/unix.py b/Darwin/lib/python2.7/site-packages/twisted/conch/unix.py
deleted file mode 100644
index 3a44be0..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/conch/unix.py
+++ /dev/null
@@ -1,457 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-from twisted.cred import portal
-from twisted.python import components, log
-from twisted.internet.error import ProcessExitedAlready
-from zope import interface
-from ssh import session, forwarding, filetransfer
-from ssh.filetransfer import FXF_READ, FXF_WRITE, FXF_APPEND, FXF_CREAT, FXF_TRUNC, FXF_EXCL
-from twisted.conch.ls import lsLine
-
-from avatar import ConchUser
-from error import ConchError
-from interfaces import ISession, ISFTPServer, ISFTPFile
-
-import struct, os, time, socket
-import fcntl, tty
-import pwd, grp
-import pty
-import ttymodes
-
-try:
- import utmp
-except ImportError:
- utmp = None
-
-class UnixSSHRealm:
- interface.implements(portal.IRealm)
-
- def requestAvatar(self, username, mind, *interfaces):
- user = UnixConchUser(username)
- return interfaces[0], user, user.logout
-
-
-class UnixConchUser(ConchUser):
-
- def __init__(self, username):
- ConchUser.__init__(self)
- self.username = username
- self.pwdData = pwd.getpwnam(self.username)
- l = [self.pwdData[3]]
- for groupname, password, gid, userlist in grp.getgrall():
- if username in userlist:
- l.append(gid)
- self.otherGroups = l
- self.listeners = {} # dict mapping (interface, port) -> listener
- self.channelLookup.update(
- {"session": session.SSHSession,
- "direct-tcpip": forwarding.openConnectForwardingClient})
-
- self.subsystemLookup.update(
- {"sftp": filetransfer.FileTransferServer})
-
- def getUserGroupId(self):
- return self.pwdData[2:4]
-
- def getOtherGroups(self):
- return self.otherGroups
-
- def getHomeDir(self):
- return self.pwdData[5]
-
- def getShell(self):
- return self.pwdData[6]
-
- def global_tcpip_forward(self, data):
- hostToBind, portToBind = forwarding.unpackGlobal_tcpip_forward(data)
- from twisted.internet import reactor
- try: listener = self._runAsUser(
- reactor.listenTCP, portToBind,
- forwarding.SSHListenForwardingFactory(self.conn,
- (hostToBind, portToBind),
- forwarding.SSHListenServerForwardingChannel),
- interface = hostToBind)
- except:
- return 0
- else:
- self.listeners[(hostToBind, portToBind)] = listener
- if portToBind == 0:
- portToBind = listener.getHost()[2] # the port
- return 1, struct.pack('>L', portToBind)
- else:
- return 1
-
- def global_cancel_tcpip_forward(self, data):
- hostToBind, portToBind = forwarding.unpackGlobal_tcpip_forward(data)
- listener = self.listeners.get((hostToBind, portToBind), None)
- if not listener:
- return 0
- del self.listeners[(hostToBind, portToBind)]
- self._runAsUser(listener.stopListening)
- return 1
-
- def logout(self):
- # remove all listeners
- for listener in self.listeners.itervalues():
- self._runAsUser(listener.stopListening)
- log.msg('avatar %s logging out (%i)' % (self.username, len(self.listeners)))
-
- def _runAsUser(self, f, *args, **kw):
- euid = os.geteuid()
- egid = os.getegid()
- groups = os.getgroups()
- uid, gid = self.getUserGroupId()
- os.setegid(0)
- os.seteuid(0)
- os.setgroups(self.getOtherGroups())
- os.setegid(gid)
- os.seteuid(uid)
- try:
- f = iter(f)
- except TypeError:
- f = [(f, args, kw)]
- try:
- for i in f:
- func = i[0]
- args = len(i)>1 and i[1] or ()
- kw = len(i)>2 and i[2] or {}
- r = func(*args, **kw)
- finally:
- os.setegid(0)
- os.seteuid(0)
- os.setgroups(groups)
- os.setegid(egid)
- os.seteuid(euid)
- return r
-
-class SSHSessionForUnixConchUser:
-
- interface.implements(ISession)
-
- def __init__(self, avatar):
- self.avatar = avatar
- self. environ = {'PATH':'/bin:/usr/bin:/usr/local/bin'}
- self.pty = None
- self.ptyTuple = 0
-
- def addUTMPEntry(self, loggedIn=1):
- if not utmp:
- return
- ipAddress = self.avatar.conn.transport.transport.getPeer().host
- packedIp ,= struct.unpack('L', socket.inet_aton(ipAddress))
- ttyName = self.ptyTuple[2][5:]
- t = time.time()
- t1 = int(t)
- t2 = int((t-t1) * 1e6)
- entry = utmp.UtmpEntry()
- entry.ut_type = loggedIn and utmp.USER_PROCESS or utmp.DEAD_PROCESS
- entry.ut_pid = self.pty.pid
- entry.ut_line = ttyName
- entry.ut_id = ttyName[-4:]
- entry.ut_tv = (t1,t2)
- if loggedIn:
- entry.ut_user = self.avatar.username
- entry.ut_host = socket.gethostbyaddr(ipAddress)[0]
- entry.ut_addr_v6 = (packedIp, 0, 0, 0)
- a = utmp.UtmpRecord(utmp.UTMP_FILE)
- a.pututline(entry)
- a.endutent()
- b = utmp.UtmpRecord(utmp.WTMP_FILE)
- b.pututline(entry)
- b.endutent()
-
-
- def getPty(self, term, windowSize, modes):
- self.environ['TERM'] = term
- self.winSize = windowSize
- self.modes = modes
- master, slave = pty.openpty()
- ttyname = os.ttyname(slave)
- self.environ['SSH_TTY'] = ttyname
- self.ptyTuple = (master, slave, ttyname)
-
- def openShell(self, proto):
- from twisted.internet import reactor
- if not self.ptyTuple: # we didn't get a pty-req
- log.msg('tried to get shell without pty, failing')
- raise ConchError("no pty")
- uid, gid = self.avatar.getUserGroupId()
- homeDir = self.avatar.getHomeDir()
- shell = self.avatar.getShell()
- self.environ['USER'] = self.avatar.username
- self.environ['HOME'] = homeDir
- self.environ['SHELL'] = shell
- shellExec = os.path.basename(shell)
- peer = self.avatar.conn.transport.transport.getPeer()
- host = self.avatar.conn.transport.transport.getHost()
- self.environ['SSH_CLIENT'] = '%s %s %s' % (peer.host, peer.port, host.port)
- self.getPtyOwnership()
- self.pty = reactor.spawnProcess(proto, \
- shell, ['-%s' % shellExec], self.environ, homeDir, uid, gid,
- usePTY = self.ptyTuple)
- self.addUTMPEntry()
- fcntl.ioctl(self.pty.fileno(), tty.TIOCSWINSZ,
- struct.pack('4H', *self.winSize))
- if self.modes:
- self.setModes()
- self.oldWrite = proto.transport.write
- proto.transport.write = self._writeHack
- self.avatar.conn.transport.transport.setTcpNoDelay(1)
-
- def execCommand(self, proto, cmd):
- from twisted.internet import reactor
- uid, gid = self.avatar.getUserGroupId()
- homeDir = self.avatar.getHomeDir()
- shell = self.avatar.getShell() or '/bin/sh'
- command = (shell, '-c', cmd)
- peer = self.avatar.conn.transport.transport.getPeer()
- host = self.avatar.conn.transport.transport.getHost()
- self.environ['SSH_CLIENT'] = '%s %s %s' % (peer.host, peer.port, host.port)
- if self.ptyTuple:
- self.getPtyOwnership()
- self.pty = reactor.spawnProcess(proto, \
- shell, command, self.environ, homeDir,
- uid, gid, usePTY = self.ptyTuple or 0)
- if self.ptyTuple:
- self.addUTMPEntry()
- if self.modes:
- self.setModes()
-# else:
-# tty.setraw(self.pty.pipes[0].fileno(), tty.TCSANOW)
- self.avatar.conn.transport.transport.setTcpNoDelay(1)
-
- def getPtyOwnership(self):
- ttyGid = os.stat(self.ptyTuple[2])[5]
- uid, gid = self.avatar.getUserGroupId()
- euid, egid = os.geteuid(), os.getegid()
- os.setegid(0)
- os.seteuid(0)
- try:
- os.chown(self.ptyTuple[2], uid, ttyGid)
- finally:
- os.setegid(egid)
- os.seteuid(euid)
-
- def setModes(self):
- pty = self.pty
- attr = tty.tcgetattr(pty.fileno())
- for mode, modeValue in self.modes:
- if not ttymodes.TTYMODES.has_key(mode): continue
- ttyMode = ttymodes.TTYMODES[mode]
- if len(ttyMode) == 2: # flag
- flag, ttyAttr = ttyMode
- if not hasattr(tty, ttyAttr): continue
- ttyval = getattr(tty, ttyAttr)
- if modeValue:
- attr[flag] = attr[flag]|ttyval
- else:
- attr[flag] = attr[flag]&~ttyval
- elif ttyMode == 'OSPEED':
- attr[tty.OSPEED] = getattr(tty, 'B%s'%modeValue)
- elif ttyMode == 'ISPEED':
- attr[tty.ISPEED] = getattr(tty, 'B%s'%modeValue)
- else:
- if not hasattr(tty, ttyMode): continue
- ttyval = getattr(tty, ttyMode)
- attr[tty.CC][ttyval] = chr(modeValue)
- tty.tcsetattr(pty.fileno(), tty.TCSANOW, attr)
-
- def eofReceived(self):
- if self.pty:
- self.pty.closeStdin()
-
- def closed(self):
- if self.ptyTuple and os.path.exists(self.ptyTuple[2]):
- ttyGID = os.stat(self.ptyTuple[2])[5]
- os.chown(self.ptyTuple[2], 0, ttyGID)
- if self.pty:
- try:
- self.pty.signalProcess('HUP')
- except (OSError,ProcessExitedAlready):
- pass
- self.pty.loseConnection()
- self.addUTMPEntry(0)
- log.msg('shell closed')
-
- def windowChanged(self, winSize):
- self.winSize = winSize
- fcntl.ioctl(self.pty.fileno(), tty.TIOCSWINSZ,
- struct.pack('4H', *self.winSize))
-
- def _writeHack(self, data):
- """
- Hack to send ignore messages when we aren't echoing.
- """
- if self.pty is not None:
- attr = tty.tcgetattr(self.pty.fileno())[3]
- if not attr & tty.ECHO and attr & tty.ICANON: # no echo
- self.avatar.conn.transport.sendIgnore('\x00'*(8+len(data)))
- self.oldWrite(data)
-
-
-class SFTPServerForUnixConchUser:
-
- interface.implements(ISFTPServer)
-
- def __init__(self, avatar):
- self.avatar = avatar
-
-
- def _setAttrs(self, path, attrs):
- """
- NOTE: this function assumes it runs as the logged-in user:
- i.e. under _runAsUser()
- """
- if "uid" in attrs and "gid" in attrs:
- os.chown(path, attrs["uid"], attrs["gid"])
- if "permissions" in attrs:
- os.chmod(path, attrs["permissions"])
- if "atime" in attrs and "mtime" in attrs:
- os.utime(path, (attrs["atime"], attrs["mtime"]))
-
- def _getAttrs(self, s):
- return {
- "size" : s.st_size,
- "uid" : s.st_uid,
- "gid" : s.st_gid,
- "permissions" : s.st_mode,
- "atime" : int(s.st_atime),
- "mtime" : int(s.st_mtime)
- }
-
- def _absPath(self, path):
- home = self.avatar.getHomeDir()
- return os.path.abspath(os.path.join(home, path))
-
- def gotVersion(self, otherVersion, extData):
- return {}
-
- def openFile(self, filename, flags, attrs):
- return UnixSFTPFile(self, self._absPath(filename), flags, attrs)
-
- def removeFile(self, filename):
- filename = self._absPath(filename)
- return self.avatar._runAsUser(os.remove, filename)
-
- def renameFile(self, oldpath, newpath):
- oldpath = self._absPath(oldpath)
- newpath = self._absPath(newpath)
- return self.avatar._runAsUser(os.rename, oldpath, newpath)
-
- def makeDirectory(self, path, attrs):
- path = self._absPath(path)
- return self.avatar._runAsUser([(os.mkdir, (path,)),
- (self._setAttrs, (path, attrs))])
-
- def removeDirectory(self, path):
- path = self._absPath(path)
- self.avatar._runAsUser(os.rmdir, path)
-
- def openDirectory(self, path):
- return UnixSFTPDirectory(self, self._absPath(path))
-
- def getAttrs(self, path, followLinks):
- path = self._absPath(path)
- if followLinks:
- s = self.avatar._runAsUser(os.stat, path)
- else:
- s = self.avatar._runAsUser(os.lstat, path)
- return self._getAttrs(s)
-
- def setAttrs(self, path, attrs):
- path = self._absPath(path)
- self.avatar._runAsUser(self._setAttrs, path, attrs)
-
- def readLink(self, path):
- path = self._absPath(path)
- return self.avatar._runAsUser(os.readlink, path)
-
- def makeLink(self, linkPath, targetPath):
- linkPath = self._absPath(linkPath)
- targetPath = self._absPath(targetPath)
- return self.avatar._runAsUser(os.symlink, targetPath, linkPath)
-
- def realPath(self, path):
- return os.path.realpath(self._absPath(path))
-
- def extendedRequest(self, extName, extData):
- raise NotImplementedError
-
-class UnixSFTPFile:
-
- interface.implements(ISFTPFile)
-
- def __init__(self, server, filename, flags, attrs):
- self.server = server
- openFlags = 0
- if flags & FXF_READ == FXF_READ and flags & FXF_WRITE == 0:
- openFlags = os.O_RDONLY
- if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == 0:
- openFlags = os.O_WRONLY
- if flags & FXF_WRITE == FXF_WRITE and flags & FXF_READ == FXF_READ:
- openFlags = os.O_RDWR
- if flags & FXF_APPEND == FXF_APPEND:
- openFlags |= os.O_APPEND
- if flags & FXF_CREAT == FXF_CREAT:
- openFlags |= os.O_CREAT
- if flags & FXF_TRUNC == FXF_TRUNC:
- openFlags |= os.O_TRUNC
- if flags & FXF_EXCL == FXF_EXCL:
- openFlags |= os.O_EXCL
- if "permissions" in attrs:
- mode = attrs["permissions"]
- del attrs["permissions"]
- else:
- mode = 0777
- fd = server.avatar._runAsUser(os.open, filename, openFlags, mode)
- if attrs:
- server.avatar._runAsUser(server._setAttrs, filename, attrs)
- self.fd = fd
-
- def close(self):
- return self.server.avatar._runAsUser(os.close, self.fd)
-
- def readChunk(self, offset, length):
- return self.server.avatar._runAsUser([ (os.lseek, (self.fd, offset, 0)),
- (os.read, (self.fd, length)) ])
-
- def writeChunk(self, offset, data):
- return self.server.avatar._runAsUser([(os.lseek, (self.fd, offset, 0)),
- (os.write, (self.fd, data))])
-
- def getAttrs(self):
- s = self.server.avatar._runAsUser(os.fstat, self.fd)
- return self.server._getAttrs(s)
-
- def setAttrs(self, attrs):
- raise NotImplementedError
-
-
-class UnixSFTPDirectory:
-
- def __init__(self, server, directory):
- self.server = server
- self.files = server.avatar._runAsUser(os.listdir, directory)
- self.dir = directory
-
- def __iter__(self):
- return self
-
- def next(self):
- try:
- f = self.files.pop(0)
- except IndexError:
- raise StopIteration
- else:
- s = self.server.avatar._runAsUser(os.lstat, os.path.join(self.dir, f))
- longname = lsLine(f, s)
- attrs = self.server._getAttrs(s)
- return (f, longname, attrs)
-
- def close(self):
- self.files = []
-
-
-components.registerAdapter(SFTPServerForUnixConchUser, UnixConchUser, filetransfer.ISFTPServer)
-components.registerAdapter(SSHSessionForUnixConchUser, UnixConchUser, session.ISession)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/copyright.py b/Darwin/lib/python2.7/site-packages/twisted/copyright.py
deleted file mode 100644
index e650c87..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/copyright.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Copyright information for Twisted.
-"""
-
-from __future__ import division, absolute_import
-
-from twisted import __version__ as version, version as longversion
-
-longversion = str(longversion)
-
-copyright="""\
-Copyright (c) 2001-2014 Twisted Matrix Laboratories.
-See LICENSE for details."""
-
-disclaimer='''
-Twisted, the Framework of Your Internet
-%s
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-''' % (copyright,)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/cred/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/cred/__init__.py
deleted file mode 100644
index 06e287f..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/cred/__init__.py
+++ /dev/null
@@ -1,13 +0,0 @@
-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Twisted Cred
-
-Support for verifying credentials, and providing services to users based on
-those credentials.
-
-(This package was previously known as the module twisted.internet.passport.)
-"""
diff --git a/Darwin/lib/python2.7/site-packages/twisted/cred/_digest.py b/Darwin/lib/python2.7/site-packages/twisted/cred/_digest.py
deleted file mode 100644
index 8257234..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/cred/_digest.py
+++ /dev/null
@@ -1,129 +0,0 @@
-# -*- test-case-name: twisted.test.test_digestauth -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Calculations for HTTP Digest authentication.
-
-@see: U{http://www.faqs.org/rfcs/rfc2617.html}
-"""
-
-from hashlib import md5, sha1
-
-
-
-# The digest math
-
-algorithms = {
- 'md5': md5,
-
- # md5-sess is more complicated than just another algorithm. It requires
- # H(A1) state to be remembered from the first WWW-Authenticate challenge
- # issued and re-used to process any Authorization header in response to
- # that WWW-Authenticate challenge. It is *not* correct to simply
- # recalculate H(A1) each time an Authorization header is received. Read
- # RFC 2617, section 3.2.2.2 and do not try to make DigestCredentialFactory
- # support this unless you completely understand it. -exarkun
- 'md5-sess': md5,
-
- 'sha': sha1,
-}
-
-# DigestCalcHA1
-def calcHA1(pszAlg, pszUserName, pszRealm, pszPassword, pszNonce, pszCNonce,
- preHA1=None):
- """
- Compute H(A1) from RFC 2617.
-
- @param pszAlg: The name of the algorithm to use to calculate the digest.
- Currently supported are md5, md5-sess, and sha.
- @param pszUserName: The username
- @param pszRealm: The realm
- @param pszPassword: The password
- @param pszNonce: The nonce
- @param pszCNonce: The cnonce
-
- @param preHA1: If available this is a str containing a previously
- calculated H(A1) as a hex string. If this is given then the values for
- pszUserName, pszRealm, and pszPassword must be C{None} and are ignored.
- """
-
- if (preHA1 and (pszUserName or pszRealm or pszPassword)):
- raise TypeError(("preHA1 is incompatible with the pszUserName, "
- "pszRealm, and pszPassword arguments"))
-
- if preHA1 is None:
- # We need to calculate the HA1 from the username:realm:password
- m = algorithms[pszAlg]()
- m.update(pszUserName)
- m.update(":")
- m.update(pszRealm)
- m.update(":")
- m.update(pszPassword)
- HA1 = m.digest()
- else:
- # We were given a username:realm:password
- HA1 = preHA1.decode('hex')
-
- if pszAlg == "md5-sess":
- m = algorithms[pszAlg]()
- m.update(HA1)
- m.update(":")
- m.update(pszNonce)
- m.update(":")
- m.update(pszCNonce)
- HA1 = m.digest()
-
- return HA1.encode('hex')
-
-
-def calcHA2(algo, pszMethod, pszDigestUri, pszQop, pszHEntity):
- """
- Compute H(A2) from RFC 2617.
-
- @param pszAlg: The name of the algorithm to use to calculate the digest.
- Currently supported are md5, md5-sess, and sha.
- @param pszMethod: The request method.
- @param pszDigestUri: The request URI.
- @param pszQop: The Quality-of-Protection value.
- @param pszHEntity: The hash of the entity body or C{None} if C{pszQop} is
- not C{'auth-int'}.
- @return: The hash of the A2 value for the calculation of the response
- digest.
- """
- m = algorithms[algo]()
- m.update(pszMethod)
- m.update(":")
- m.update(pszDigestUri)
- if pszQop == "auth-int":
- m.update(":")
- m.update(pszHEntity)
- return m.digest().encode('hex')
-
-
-def calcResponse(HA1, HA2, algo, pszNonce, pszNonceCount, pszCNonce, pszQop):
- """
- Compute the digest for the given parameters.
-
- @param HA1: The H(A1) value, as computed by L{calcHA1}.
- @param HA2: The H(A2) value, as computed by L{calcHA2}.
- @param pszNonce: The challenge nonce.
- @param pszNonceCount: The (client) nonce count value for this response.
- @param pszCNonce: The client nonce.
- @param pszQop: The Quality-of-Protection value.
- """
- m = algorithms[algo]()
- m.update(HA1)
- m.update(":")
- m.update(pszNonce)
- m.update(":")
- if pszNonceCount and pszCNonce:
- m.update(pszNonceCount)
- m.update(":")
- m.update(pszCNonce)
- m.update(":")
- m.update(pszQop)
- m.update(":")
- m.update(HA2)
- respHash = m.digest().encode('hex')
- return respHash
diff --git a/Darwin/lib/python2.7/site-packages/twisted/cred/checkers.py b/Darwin/lib/python2.7/site-packages/twisted/cred/checkers.py
deleted file mode 100644
index 523a94d..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/cred/checkers.py
+++ /dev/null
@@ -1,268 +0,0 @@
-# -*- test-case-name: twisted.test.test_newcred -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-import os
-
-from zope.interface import implements, Interface, Attribute
-
-from twisted.internet import defer
-from twisted.python import failure, log
-from twisted.cred import error, credentials
-
-
-
-class ICredentialsChecker(Interface):
- """
- An object that can check sub-interfaces of ICredentials.
- """
-
- credentialInterfaces = Attribute(
- 'A list of sub-interfaces of ICredentials which specifies which I may check.')
-
-
- def requestAvatarId(credentials):
- """
- @param credentials: something which implements one of the interfaces in
- self.credentialInterfaces.
-
- @return: a Deferred which will fire a string which identifies an
- avatar, an empty tuple to specify an authenticated anonymous user
- (provided as checkers.ANONYMOUS) or fire a Failure(UnauthorizedLogin).
- Alternatively, return the result itself.
-
- @see: L{twisted.cred.credentials}
- """
-
-
-
-# A note on anonymity - We do not want None as the value for anonymous
-# because it is too easy to accidentally return it. We do not want the
-# empty string, because it is too easy to mistype a password file. For
-# example, an .htpasswd file may contain the lines: ['hello:asdf',
-# 'world:asdf', 'goodbye', ':world']. This misconfiguration will have an
-# ill effect in any case, but accidentally granting anonymous access is a
-# worse failure mode than simply granting access to an untypeable
-# username. We do not want an instance of 'object', because that would
-# create potential problems with persistence.
-
-ANONYMOUS = ()
-
-
-class AllowAnonymousAccess:
- implements(ICredentialsChecker)
- credentialInterfaces = credentials.IAnonymous,
-
- def requestAvatarId(self, credentials):
- return defer.succeed(ANONYMOUS)
-
-
-class InMemoryUsernamePasswordDatabaseDontUse:
- """
- An extremely simple credentials checker.
-
- This is only of use in one-off test programs or examples which don't
- want to focus too much on how credentials are verified.
-
- You really don't want to use this for anything else. It is, at best, a
- toy. If you need a simple credentials checker for a real application,
- see L{FilePasswordDB}.
- """
-
- implements(ICredentialsChecker)
-
- credentialInterfaces = (credentials.IUsernamePassword,
- credentials.IUsernameHashedPassword)
-
- def __init__(self, **users):
- self.users = users
-
- def addUser(self, username, password):
- self.users[username] = password
-
- def _cbPasswordMatch(self, matched, username):
- if matched:
- return username
- else:
- return failure.Failure(error.UnauthorizedLogin())
-
- def requestAvatarId(self, credentials):
- if credentials.username in self.users:
- return defer.maybeDeferred(
- credentials.checkPassword,
- self.users[credentials.username]).addCallback(
- self._cbPasswordMatch, str(credentials.username))
- else:
- return defer.fail(error.UnauthorizedLogin())
-
-
-class FilePasswordDB:
- """A file-based, text-based username/password database.
-
- Records in the datafile for this class are delimited by a particular
- string. The username appears in a fixed field of the columns delimited
- by this string, as does the password. Both fields are specifiable. If
- the passwords are not stored plaintext, a hash function must be supplied
- to convert plaintext passwords to the form stored on disk and this
- CredentialsChecker will only be able to check IUsernamePassword
- credentials. If the passwords are stored plaintext,
- IUsernameHashedPassword credentials will be checkable as well.
- """
-
- implements(ICredentialsChecker)
-
- cache = False
- _credCache = None
- _cacheTimestamp = 0
-
- def __init__(self, filename, delim=':', usernameField=0, passwordField=1,
- caseSensitive=True, hash=None, cache=False):
- """
- @type filename: C{str}
- @param filename: The name of the file from which to read username and
- password information.
-
- @type delim: C{str}
- @param delim: The field delimiter used in the file.
-
- @type usernameField: C{int}
- @param usernameField: The index of the username after splitting a
- line on the delimiter.
-
- @type passwordField: C{int}
- @param passwordField: The index of the password after splitting a
- line on the delimiter.
-
- @type caseSensitive: C{bool}
- @param caseSensitive: If true, consider the case of the username when
- performing a lookup. Ignore it otherwise.
-
- @type hash: Three-argument callable or C{None}
- @param hash: A function used to transform the plaintext password
- received over the network to a format suitable for comparison
- against the version stored on disk. The arguments to the callable
- are the username, the network-supplied password, and the in-file
- version of the password. If the return value compares equal to the
- version stored on disk, the credentials are accepted.
-
- @type cache: C{bool}
- @param cache: If true, maintain an in-memory cache of the
- contents of the password file. On lookups, the mtime of the
- file will be checked, and the file will only be re-parsed if
- the mtime is newer than when the cache was generated.
- """
- self.filename = filename
- self.delim = delim
- self.ufield = usernameField
- self.pfield = passwordField
- self.caseSensitive = caseSensitive
- self.hash = hash
- self.cache = cache
-
- if self.hash is None:
- # The passwords are stored plaintext. We can support both
- # plaintext and hashed passwords received over the network.
- self.credentialInterfaces = (
- credentials.IUsernamePassword,
- credentials.IUsernameHashedPassword
- )
- else:
- # The passwords are hashed on disk. We can support only
- # plaintext passwords received over the network.
- self.credentialInterfaces = (
- credentials.IUsernamePassword,
- )
-
-
- def __getstate__(self):
- d = dict(vars(self))
- for k in '_credCache', '_cacheTimestamp':
- try:
- del d[k]
- except KeyError:
- pass
- return d
-
-
- def _cbPasswordMatch(self, matched, username):
- if matched:
- return username
- else:
- return failure.Failure(error.UnauthorizedLogin())
-
-
- def _loadCredentials(self):
- try:
- f = file(self.filename)
- except:
- log.err()
- raise error.UnauthorizedLogin()
- else:
- for line in f:
- line = line.rstrip()
- parts = line.split(self.delim)
-
- if self.ufield >= len(parts) or self.pfield >= len(parts):
- continue
- if self.caseSensitive:
- yield parts[self.ufield], parts[self.pfield]
- else:
- yield parts[self.ufield].lower(), parts[self.pfield]
-
-
- def getUser(self, username):
- if not self.caseSensitive:
- username = username.lower()
-
- if self.cache:
- if self._credCache is None or os.path.getmtime(self.filename) > self._cacheTimestamp:
- self._cacheTimestamp = os.path.getmtime(self.filename)
- self._credCache = dict(self._loadCredentials())
- return username, self._credCache[username]
- else:
- for u, p in self._loadCredentials():
- if u == username:
- return u, p
- raise KeyError(username)
-
-
- def requestAvatarId(self, c):
- try:
- u, p = self.getUser(c.username)
- except KeyError:
- return defer.fail(error.UnauthorizedLogin())
- else:
- up = credentials.IUsernamePassword(c, None)
- if self.hash:
- if up is not None:
- h = self.hash(up.username, up.password, p)
- if h == p:
- return defer.succeed(u)
- return defer.fail(error.UnauthorizedLogin())
- else:
- return defer.maybeDeferred(c.checkPassword, p
- ).addCallback(self._cbPasswordMatch, u)
-
-
-
-class PluggableAuthenticationModulesChecker:
- implements(ICredentialsChecker)
- credentialInterfaces = credentials.IPluggableAuthenticationModules,
- service = 'Twisted'
-
- def requestAvatarId(self, credentials):
- try:
- from twisted.cred import pamauth
- except ImportError: # PyPAM is missing
- return defer.fail(error.UnauthorizedLogin())
- else:
- d = pamauth.pamAuthenticate(self.service, credentials.username,
- credentials.pamConversion)
- d.addCallback(lambda x: credentials.username)
- return d
-
-
-
-# For backwards compatibility
-# Allow access as the old name.
-OnDiskUsernamePasswordDatabase = FilePasswordDB
diff --git a/Darwin/lib/python2.7/site-packages/twisted/cred/credentials.py b/Darwin/lib/python2.7/site-packages/twisted/cred/credentials.py
deleted file mode 100644
index 05ac2a4..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/cred/credentials.py
+++ /dev/null
@@ -1,493 +0,0 @@
-# -*- test-case-name: twisted.test.test_newcred-*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-This module defines L{ICredentials}, an interface for objects that represent
-authentication credentials to provide, and also includes a number of useful
-implementations of that interface.
-"""
-
-from zope.interface import implements, Interface
-
-import hmac, time, random, re
-from hashlib import md5
-
-from twisted.python.randbytes import secureRandom
-from twisted.cred._digest import calcResponse, calcHA1, calcHA2
-from twisted.cred import error
-
-class ICredentials(Interface):
- """
- I check credentials.
-
- Implementors _must_ specify which sub-interfaces of ICredentials
- to which it conforms, using zope.interface.implements().
- """
-
-
-
-class IUsernameDigestHash(ICredentials):
- """
- This credential is used when a CredentialChecker has access to the hash
- of the username:realm:password as in an Apache .htdigest file.
- """
- def checkHash(digestHash):
- """
- @param digestHash: The hashed username:realm:password to check against.
-
- @return: C{True} if the credentials represented by this object match
- the given hash, C{False} if they do not, or a L{Deferred} which
- will be called back with one of these values.
- """
-
-
-
-class IUsernameHashedPassword(ICredentials):
- """
- I encapsulate a username and a hashed password.
-
- This credential is used when a hashed password is received from the
- party requesting authentication. CredentialCheckers which check this
- kind of credential must store the passwords in plaintext (or as
- password-equivalent hashes) form so that they can be hashed in a manner
- appropriate for the particular credentials class.
-
- @type username: C{str}
- @ivar username: The username associated with these credentials.
- """
-
- def checkPassword(password):
- """
- Validate these credentials against the correct password.
-
- @type password: C{str}
- @param password: The correct, plaintext password against which to
- check.
-
- @rtype: C{bool} or L{Deferred}
- @return: C{True} if the credentials represented by this object match the
- given password, C{False} if they do not, or a L{Deferred} which will
- be called back with one of these values.
- """
-
-
-
-class IUsernamePassword(ICredentials):
- """
- I encapsulate a username and a plaintext password.
-
- This encapsulates the case where the password received over the network
- has been hashed with the identity function (That is, not at all). The
- CredentialsChecker may store the password in whatever format it desires,
- it need only transform the stored password in a similar way before
- performing the comparison.
-
- @type username: C{str}
- @ivar username: The username associated with these credentials.
-
- @type password: C{str}
- @ivar password: The password associated with these credentials.
- """
-
- def checkPassword(password):
- """
- Validate these credentials against the correct password.
-
- @type password: C{str}
- @param password: The correct, plaintext password against which to
- check.
-
- @rtype: C{bool} or L{Deferred}
- @return: C{True} if the credentials represented by this object match the
- given password, C{False} if they do not, or a L{Deferred} which will
- be called back with one of these values.
- """
-
-
-
-class IAnonymous(ICredentials):
- """
- I am an explicitly anonymous request for access.
- """
-
-
-
-class DigestedCredentials(object):
- """
- Yet Another Simple HTTP Digest authentication scheme.
- """
- implements(IUsernameHashedPassword, IUsernameDigestHash)
-
- def __init__(self, username, method, realm, fields):
- self.username = username
- self.method = method
- self.realm = realm
- self.fields = fields
-
-
- def checkPassword(self, password):
- """
- Verify that the credentials represented by this object agree with the
- given plaintext C{password} by hashing C{password} in the same way the
- response hash represented by this object was generated and comparing
- the results.
- """
- response = self.fields.get('response')
- uri = self.fields.get('uri')
- nonce = self.fields.get('nonce')
- cnonce = self.fields.get('cnonce')
- nc = self.fields.get('nc')
- algo = self.fields.get('algorithm', 'md5').lower()
- qop = self.fields.get('qop', 'auth')
-
- expected = calcResponse(
- calcHA1(algo, self.username, self.realm, password, nonce, cnonce),
- calcHA2(algo, self.method, uri, qop, None),
- algo, nonce, nc, cnonce, qop)
-
- return expected == response
-
-
- def checkHash(self, digestHash):
- """
- Verify that the credentials represented by this object agree with the
- credentials represented by the I{H(A1)} given in C{digestHash}.
-
- @param digestHash: A precomputed H(A1) value based on the username,
- realm, and password associate with this credentials object.
- """
- response = self.fields.get('response')
- uri = self.fields.get('uri')
- nonce = self.fields.get('nonce')
- cnonce = self.fields.get('cnonce')
- nc = self.fields.get('nc')
- algo = self.fields.get('algorithm', 'md5').lower()
- qop = self.fields.get('qop', 'auth')
-
- expected = calcResponse(
- calcHA1(algo, None, None, None, nonce, cnonce, preHA1=digestHash),
- calcHA2(algo, self.method, uri, qop, None),
- algo, nonce, nc, cnonce, qop)
-
- return expected == response
-
-
-
-class DigestCredentialFactory(object):
- """
- Support for RFC2617 HTTP Digest Authentication
-
- @cvar CHALLENGE_LIFETIME_SECS: The number of seconds for which an
- opaque should be valid.
-
- @type privateKey: C{str}
- @ivar privateKey: A random string used for generating the secure opaque.
-
- @type algorithm: C{str}
- @param algorithm: Case insensitive string specifying the hash algorithm to
- use. Must be either C{'md5'} or C{'sha'}. C{'md5-sess'} is B{not}
- supported.
-
- @type authenticationRealm: C{str}
- @param authenticationRealm: case sensitive string that specifies the realm
- portion of the challenge
- """
-
- _parseparts = re.compile(
- b'([^= ]+)' # The key
- b'=' # Conventional key/value separator (literal)
- b'(?:' # Group together a couple options
- b'"([^"]*)"' # A quoted string of length 0 or more
- b'|' # The other option in the group is coming
- b'([^,]+)' # An unquoted string of length 1 or more, up to a comma
- b')' # That non-matching group ends
- b',?') # There might be a comma at the end (none on last pair)
-
- CHALLENGE_LIFETIME_SECS = 15 * 60 # 15 minutes
-
- scheme = "digest"
-
- def __init__(self, algorithm, authenticationRealm):
- self.algorithm = algorithm
- self.authenticationRealm = authenticationRealm
- self.privateKey = secureRandom(12)
-
-
- def getChallenge(self, address):
- """
- Generate the challenge for use in the WWW-Authenticate header.
-
- @param address: The client address to which this challenge is being
- sent.
-
- @return: The C{dict} that can be used to generate a WWW-Authenticate
- header.
- """
- c = self._generateNonce()
- o = self._generateOpaque(c, address)
-
- return {'nonce': c,
- 'opaque': o,
- 'qop': 'auth',
- 'algorithm': self.algorithm,
- 'realm': self.authenticationRealm}
-
-
- def _generateNonce(self):
- """
- Create a random value suitable for use as the nonce parameter of a
- WWW-Authenticate challenge.
-
- @rtype: C{str}
- """
- return secureRandom(12).encode('hex')
-
-
- def _getTime(self):
- """
- Parameterize the time based seed used in C{_generateOpaque}
- so we can deterministically unittest it's behavior.
- """
- return time.time()
-
-
- def _generateOpaque(self, nonce, clientip):
- """
- Generate an opaque to be returned to the client. This is a unique
- string that can be returned to us and verified.
- """
- # Now, what we do is encode the nonce, client ip and a timestamp in the
- # opaque value with a suitable digest.
- now = str(int(self._getTime()))
- if clientip is None:
- clientip = ''
- key = "%s,%s,%s" % (nonce, clientip, now)
- digest = md5(key + self.privateKey).hexdigest()
- ekey = key.encode('base64')
- return "%s-%s" % (digest, ekey.replace('\n', ''))
-
-
- def _verifyOpaque(self, opaque, nonce, clientip):
- """
- Given the opaque and nonce from the request, as well as the client IP
- that made the request, verify that the opaque was generated by us.
- And that it's not too old.
-
- @param opaque: The opaque value from the Digest response
- @param nonce: The nonce value from the Digest response
- @param clientip: The remote IP address of the client making the request
- or C{None} if the request was submitted over a channel where this
- does not make sense.
-
- @return: C{True} if the opaque was successfully verified.
-
- @raise error.LoginFailed: if C{opaque} could not be parsed or
- contained the wrong values.
- """
- # First split the digest from the key
- opaqueParts = opaque.split('-')
- if len(opaqueParts) != 2:
- raise error.LoginFailed('Invalid response, invalid opaque value')
-
- if clientip is None:
- clientip = ''
-
- # Verify the key
- key = opaqueParts[1].decode('base64')
- keyParts = key.split(',')
-
- if len(keyParts) != 3:
- raise error.LoginFailed('Invalid response, invalid opaque value')
-
- if keyParts[0] != nonce:
- raise error.LoginFailed(
- 'Invalid response, incompatible opaque/nonce values')
-
- if keyParts[1] != clientip:
- raise error.LoginFailed(
- 'Invalid response, incompatible opaque/client values')
-
- try:
- when = int(keyParts[2])
- except ValueError:
- raise error.LoginFailed(
- 'Invalid response, invalid opaque/time values')
-
- if (int(self._getTime()) - when >
- DigestCredentialFactory.CHALLENGE_LIFETIME_SECS):
-
- raise error.LoginFailed(
- 'Invalid response, incompatible opaque/nonce too old')
-
- # Verify the digest
- digest = md5(key + self.privateKey).hexdigest()
- if digest != opaqueParts[0]:
- raise error.LoginFailed('Invalid response, invalid opaque value')
-
- return True
-
-
- def decode(self, response, method, host):
- """
- Decode the given response and attempt to generate a
- L{DigestedCredentials} from it.
-
- @type response: C{str}
- @param response: A string of comma seperated key=value pairs
-
- @type method: C{str}
- @param method: The action requested to which this response is addressed
- (GET, POST, INVITE, OPTIONS, etc).
-
- @type host: C{str}
- @param host: The address the request was sent from.
-
- @raise error.LoginFailed: If the response does not contain a username,
- a nonce, an opaque, or if the opaque is invalid.
-
- @return: L{DigestedCredentials}
- """
- response = ' '.join(response.splitlines())
- parts = self._parseparts.findall(response)
- auth = {}
- for (key, bare, quoted) in parts:
- value = (quoted or bare).strip()
- auth[key.strip()] = value
-
- username = auth.get('username')
- if not username:
- raise error.LoginFailed('Invalid response, no username given.')
-
- if 'opaque' not in auth:
- raise error.LoginFailed('Invalid response, no opaque given.')
-
- if 'nonce' not in auth:
- raise error.LoginFailed('Invalid response, no nonce given.')
-
- # Now verify the nonce/opaque values for this client
- if self._verifyOpaque(auth.get('opaque'), auth.get('nonce'), host):
- return DigestedCredentials(username,
- method,
- self.authenticationRealm,
- auth)
-
-
-
-class CramMD5Credentials:
- implements(IUsernameHashedPassword)
-
- challenge = ''
- response = ''
-
- def __init__(self, host=None):
- self.host = host
-
- def getChallenge(self):
- if self.challenge:
- return self.challenge
- # The data encoded in the first ready response contains an
- # presumptively arbitrary string of random digits, a timestamp, and
- # the fully-qualified primary host name of the server. The syntax of
- # the unencoded form must correspond to that of an RFC 822 'msg-id'
- # [RFC822] as described in [POP3].
- # -- RFC 2195
- r = random.randrange(0x7fffffff)
- t = time.time()
- self.challenge = '<%d.%d@%s>' % (r, t, self.host)
- return self.challenge
-
- def setResponse(self, response):
- self.username, self.response = response.split(None, 1)
-
- def moreChallenges(self):
- return False
-
- def checkPassword(self, password):
- verify = hmac.HMAC(password, self.challenge).hexdigest()
- return verify == self.response
-
-
-class UsernameHashedPassword:
- implements(IUsernameHashedPassword)
-
- def __init__(self, username, hashed):
- self.username = username
- self.hashed = hashed
-
- def checkPassword(self, password):
- return self.hashed == password
-
-
-class UsernamePassword:
- implements(IUsernamePassword)
-
- def __init__(self, username, password):
- self.username = username
- self.password = password
-
- def checkPassword(self, password):
- return self.password == password
-
-
-class Anonymous:
- implements(IAnonymous)
-
-
-
-class ISSHPrivateKey(ICredentials):
- """
- L{ISSHPrivateKey} credentials encapsulate an SSH public key to be checked
- against a user's private key.
-
- @ivar username: The username associated with these credentials.
- @type username: C{str}
-
- @ivar algName: The algorithm name for the blob.
- @type algName: C{str}
-
- @ivar blob: The public key blob as sent by the client.
- @type blob: C{str}
-
- @ivar sigData: The data the signature was made from.
- @type sigData: C{str}
-
- @ivar signature: The signed data. This is checked to verify that the user
- owns the private key.
- @type signature: C{str} or C{NoneType}
- """
-
-
-
-class SSHPrivateKey:
- implements(ISSHPrivateKey)
- def __init__(self, username, algName, blob, sigData, signature):
- self.username = username
- self.algName = algName
- self.blob = blob
- self.sigData = sigData
- self.signature = signature
-
-
-class IPluggableAuthenticationModules(ICredentials):
- """I encapsulate the authentication of a user via PAM (Pluggable
- Authentication Modules. I use PyPAM (available from
- http://www.tummy.com/Software/PyPam/index.html).
-
- @ivar username: The username for the user being logged in.
-
- @ivar pamConversion: A function that is called with a list of tuples
- (message, messageType). See the PAM documentation
- for the meaning of messageType. The function
- returns a Deferred which will fire with a list
- of (response, 0), one for each message. The 0 is
- currently unused, but is required by the PAM library.
- """
-
-class PluggableAuthenticationModules:
- implements(IPluggableAuthenticationModules)
-
- def __init__(self, username, pamConversion):
- self.username = username
- self.pamConversion = pamConversion
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/cred/error.py b/Darwin/lib/python2.7/site-packages/twisted/cred/error.py
deleted file mode 100644
index cce682b..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/cred/error.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""Cred errors."""
-
-class Unauthorized(Exception):
- """Standard unauthorized error."""
-
-
-
-class LoginFailed(Exception):
- """
- The user's request to log in failed for some reason.
- """
-
-
-
-class UnauthorizedLogin(LoginFailed, Unauthorized):
- """The user was not authorized to log in.
- """
-
-
-
-class UnhandledCredentials(LoginFailed):
- """A type of credentials were passed in with no knowledge of how to check
- them. This is a server configuration error - it means that a protocol was
- connected to a Portal without a CredentialChecker that can check all of its
- potential authentication strategies.
- """
-
-
-
-class LoginDenied(LoginFailed):
- """
- The realm rejected this login for some reason.
-
- Examples of reasons this might be raised include an avatar logging in
- too frequently, a quota having been fully used, or the overall server
- load being too high.
- """
diff --git a/Darwin/lib/python2.7/site-packages/twisted/cred/pamauth.py b/Darwin/lib/python2.7/site-packages/twisted/cred/pamauth.py
deleted file mode 100644
index 12357df..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/cred/pamauth.py
+++ /dev/null
@@ -1,79 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Support for asynchronously authenticating using PAM.
-"""
-
-
-import PAM
-
-import getpass, threading, os
-
-from twisted.internet import threads, defer
-
-def pamAuthenticateThread(service, user, conv):
- def _conv(items):
- from twisted.internet import reactor
- try:
- d = conv(items)
- except:
- import traceback
- traceback.print_exc()
- return
- ev = threading.Event()
- def cb(r):
- ev.r = (1, r)
- ev.set()
- def eb(e):
- ev.r = (0, e)
- ev.set()
- reactor.callFromThread(d.addCallbacks, cb, eb)
- ev.wait()
- done = ev.r
- if done[0]:
- return done[1]
- else:
- raise done[1].type, done[1].value
-
- return callIntoPAM(service, user, _conv)
-
-def callIntoPAM(service, user, conv):
- """A testing hook.
- """
- pam = PAM.pam()
- pam.start(service)
- pam.set_item(PAM.PAM_USER, user)
- pam.set_item(PAM.PAM_CONV, conv)
- gid = os.getegid()
- uid = os.geteuid()
- os.setegid(0)
- os.seteuid(0)
- try:
- pam.authenticate() # these will raise
- pam.acct_mgmt()
- return 1
- finally:
- os.setegid(gid)
- os.seteuid(uid)
-
-def defConv(items):
- resp = []
- for i in range(len(items)):
- message, kind = items[i]
- if kind == 1: # password
- p = getpass.getpass(message)
- resp.append((p, 0))
- elif kind == 2: # text
- p = raw_input(message)
- resp.append((p, 0))
- elif kind in (3,4):
- print message
- resp.append(("", 0))
- else:
- return defer.fail('foo')
- d = defer.succeed(resp)
- return d
-
-def pamAuthenticate(service, user, conv):
- return threads.deferToThread(pamAuthenticateThread, service, user, conv)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/cred/portal.py b/Darwin/lib/python2.7/site-packages/twisted/cred/portal.py
deleted file mode 100644
index bbb0af8..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/cred/portal.py
+++ /dev/null
@@ -1,121 +0,0 @@
-# -*- test-case-name: twisted.test.test_newcred -*-
-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-The point of integration of application and authentication.
-"""
-
-
-from twisted.internet import defer
-from twisted.internet.defer import maybeDeferred
-from twisted.python import failure, reflect
-from twisted.cred import error
-from zope.interface import providedBy, Interface
-
-
-class IRealm(Interface):
- """
- The realm connects application-specific objects to the
- authentication system.
- """
- def requestAvatar(avatarId, mind, *interfaces):
- """
- Return avatar which provides one of the given interfaces.
-
- @param avatarId: a string that identifies an avatar, as returned by
- L{ICredentialsChecker.requestAvatarId}
- (via a Deferred). Alternatively, it may be
- C{twisted.cred.checkers.ANONYMOUS}.
- @param mind: usually None. See the description of mind in
- L{Portal.login}.
- @param interfaces: the interface(s) the returned avatar should
- implement, e.g. C{IMailAccount}. See the description of
- L{Portal.login}.
-
- @returns: a deferred which will fire a tuple of (interface,
- avatarAspect, logout), or the tuple itself. The interface will be
- one of the interfaces passed in the 'interfaces' argument. The
- 'avatarAspect' will implement that interface. The 'logout' object
- is a callable which will detach the mind from the avatar.
- """
-
-
-class Portal:
- """
- A mediator between clients and a realm.
-
- A portal is associated with one Realm and zero or more credentials checkers.
- When a login is attempted, the portal finds the appropriate credentials
- checker for the credentials given, invokes it, and if the credentials are
- valid, retrieves the appropriate avatar from the Realm.
-
- This class is not intended to be subclassed. Customization should be done
- in the realm object and in the credentials checker objects.
- """
- def __init__(self, realm, checkers=()):
- """
- Create a Portal to a L{IRealm}.
- """
- self.realm = realm
- self.checkers = {}
- for checker in checkers:
- self.registerChecker(checker)
-
- def listCredentialsInterfaces(self):
- """
- Return list of credentials interfaces that can be used to login.
- """
- return self.checkers.keys()
-
- def registerChecker(self, checker, *credentialInterfaces):
- if not credentialInterfaces:
- credentialInterfaces = checker.credentialInterfaces
- for credentialInterface in credentialInterfaces:
- self.checkers[credentialInterface] = checker
-
- def login(self, credentials, mind, *interfaces):
- """
- @param credentials: an implementor of
- L{twisted.cred.credentials.ICredentials}
-
- @param mind: an object which implements a client-side interface for
- your particular realm. In many cases, this may be None, so if the
- word 'mind' confuses you, just ignore it.
-
- @param interfaces: list of interfaces for the perspective that the mind
- wishes to attach to. Usually, this will be only one interface, for
- example IMailAccount. For highly dynamic protocols, however, this
- may be a list like (IMailAccount, IUserChooser, IServiceInfo). To
- expand: if we are speaking to the system over IMAP, any information
- that will be relayed to the user MUST be returned as an
- IMailAccount implementor; IMAP clients would not be able to
- understand anything else. Any information about unusual status
- would have to be relayed as a single mail message in an
- otherwise-empty mailbox. However, in a web-based mail system, or a
- PB-based client, the ``mind'' object inside the web server
- (implemented with a dynamic page-viewing mechanism such as a
- Twisted Web Resource) or on the user's client program may be
- intelligent enough to respond to several ``server''-side
- interfaces.
-
- @return: A deferred which will fire a tuple of (interface,
- avatarAspect, logout). The interface will be one of the interfaces
- passed in the 'interfaces' argument. The 'avatarAspect' will
- implement that interface. The 'logout' object is a callable which
- will detach the mind from the avatar. It must be called when the
- user has conceptually disconnected from the service. Although in
- some cases this will not be in connectionLost (such as in a
- web-based session), it will always be at the end of a user's
- interactive session.
- """
- for i in self.checkers:
- if i.providedBy(credentials):
- return maybeDeferred(self.checkers[i].requestAvatarId, credentials
- ).addCallback(self.realm.requestAvatar, mind, *interfaces
- )
- ifac = providedBy(credentials)
- return defer.fail(failure.Failure(error.UnhandledCredentials(
- "No checker for %s" % ', '.join(map(reflect.qual, ifac)))))
-
diff --git a/Darwin/lib/python2.7/site-packages/twisted/cred/strcred.py b/Darwin/lib/python2.7/site-packages/twisted/cred/strcred.py
deleted file mode 100644
index 5f99a16..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/cred/strcred.py
+++ /dev/null
@@ -1,270 +0,0 @@
-# -*- test-case-name: twisted.test.test_strcred -*-
-#
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-#
-
-"""
-Support for resolving command-line strings that represent different
-checkers available to cred.
-
-Examples:
- - passwd:/etc/passwd
- - memory:admin:asdf:user:lkj
- - unix
-"""
-
-import sys
-
-from zope.interface import Interface, Attribute
-
-from twisted.plugin import getPlugins
-from twisted.python import usage
-
-
-
-class ICheckerFactory(Interface):
- """
- A factory for objects which provide
- L{twisted.cred.checkers.ICredentialsChecker}.
-
- It's implemented by twistd plugins creating checkers.
- """
-
- authType = Attribute(
- 'A tag that identifies the authentication method.')
-
-
- authHelp = Attribute(
- 'A detailed (potentially multi-line) description of precisely '
- 'what functionality this CheckerFactory provides.')
-
-
- argStringFormat = Attribute(
- 'A short (one-line) description of the argument string format.')
-
-
- credentialInterfaces = Attribute(
- 'A list of credentials interfaces that this factory will support.')
-
-
- def generateChecker(argstring):
- """
- Return an L{ICredentialChecker} provider using the supplied
- argument string.
- """
-
-
-
-class StrcredException(Exception):
- """
- Base exception class for strcred.
- """
-
-
-
-class InvalidAuthType(StrcredException):
- """
- Raised when a user provides an invalid identifier for the
- authentication plugin (known as the authType).
- """
-
-
-
-class InvalidAuthArgumentString(StrcredException):
- """
- Raised by an authentication plugin when the argument string
- provided is formatted incorrectly.
- """
-
-
-
-class UnsupportedInterfaces(StrcredException):
- """
- Raised when an application is given a checker to use that does not
- provide any of the application's supported credentials interfaces.
- """
-
-
-
-# This will be used to warn the users whenever they view help for an
-# authType that is not supported by the application.
-notSupportedWarning = ("WARNING: This authType is not supported by "
- "this application.")
-
-
-
-def findCheckerFactories():
- """
- Find all objects that implement L{ICheckerFactory}.
- """
- return getPlugins(ICheckerFactory)
-
-
-
-def findCheckerFactory(authType):
- """
- Find the first checker factory that supports the given authType.
- """
- for factory in findCheckerFactories():
- if factory.authType == authType:
- return factory
- raise InvalidAuthType(authType)
-
-
-
-def makeChecker(description):
- """
- Returns an L{twisted.cred.checkers.ICredentialsChecker} based on the
- contents of a descriptive string. Similar to
- L{twisted.application.strports}.
- """
- if ':' in description:
- authType, argstring = description.split(':', 1)
- else:
- authType = description
- argstring = ''
- return findCheckerFactory(authType).generateChecker(argstring)
-
-
-
-class AuthOptionMixin:
- """
- Defines helper methods that can be added on to any
- L{usage.Options} subclass that needs authentication.
-
- This mixin implements three new options methods:
-
- The opt_auth method (--auth) will write two new values to the
- 'self' dictionary: C{credInterfaces} (a dict of lists) and
- C{credCheckers} (a list).
-
- The opt_help_auth method (--help-auth) will search for all
- available checker plugins and list them for the user; it will exit
- when finished.
-
- The opt_help_auth_type method (--help-auth-type) will display
- detailed help for a particular checker plugin.
-
- @cvar supportedInterfaces: An iterable object that returns
- credential interfaces which this application is able to support.
-
- @cvar authOutput: A writeable object to which this options class
- will send all help-related output. Default: L{sys.stdout}
- """
-
- supportedInterfaces = None
- authOutput = sys.stdout
-
-
- def supportsInterface(self, interface):
- """
- Returns whether a particular credentials interface is supported.
- """
- return (self.supportedInterfaces is None
- or interface in self.supportedInterfaces)
-
-
- def supportsCheckerFactory(self, factory):
- """
- Returns whether a checker factory will provide at least one of
- the credentials interfaces that we care about.
- """
- for interface in factory.credentialInterfaces:
- if self.supportsInterface(interface):
- return True
- return False
-
-
- def addChecker(self, checker):
- """
- Supply a supplied credentials checker to the Options class.
- """
- # First figure out which interfaces we're willing to support.
- supported = []
- if self.supportedInterfaces is None:
- supported = checker.credentialInterfaces
- else:
- for interface in checker.credentialInterfaces:
- if self.supportsInterface(interface):
- supported.append(interface)
- if not supported:
- raise UnsupportedInterfaces(checker.credentialInterfaces)
- # If we get this far, then we know we can use this checker.
- if 'credInterfaces' not in self:
- self['credInterfaces'] = {}
- if 'credCheckers' not in self:
- self['credCheckers'] = []
- self['credCheckers'].append(checker)
- for interface in supported:
- self['credInterfaces'].setdefault(interface, []).append(checker)
-
-
- def opt_auth(self, description):
- """
- Specify an authentication method for the server.
- """
- try:
- self.addChecker(makeChecker(description))
- except UnsupportedInterfaces, e:
- raise usage.UsageError(
- 'Auth plugin not supported: %s' % e.args[0])
- except InvalidAuthType, e:
- raise usage.UsageError(
- 'Auth plugin not recognized: %s' % e.args[0])
- except Exception, e:
- raise usage.UsageError('Unexpected error: %s' % e)
-
-
- def _checkerFactoriesForOptHelpAuth(self):
- """
- Return a list of which authTypes will be displayed by --help-auth.
- This makes it a lot easier to test this module.
- """
- for factory in findCheckerFactories():
- for interface in factory.credentialInterfaces:
- if self.supportsInterface(interface):
- yield factory
- break
-
-
- def opt_help_auth(self):
- """
- Show all authentication methods available.
- """
- self.authOutput.write("Usage: --auth AuthType[:ArgString]\n")
- self.authOutput.write("For detailed help: --help-auth-type AuthType\n")
- self.authOutput.write('\n')
- # Figure out the right width for our columns
- firstLength = 0
- for factory in self._checkerFactoriesForOptHelpAuth():
- if len(factory.authType) > firstLength:
- firstLength = len(factory.authType)
- formatString = ' %%-%is\t%%s\n' % firstLength
- self.authOutput.write(formatString % ('AuthType', 'ArgString format'))
- self.authOutput.write(formatString % ('========', '================'))
- for factory in self._checkerFactoriesForOptHelpAuth():
- self.authOutput.write(
- formatString % (factory.authType, factory.argStringFormat))
- self.authOutput.write('\n')
- raise SystemExit(0)
-
-
- def opt_help_auth_type(self, authType):
- """
- Show help for a particular authentication type.
- """
- try:
- cf = findCheckerFactory(authType)
- except InvalidAuthType:
- raise usage.UsageError("Invalid auth type: %s" % authType)
- self.authOutput.write("Usage: --auth %s[:ArgString]\n" % authType)
- self.authOutput.write("ArgString format: %s\n" % cf.argStringFormat)
- self.authOutput.write('\n')
- for line in cf.authHelp.strip().splitlines():
- self.authOutput.write(' %s\n' % line.rstrip())
- self.authOutput.write('\n')
- if not self.supportsCheckerFactory(cf):
- self.authOutput.write(' %s\n' % notSupportedWarning)
- self.authOutput.write('\n')
- raise SystemExit(0)
diff --git a/Darwin/lib/python2.7/site-packages/twisted/enterprise/__init__.py b/Darwin/lib/python2.7/site-packages/twisted/enterprise/__init__.py
deleted file mode 100644
index 06c6a61..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/enterprise/__init__.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-Twisted Enterprise: database support for Twisted services.
-"""
-
-__all__ = ['adbapi']
diff --git a/Darwin/lib/python2.7/site-packages/twisted/enterprise/adbapi.py b/Darwin/lib/python2.7/site-packages/twisted/enterprise/adbapi.py
deleted file mode 100644
index 0531d2d..0000000
--- a/Darwin/lib/python2.7/site-packages/twisted/enterprise/adbapi.py
+++ /dev/null
@@ -1,483 +0,0 @@
-# -*- test-case-name: twisted.test.test_adbapi -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-An asynchronous mapping to U{DB-API 2.0