Преглед изворни кода

HUE-1281 [core] Remove unused ext-py depdencies

Removed:
- zope.interface - being used in 'avro' package as an extra dependency.
- beaker - being used as an extra dependency in 'mako'.
- twisted - was being used in 'avro' package as an extra dependency.
- processing - was not being used
Abraham Elmahrek пре 12 година
родитељ
комит
bf3befffe0
100 измењених фајлова са 0 додато и 9929 уклоњено
  1. 0 10
      desktop/core/ext-py/Beaker/.hgignore
  2. 0 26
      desktop/core/ext-py/Beaker/.hgtags
  3. 0 381
      desktop/core/ext-py/Beaker/CHANGELOG
  4. 0 27
      desktop/core/ext-py/Beaker/LICENSE
  5. 0 69
      desktop/core/ext-py/Beaker/PKG-INFO
  6. 0 1
      desktop/core/ext-py/Beaker/beaker/__init__.py
  7. 0 385
      desktop/core/ext-py/Beaker/beaker/cache.py
  8. 0 600
      desktop/core/ext-py/Beaker/beaker/container.py
  9. 0 26
      desktop/core/ext-py/Beaker/beaker/converters.py
  10. 0 35
      desktop/core/ext-py/Beaker/beaker/crypto/__init__.py
  11. 0 28
      desktop/core/ext-py/Beaker/beaker/crypto/jcecrypto.py
  12. 0 358
      desktop/core/ext-py/Beaker/beaker/crypto/pbkdf2.py
  13. 0 12
      desktop/core/ext-py/Beaker/beaker/crypto/pycrypto.py
  14. 0 27
      desktop/core/ext-py/Beaker/beaker/exceptions.py
  15. 0 0
      desktop/core/ext-py/Beaker/beaker/ext/__init__.py
  16. 0 167
      desktop/core/ext-py/Beaker/beaker/ext/database.py
  17. 0 115
      desktop/core/ext-py/Beaker/beaker/ext/google.py
  18. 0 69
      desktop/core/ext-py/Beaker/beaker/ext/memcached.py
  19. 0 124
      desktop/core/ext-py/Beaker/beaker/ext/sqla.py
  20. 0 165
      desktop/core/ext-py/Beaker/beaker/middleware.py
  21. 0 618
      desktop/core/ext-py/Beaker/beaker/session.py
  22. 0 381
      desktop/core/ext-py/Beaker/beaker/synchronization.py
  23. 0 364
      desktop/core/ext-py/Beaker/beaker/util.py
  24. 0 11
      desktop/core/ext-py/Beaker/setup.cfg
  25. 0 107
      desktop/core/ext-py/Beaker/setup.py
  26. 0 251
      desktop/core/ext-py/Beaker/tests/test_cache.py
  27. 0 180
      desktop/core/ext-py/Beaker/tests/test_container.py
  28. 0 120
      desktop/core/ext-py/Beaker/tests/test_cookie_only.py
  29. 0 99
      desktop/core/ext-py/Beaker/tests/test_database.py
  30. 0 174
      desktop/core/ext-py/Beaker/tests/test_increment.py
  31. 0 220
      desktop/core/ext-py/Beaker/tests/test_memcached.py
  32. 0 149
      desktop/core/ext-py/Beaker/tests/test_syncdict.py
  33. 0 23
      desktop/core/ext-py/Beaker/tests/test_synchronizer.py
  34. 0 32
      desktop/core/ext-py/Twisted/INSTALL
  35. 0 52
      desktop/core/ext-py/Twisted/LICENSE
  36. 0 766
      desktop/core/ext-py/Twisted/NEWS
  37. 0 116
      desktop/core/ext-py/Twisted/README
  38. 0 21
      desktop/core/ext-py/Twisted/bin/conch/cftp
  39. 0 21
      desktop/core/ext-py/Twisted/bin/conch/ckeygen
  40. 0 21
      desktop/core/ext-py/Twisted/bin/conch/conch
  41. 0 21
      desktop/core/ext-py/Twisted/bin/conch/tkconch
  42. 0 22
      desktop/core/ext-py/Twisted/bin/lore/lore
  43. 0 24
      desktop/core/ext-py/Twisted/bin/mail/mailmail
  44. 0 21
      desktop/core/ext-py/Twisted/bin/manhole
  45. 0 20
      desktop/core/ext-py/Twisted/bin/mktap
  46. 0 17
      desktop/core/ext-py/Twisted/bin/pyhtmlizer
  47. 0 19
      desktop/core/ext-py/Twisted/bin/tap2deb
  48. 0 17
      desktop/core/ext-py/Twisted/bin/tap2rpm
  49. 0 19
      desktop/core/ext-py/Twisted/bin/tapconvert
  50. 0 24
      desktop/core/ext-py/Twisted/bin/trial
  51. 0 21
      desktop/core/ext-py/Twisted/bin/twistd
  52. 0 22
      desktop/core/ext-py/Twisted/bin/words/im
  53. 0 15
      desktop/core/ext-py/Twisted/doc/conch/benchmarks/README
  54. 0 182
      desktop/core/ext-py/Twisted/doc/conch/benchmarks/buffering_mixin.py
  55. 0 25
      desktop/core/ext-py/Twisted/doc/conch/examples/demo.tac
  56. 0 80
      desktop/core/ext-py/Twisted/doc/conch/examples/demo_draw.tac
  57. 0 252
      desktop/core/ext-py/Twisted/doc/conch/examples/demo_insults.tac
  58. 0 56
      desktop/core/ext-py/Twisted/doc/conch/examples/demo_manhole.tac
  59. 0 77
      desktop/core/ext-py/Twisted/doc/conch/examples/demo_recvline.tac
  60. 0 100
      desktop/core/ext-py/Twisted/doc/conch/examples/demo_scroll.tac
  61. 0 2
      desktop/core/ext-py/Twisted/doc/conch/examples/index.html
  62. 0 107
      desktop/core/ext-py/Twisted/doc/conch/examples/sshsimpleclient.py
  63. 0 112
      desktop/core/ext-py/Twisted/doc/conch/examples/sshsimpleserver.py
  64. 0 190
      desktop/core/ext-py/Twisted/doc/conch/examples/window.tac
  65. 0 172
      desktop/core/ext-py/Twisted/doc/conch/howto/conch_client.html
  66. 0 3
      desktop/core/ext-py/Twisted/doc/conch/howto/index.html
  67. 0 4
      desktop/core/ext-py/Twisted/doc/conch/index.html
  68. 0 37
      desktop/core/ext-py/Twisted/doc/conch/man/cftp-man.html
  69. 0 89
      desktop/core/ext-py/Twisted/doc/conch/man/cftp.1
  70. 0 22
      desktop/core/ext-py/Twisted/doc/conch/man/ckeygen-man.html
  71. 0 58
      desktop/core/ext-py/Twisted/doc/conch/man/ckeygen.1
  72. 0 81
      desktop/core/ext-py/Twisted/doc/conch/man/conch-man.html
  73. 0 206
      desktop/core/ext-py/Twisted/doc/conch/man/conch.1
  74. 0 27
      desktop/core/ext-py/Twisted/doc/conch/man/tkconch-man.html
  75. 0 72
      desktop/core/ext-py/Twisted/doc/conch/man/tkconch.1
  76. 0 66
      desktop/core/ext-py/Twisted/doc/core/benchmarks/failure.py
  77. 0 47
      desktop/core/ext-py/Twisted/doc/core/benchmarks/linereceiver.py
  78. 0 26
      desktop/core/ext-py/Twisted/doc/core/benchmarks/task.py
  79. 0 19
      desktop/core/ext-py/Twisted/doc/core/benchmarks/timer.py
  80. 0 60
      desktop/core/ext-py/Twisted/doc/core/benchmarks/tpclient.py
  81. 0 22
      desktop/core/ext-py/Twisted/doc/core/benchmarks/tpclient_nt.py
  82. 0 19
      desktop/core/ext-py/Twisted/doc/core/benchmarks/tpserver.py
  83. 0 22
      desktop/core/ext-py/Twisted/doc/core/benchmarks/tpserver_nt.py
  84. 0 26
      desktop/core/ext-py/Twisted/doc/core/examples/ampclient.py
  85. 0 40
      desktop/core/ext-py/Twisted/doc/core/examples/ampserver.py
  86. 0 79
      desktop/core/ext-py/Twisted/doc/core/examples/bananabench.py
  87. 0 37
      desktop/core/ext-py/Twisted/doc/core/examples/chatserver.py
  88. 0 105
      desktop/core/ext-py/Twisted/doc/core/examples/courier.py
  89. 0 163
      desktop/core/ext-py/Twisted/doc/core/examples/cred.py
  90. 0 178
      desktop/core/ext-py/Twisted/doc/core/examples/dbcred.py
  91. 0 40
      desktop/core/ext-py/Twisted/doc/core/examples/echoclient.py
  92. 0 46
      desktop/core/ext-py/Twisted/doc/core/examples/echoclient_ssl.py
  93. 0 37
      desktop/core/ext-py/Twisted/doc/core/examples/echoclient_udp.py
  94. 0 26
      desktop/core/ext-py/Twisted/doc/core/examples/echoserv.py
  95. 0 30
      desktop/core/ext-py/Twisted/doc/core/examples/echoserv_ssl.py
  96. 0 20
      desktop/core/ext-py/Twisted/doc/core/examples/echoserv_udp.py
  97. 0 17
      desktop/core/ext-py/Twisted/doc/core/examples/filewatch.py
  98. 0 113
      desktop/core/ext-py/Twisted/doc/core/examples/ftpclient.py
  99. 0 55
      desktop/core/ext-py/Twisted/doc/core/examples/ftpserver.py
  100. 0 69
      desktop/core/ext-py/Twisted/doc/core/examples/gpsfix.py

+ 0 - 10
desktop/core/ext-py/Beaker/.hgignore

@@ -1,10 +0,0 @@
-
-# Automatically generated by `hgimportsvn`
-syntax:glob
-.svn
-*.pyc
-*.egg-info
-beaker/docs/build
-container_file
-container_dbm
-tests/*/container_*

+ 0 - 26
desktop/core/ext-py/Beaker/.hgtags

@@ -1,26 +0,0 @@
-4cfae69a4e425396c8aafad69e620d669f14a986 v0.5
-793218d03763817d98c5b6b3ee1e11e68171d8a7 v0.7.5
-19d215f1d4489d1b49ca05f41846e3983317e508 v0.8
-30ab3a978bec66c3437c29fceadcbc68ef9e9d0b v0.8.1
-d3a283832eea93bde5370f6696e09bb710a72547 v0.9
-d3a283832eea93bde5370f6696e09bb710a72547 v0.9
-05692a4bedf24524666bc59fb9cce6a13f9536ac v0.9.1
-4522f4b074ede11e63f07c7027bea5c9ca4f9bcd v0.9.2
-80f0cede0705ef6362e539ce4b5f0c87349eeef4 v0.9.3
-59237dd1d96262a83685617b2d305b7e55ae86a2 v0.9.4
-7ba1c094218b52c2e5d88c3687cab50bbbe81c81 v0.9.5
-0c772cbe08f3f6f02bf930b8f0f5fc0e1b225239 v1.0
-a3fa827c70246a57f3893c2496c73edf93ab77fe v1.0.1
-c258512c54efa7665b777393fcee5c9bd7e5f57a v1.0.2
-2fe6b4dbd73f6ce8e46a6709e9b1ca33d31d2df0 v1.0.3
-92506e9abe02c6147a15ba6de622b2eb1d9de029 v1.1
-2d2ac26bae8e5f6684da9564ba4e78f772fa8519 v1.1.1
-93b9dfcbe1dd9a7b78a88d502fb3e0c1cdb13d2e v1.1.2
-9fccf9544e4a9596102958e6eaa9f6724d35b064 v1.1.3
-b958d0a51dde75a72754c3befab63879552b2048 v1.2
-3c524e8a984ba2b6ecfb14055dcbfa56a9709575 v1.2.1
-279caf5065d3364b5f4de073b7728cd42f692b39 v1.2.2
-648a4ef26097991c40e29b6e8c17d44efe812363 v1.3
-0321f770855c4c272d08bd803bd7f37116b9aa9b v1.3.1
-345f9530e54d250a0456257ede314debb6acea77 v1.4
-2aca643bd310fdb35452374f7cbd913c8dbb7899 v1.4.1

+ 0 - 381
desktop/core/ext-py/Beaker/CHANGELOG

@@ -1,381 +0,0 @@
-Release 1.4.2 (9/25/2009)
-=========================
-
-* Fix bug where memcached may yank a value after the has_value but before
-  the value can be fetched.
-* Fix properties for setting the path. Fixes #15.
-* Fix the 'TypeError: argument must be an int, or have a fileno()
-  method' erorr sporadically emitted by FileSynchronizer under moderate
-  load.
-
-Release 1.4.1 (9/10/2009)
-=========================
-
-* Fix verification of options to throw an error if a beaker param is an
-  empty string.
-* Add CacheManager.invalidate function to easily invalidate cache
-  spaces created by the use of the cache decorator.
-* Add CacheManager.region_invalidate function to easily invalidate cache
-  spaces created by the use of the cache_region decorator.
-* Fix the InvalidCryptoBackendError exception triggering a TypeError. Patch
-  from dz, fixes #13.
-
-Release 1.4 (7/24/2009)
-=======================
-
-* Fix bug with hmac on Python 2.4. Patch from toshio, closes ticket #2133
-  from the TurboGears2 Trac.
-* Fix bug with occasional ValueError from FileNamespaceManager.do_open.
-  Fixes #10.
-* Fixed bug with session files being saved despite being new and not
-  saved.
-* Fixed bug with CacheMiddleware overwriting configuration with default
-  arguments despite prior setting.
-* Fixed bug with SyntaxError not being caught properly in entry point
-  discovery.
-* Changed to using BlobProperty for Google Datastore.
-* Added domain/path properties to the session. This allows one to
-  dynamically set the cookie's domain and/or path on the fly, which
-  will then be set on the cookie for the session.
-* Added support for cookie-based sessions in Jython via the JCE (Java
-  Cryptography Extensions). Patch from Alex Grönholm.
-* Update Beaker database extensions to work with SQLAlchemy 0.6
-  PostgreSQL, and Jython.
-
-Release 1.3.1 (5/5/2009)
-========================
-
-* Added a whole bunch of Sphinx documentation for the updated site.
-* Added corresponding remove as an alias to the caches remove_value.
-* Fixed cookie session not having an invalidate function.
-* Fix bug with CacheMiddleware not using proper function to load
-  configuration options, missing the cache regions.
-
-Release 1.3 (4/6/2009)
-======================
-
-* Added last_accessed attribute to session to indicate the previous time the
-  session was last accessed.
-* Added setuptools entry points to dynamically discover additional namespace
-  backends.
-* Fixed bug with invalidate and locks, fixes #594.
-* Added cache.cache decorator for arbitrary caching.
-* Added cache.region decorator to the CacheManager object.
-* Added cache regions. Can be provided in a configuration INI type, or
-  by adding in a cache_regions arg to the CacheManager.
-* Fix bug with timeout not being saved properly.
-* Fix bug with cookie-only sessions sending cookies for new sessions even
-  if they weren't supposed to be saved.
-* Fix bug that caused a non-auto accessed session to not record the time it
-  was previously accessed resulting in session timeouts.
-* Add function to parse configuration dicts as appropriate for use with the
-  CacheManager.
-* The "expiretime" is no longer passed to the memcached backend - since
-  if memcached makes the expired item unavailable at the same time the
-  container expires it, then all actors must block until the new value
-  is available (i.e. breaks the anti-dogpile logic).
-
-
-Release 1.2.3 (3/2/2009)
-========================
-
-* Fix accessed increment to take place *after* the accessed time is checked
-  to see if it has expired. Fixes #580.
-* data_dir/lock_dir parameters are optional to most backends; if not
-  present, mutex-based locking will be used for creation functions
-* Adjustments to Container to better account for backends which
-  don't provide read/write locks, such as memcached.  As a result,
-  the plain "memory" cache no longer requires read/write mutexing.
-
-
-Release 1.2.2 (2/14/2009)
-=========================
-
-* Fix delete bug reported by andres with session not being deleted.
-
-
-Release 1.2.1 (2/09/2009)
-=========================
-
-* Fix memcached behavior as memcached returns None on nonexistent key
-  fetch which broke invalid session checking.
-
-
-Release 1.2 (1/22/2009)
-=======================
-
-* Updated session to only save to the storage *once* no under any/all
-  conditions rather than every time save() is called.
-* Added session.revert() function that reverts the session to the state at
-  the beginning of the request.
-* Updated session to store entire session data in a single namespace key,
-  this lets memcached work properly, and makes for more efficient use of the
-  storage system for sessions.
-
-
-Release 1.1.3 (12/29/2008)
-==========================
-
-* Fix the 1.1.2 old cache/session upgrader to handle the has_current_value
-  method.
-* Make InvalidCacheBackendError an ImportError.
-
-
-Release 1.1.2 (11/24/2008)
-==========================
-
-* Upgrade Beaker pre-1.1 cache/session values to the new format rather than
-  throwing an exception.
-
-
-Release 1.1.1 (11/24/2008)
-==========================
-
-* Fixed bug in Google extension which passed arguments it should no longer
-  pass to NamespaceManager.
-* Fixed bug involving lockfiles left open during cache "value creation"
-  step.
-
-
-Release 1.1 (11/16/2008)
-========================
-
-* file-based cache will not hold onto cached value once read from file;
-  will create new value if the file is deleted as opposed to re-using
-  what was last read.  This allows external removal of files to be
-  used as a cache-invalidation mechanism.
-* file-based locking will not unlink lockfiles; this can interfere
-  with the flock() mechanism in the event that a concurrent process
-  is accessing the files.  
-* Sending "type" and other namespace config arguments to cache.get()/
-  cache.put()/cache.remove_value() is deprecated.   The namespace
-  configuration is now preferred at the Cache level, i.e. when you construct
-  a Cache or call cache_manager.get_cache().  This removes the ambiguity
-  of Cache's dictionary interface and has_key() methods, which have
-  no awareness of those arguments.
-* the "expiretime" in use is stored in the cache itself, so that it is 
-  always available when calling has_key() and other methods.  Between
-  this change and the deprecation of 'type', the Cache no longer has
-  any need to store cache configuration in memory per cache key, which in a 
-  dynamically-generated key scenario stores an arbitrarily large number 
-  of configurations - essentially a memory leak.
-* memcache caching has been vastly improved, no longer stores a list of
-  all keys, which along the same theme prevented efficient usage for an 
-  arbitrarily large number of keys.  The keys() method is now unimplemented, 
-  and cache.remove() clears the entire memcache cache across all namespaces.  
-  This is what the memcache API provides so it's the best we can do. 
-* memcache caching passes along "expiretime" to the memcached "time"
-  parameter, so that the cache itself can reduce its size for elements which
-  are expired (memcache seems to manage its size in any case, this is just a
-  hint to improve its operation).
-* replaced homegrown ThreadLocal implementation with threading.local, falls
-  back to a 2.3 compat one for python<2.4
-
-
-Release 1.0.3 (10/14/2008)
-==========================
-
-* Fixed os.getpid issue on GAE.
-* CookieSession will add '_expires' value to data when an expire time is set, 
-  and uses it
-
-
-Release 1.0.2 (9/22/2008)
-=========================
-
-* Fixed bug caused when attempting to invalidate a session that hadn't
-  previously been created.
-
-
-Release 1.0.1 (8/19/2008)
-=========================
-
-* Bug fix for cookie sessions to retain id before clearing values.
-
-
-Release 1.0 (8/13/2008)
-=======================
-
-* Added cookie delete to both cookie only sessions and normal sessions, to
-  help with proxies and such that may determine whether a user is logged in
-  via a cookie. (cookie varies, etc.). Suggested by Felix Schwarz.
-* cache.get_value() now uses the given **kwargs in all cases in the same
-  manner as cache.set_value().  This way you can send a new createfunc
-  to cache.get_value() each time and it will be used.
-
-  
-Release 0.9.5 (6/19/2008)
-=========================
-
-* Fixed bug in memcached to be tolerant of keys disappearing when memcached
-  expires them.
-* Fixed the cache functionality to actually work, previously set_value was
-  ignored if there was already a value set.
-
-
-Release 0.9.4 (4/13/2008)
-=========================
-
-* Adding 'google' backend datastore, available by specifying 'google' as the
-  cache/session type. Note that this takes an optional table_name used to name
-  the model class used.
-* SECURITY BUG: Fixed security issue with Beaker not properly removing
-  directory escaping characters from the session ID when un-signed sessions
-  are used. Reported with patch by Felix Schwarz.
-* Fixed bug with Beaker not playing well with Registry when its placed above
-  it in the stack. Thanks Wichert Akkerman.
-
-
-Release 0.9.3 (2/28/2008)
-=========================
-
-* Adding 'id' to cookie-based sessions for better compatibility.
-* Fixed error with exception still raised for PyCrypto missing.
-* WARNING: Session middleware no longer catches Paste HTTP Exceptions, apps
-  are now expected to capture and handle Paste HTTP Exceptions themselves.
-* Fixed Python 2.4 compatibility bug in hmac.
-* Fixed key lookup bug on cache object to only use the settings for the key
-  lookup. Found by Andrew Stromnov.
-
-
-Release 0.9.2 (2/13/2008)
-=========================
-
-* Added option to make Beaker use a secure cookie.
-* Removed CTRCipher as pycryptopp doesn't need it.
-* Changed AES to use 256 bit.
-* Fixed signing code to use hmac with sha for better signing security.
-* Fixed memcached code to use delete_multi on clearing the keys for efficiency
-  and updated key retrieval to properly store and retrieve None values.
-* Removing cookie.py and signed cookie middleware, as the environ_key option
-  for session middleware provides a close enough setting.
-* Added option to use just cookie-based sessions without requiring
-  encryption.
-* Switched encryption requirement from PyCrypto to pycryptopp which uses a 
-  proper AES in Counter Mode.
-
-
-Release 0.9.1 (2/4/2008)
-========================
-
-* Fixed bug in middleware using module that wasn't imported.
-
-
-Release 0.9 (12/17/07)
-======================
-
-* Fixed bug in memcached replace to actually replace spaces properly.
-* Fixed md5 cookie signature to use SHA-1 when available.
-* Updated cookie-based session storage to use 256-bit AES-CTR mode with a
-  SHA-1 HMAC signature. Now requires PyCrypto to use for AES scheme.
-* WARNING: Moved session and cache middleware to middleware, as per the old
-  deprecation warnings had said was going to happen for 0.8.
-* Added cookie-only session storage with RC4 ciphered encryption, requires 
-  Python 2.4.
-* Add the ability to specify the cookie's domain for sessions.
-
-
-Release 0.8.1 (11/15/07)
-========================
-
-* Fixed bug in database.py not properly handling missing sqlalchemy library.
-
-
-Release 0.8 (10/17/07)
-======================
-
-* Fixed bug in prior db update causing session to occasionally not be written
-  back to the db.
-* Fixed memcached key error with keys containing spaces. Thanks Jim Musil.
-* WARNING: Major change to ext:database to use a single row per namespace.
-  Additionally, there's an accessed and created column present to support 
-  easier deletion of old cache/session data. You *will* need to drop any
-  existing tables being used by the ext:database backend.
-* Streamline ext:database backend to avoid unnecessary database selects for
-  repeat data.
-* Added SQLAlchemy 0.4 support to ext:database backend.
-
-
-Release 0.7.5 (08/18/07)
-========================
-
-* Fixed data_dir parsing for session string coercions, no longer picks up None
-  as a data_dir.
-* Fixed session.get_by_id to lookup recently saved sessions properly, also
-  updates session with creation/access time upon save.
-* Add unit tests for get_by_id function. Updated get_by_id to not result in
-  additional session files.
-* Added session.get_by_id function to retrieve a session of the given id.
-
-
-Release 0.7.4 (07/09/07)
-========================
-
-* Fixed issue with Beaker not properly handling arguments as Pylons may pass
-  them in.
-* Fixed unit test to catch file removal exception.
-* Fixed another bug in synchronization, this one involving reentrant
-  conditions with file synchronization
-* If a file open fails due to pickling errors, locks just opened
-  are released unconditionally
-
-
-Release 0.7.3 (06/08/07)
-========================
-
-* Beaker was not properly parsing input options to session middleware. Thanks
-  to Yannick Gingras and Timothy S for spotting the issue.
-* Changed session to only send the cookie header if its a new session and
-  save() was called. Also only creates the session file under these 
-  conditions.
-
-
-Release 0.7.2 (05/19/07)
-========================
-
-* Added deprecation warning for middleware move, relocated middleware to cache
-  and session modules for backwards compatibility.
-
-
-Release 0.7.1 05/18/07)
-=======================
-
-* adjusted synchronization logic to account for Mako/new Cache object's 
-  multithreaded usage of Container.
-
-
-Release 0.7 (05/18/07)
-======================
-
-* WARNING: Cleaned up Cache object based on Mako cache object, this changes
-  the call interface slightly for creating a Cache object directly. The
-  middleware cache object is unaffected from an end-user view. This change
-  also avoids duplicate creations of Cache objects.
-* Adding database backend and unit tests.
-* Added memcached test, fixed memcached namespace arg passing.
-* Fixed session and cache tests, still failing syncdict test. Added doctests
-  for Cache and Session middleware.
-* Cleanup of container/cache/container_test
-* Namespaces no longer require a context, removed NamespaceContext?
-* Logging in container.py uses logging module
-* Cleanup of argument passing, use name **kwargs instead of **params for 
-  generic kwargs
-* Container classes contain a static create_namespace() method, namespaces are 
-  accessed from the ContainerContext? via string name + container class alone
-* Implemented (but not yet tested) clear() method on Cache, locates all 
-  Namespaces used thus far and clears each one based on its keys() collection
-* Fixed Cache.clear() method to actually clear the Cache namespace.
-* Updated memcached backend to split servers on ';' for multiple memcached
-  backends.
-* Merging MyghtyUtils code into Beaker.
-
-
-Release 0.6.3 (03/18/2007)
-==========================
-
-* Added api with customized Session that doesn't require a Myghty request 
-  object, just a dict. Updated session to use the new version.
-* Removing unicode keys as some dbm backends can't handle unicode keys.
-* Adding core files that should've been here.
-* More stringent checking for existence of a session.
-* Avoid recreating the session object when it's empty.

+ 0 - 27
desktop/core/ext-py/Beaker/LICENSE

@@ -1,27 +0,0 @@
-Copyright (c) 2006, 2007 Ben Bangert, Mike Bayer, Philip Jenvey
-                         and contributors.
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-1. Redistributions of source code must retain the above copyright
-   notice, this list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright
-   notice, this list of conditions and the following disclaimer in the
-   documentation and/or other materials provided with the distribution.
-3. The name of the author or contributors may not be used to endorse or
-   promote products derived from this software without specific prior
-   written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGE.

+ 0 - 69
desktop/core/ext-py/Beaker/PKG-INFO

@@ -1,69 +0,0 @@
-Metadata-Version: 1.0
-Name: Beaker
-Version: 1.4.2
-Summary: A Session and Caching library with WSGI Middleware
-Home-page: http://beaker.groovie.org
-Author: Ben Bangart, Mike Bayer, Philip Jenvey
-Author-email: ben@groovie.org, pjenvey@groovie.org
-License: BSD
-Description: Cache and Session Library
-        +++++++++++++++++++++++++
-        
-        About
-        =====
-        
-        Beaker is a web session and general caching library that includes WSGI
-        middleware for use in web applications.
-        
-        As a general caching library, Beaker can handle storing for various times
-        any Python object that can be pickled with optional back-ends on a
-        fine-grained basis.
-        
-        Beaker was built largely on the code from MyghtyUtils, then refactored and
-        extended with database support.
-        
-        Beaker includes Cache and Session WSGI middleware to ease integration with
-        WSGI capable frameworks, and is automatically used by `Pylons
-        <http://pylonshq.com/>`_.
-        
-        
-        Features
-        ========
-        
-        * Fast, robust performance
-        * Multiple reader/single writer lock system to avoid duplicate simultaneous
-        cache creation
-        * Cache back-ends include dbm, file, memory, memcached, and database (Using
-        SQLAlchemy for multiple-db vendor support)
-        * Signed cookie's to prevent session hijacking/spoofing
-        * Cookie-only sessions to remove the need for a db or file backend (ideal
-        for clustered systems)
-        * Extensible Container object to support new back-ends
-        * Cache's can be divided into namespaces (to represent templates, objects,
-        etc.) then keyed for different copies
-        * Create functions for automatic call-backs to create new cache copies after
-        expiration
-        * Fine-grained toggling of back-ends, keys, and expiration per Cache object
-        
-        
-        Documentation
-        =============
-        
-        Documentation can be found on the `Official Beaker Docs site
-        <http://beaker.groovie.org/>`_.
-        
-        
-        Source
-        ======
-        
-        The latest developer version is available in a `Mercurial repository
-        <http://bitbucket.org/bbangert/beaker/get/tip.gz#egg=Beaker-dev>`_.
-        
-Keywords: wsgi myghty session web cache middleware
-Platform: UNKNOWN
-Classifier: Development Status :: 5 - Production/Stable
-Classifier: Environment :: Web Environment
-Classifier: Intended Audience :: Developers
-Classifier: License :: OSI Approved :: BSD License
-Classifier: Programming Language :: Python
-Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content

+ 0 - 1
desktop/core/ext-py/Beaker/beaker/__init__.py

@@ -1 +0,0 @@
-#

+ 0 - 385
desktop/core/ext-py/Beaker/beaker/cache.py

@@ -1,385 +0,0 @@
-"""Cache object
-
-The Cache object is used to manage a set of cache files and their
-associated backend. The backends can be rotated on the fly by
-specifying an alternate type when used.
-
-Advanced users can add new backends in beaker.backends
-
-"""
-import pkg_resources
-import warnings
-
-import beaker.container as container
-import beaker.util as util
-from beaker.exceptions import BeakerException, InvalidCacheBackendError
-
-# Initialize the basic available backends
-clsmap = {
-          'memory':container.MemoryNamespaceManager,
-          'dbm':container.DBMNamespaceManager,
-          'file':container.FileNamespaceManager,
-          }
-
-
-# Load up the additional entry point defined backends
-for entry_point in pkg_resources.iter_entry_points('beaker.backends'):
-    try:
-        NamespaceManager = entry_point.load()
-        name = entry_point.name
-        if name in clsmap:
-            raise BeakerException("NamespaceManager name conflict,'%s' "
-                                  "already loaded" % name)
-        clsmap[name] = NamespaceManager
-    except (InvalidCacheBackendError, SyntaxError):
-        # Ignore invalid backends
-        pass
-    except:
-        import sys
-        from pkg_resources import DistributionNotFound
-        # Warn when there's a problem loading a NamespaceManager
-        if not isinstance(sys.exc_info()[1], DistributionNotFound):
-            import traceback
-            from StringIO import StringIO
-            tb = StringIO()
-            traceback.print_exc(file=tb)
-            warnings.warn("Unable to load NamespaceManager entry point: '%s': "
-                          "%s" % (entry_point, tb.getvalue()), RuntimeWarning,
-                          2)
-
-
-# Load legacy-style backends
-try:
-    import beaker.ext.memcached as memcached
-    clsmap['ext:memcached'] = memcached.MemcachedNamespaceManager
-except InvalidCacheBackendError, e:
-    clsmap['ext:memcached'] = e
-
-try:
-    import beaker.ext.database as database
-    clsmap['ext:database'] = database.DatabaseNamespaceManager
-except InvalidCacheBackendError, e:
-    clsmap['ext:database'] = e
-
-try:
-    import beaker.ext.sqla as sqla
-    clsmap['ext:sqla'] = sqla.SqlaNamespaceManager
-except InvalidCacheBackendError, e:
-    clsmap['ext:sqla'] = e
-
-try:
-    import beaker.ext.google as google
-    clsmap['ext:google'] = google.GoogleNamespaceManager
-except (InvalidCacheBackendError, SyntaxError), e:
-    clsmap['ext:google'] = e
-
-
-class Cache(object):
-    """Front-end to the containment API implementing a data cache.
-
-    ``namespace``
-        the namespace of this Cache
-
-    ``type``
-        type of cache to use
-
-    ``expire``
-        seconds to keep cached data
-
-    ``expiretime``
-        seconds to keep cached data (legacy support)
-
-    ``starttime``
-        time when cache was cache was
-    """
-    def __init__(self, namespace, type='memory', expiretime=None,
-                 starttime=None, expire=None, **nsargs):
-        try:
-            cls = clsmap[type]
-            if isinstance(cls, InvalidCacheBackendError):
-                raise cls
-        except KeyError:
-            raise TypeError("Unknown cache implementation %r" % type)
-            
-        self.namespace = cls(namespace, **nsargs)
-        self.expiretime = expiretime or expire
-        self.starttime = starttime
-        self.nsargs = nsargs
-        
-    def put(self, key, value, **kw):
-        self._get_value(key, **kw).set_value(value)
-    set_value = put
-    
-    def get(self, key, **kw):
-        """Retrieve a cached value from the container"""
-        return self._get_value(key, **kw).get_value()
-    get_value = get
-    
-    def remove_value(self, key, **kw):
-        mycontainer = self._get_value(key, **kw)
-        if mycontainer.has_current_value():
-            mycontainer.clear_value()
-    remove = remove_value
-
-    def _get_value(self, key, **kw):
-        if isinstance(key, unicode):
-            key = key.encode('ascii', 'backslashreplace')
-
-        if 'type' in kw:
-            return self._legacy_get_value(key, **kw)
-
-        kw.setdefault('expiretime', self.expiretime)
-        kw.setdefault('starttime', self.starttime)
-        
-        return container.Value(key, self.namespace, **kw)
-    
-    def _legacy_get_value(self, key, type, **kw):
-        expiretime = kw.pop('expiretime', self.expiretime)
-        starttime = kw.pop('starttime', None)
-        createfunc = kw.pop('createfunc', None)
-        kwargs = self.nsargs.copy()
-        kwargs.update(kw)
-        c = Cache(self.namespace.namespace, type=type, **kwargs)
-        return c._get_value(key, expiretime=expiretime, createfunc=createfunc, 
-                            starttime=starttime)
-    _legacy_get_value = util.deprecated(_legacy_get_value, "Specifying a "
-        "'type' and other namespace configuration with cache.get()/put()/etc. "
-        "is deprecated. Specify 'type' and other namespace configuration to "
-        "cache_manager.get_cache() and/or the Cache constructor instead.")
-    
-    def clear(self):
-        """Clear all the values from the namespace"""
-        self.namespace.remove()
-    
-    # dict interface
-    def __getitem__(self, key):
-        return self.get(key)
-    
-    def __contains__(self, key):
-        return self._get_value(key).has_current_value()
-    
-    def has_key(self, key):
-        return key in self
-    
-    def __delitem__(self, key):
-        self.remove_value(key)
-    
-    def __setitem__(self, key, value):
-        self.put(key, value)
-
-
-class CacheManager(object):
-    def __init__(self, **kwargs):
-        """Initialize a CacheManager object with a set of options
-        
-        Options should be parsed with the
-        :func:`~beaker.util.parse_cache_config_options` function to
-        ensure only valid options are used.
-        
-        """
-        self.kwargs = kwargs
-        self.caches = {}
-        self.regions = kwargs.pop('cache_regions', {})
-    
-    def get_cache(self, name, **kwargs):
-        kw = self.kwargs.copy()
-        kw.update(kwargs)
-        return self.caches.setdefault(name + str(kw), Cache(name, **kw))
-    
-    def get_cache_region(self, name, region):
-        if region not in self.regions:
-            raise BeakerException('Cache region not configured: %s' % region)
-        kw = self.regions[region]
-        return self.caches.setdefault(name + str(kw), Cache(name, **kw))
-    
-    def region(self, region, *args):
-        """Decorate a function to cache itself using a cache region
-        
-        The region decorator requires arguments if there are more than
-        2 of the same named function, in the same module. This is
-        because the namespace used for the functions cache is based on
-        the functions name and the module.
-        
-        
-        Example::
-            
-            # Assuming a cache object is available like:
-            cache = CacheManager(dict_of_config_options)
-            
-            
-            def populate_things():
-                
-                @cache.region('short_term', 'some_data')
-                def load(search_term, limit, offset):
-                    return load_the_data(search_term, limit, offset)
-                
-                return load('rabbits', 20, 0)
-        
-        .. note::
-            
-            The function being decorated must only be called with
-            positional arguments.
-        
-        """
-        cache = [None]
-        key = " ".join(str(x) for x in args)
-        
-        def decorate(func):
-            namespace = util.func_namespace(func)
-            def cached(*args):
-                reg = self.regions[region]
-                if not reg.get('enabled', True):
-                    return func(*args)
-                
-                if not cache[0]:
-                    cache[0] = self.get_cache_region(namespace, region)
-                
-                cache_key = key + " " + " ".join(str(x) for x in args)
-                def go():
-                    return func(*args)
-                
-                return cache[0].get_value(cache_key, createfunc=go)
-            cached._arg_namespace = namespace
-            cached._arg_region = region
-            return cached
-        return decorate
-
-    def region_invalidate(self, namespace, region, *args):
-        """Invalidate a cache region namespace or decorated function
-        
-        This function only invalidates cache spaces created with the
-        cache_region decorator.
-        
-        namespace
-            Either the namespace of the result to invalidate, or the
-            name of the cached function
-        
-        region
-            The region the function was cached to. If the function was
-            cached to a single region then this argument can be None
-        
-        args
-            Arguments that were used to differentiate the cached
-            function as well as the arguments passed to the decorated
-            function
-
-        Example::
-            
-            # Assuming a cache object is available like:
-            cache = CacheManager(dict_of_config_options)
-            
-            def populate_things(invalidate=False):
-                
-                @cache.region('short_term', 'some_data')
-                def load(search_term, limit, offset):
-                    return load_the_data(search_term, limit, offset)
-                
-                # If the results should be invalidated first
-                if invalidate:
-                    cache.region_invalidate(load, None, 'some_data',
-                                            'rabbits', 20, 0)
-                return load('rabbits', 20, 0)
-            
-        
-        """
-        if callable(namespace):
-            if not region:
-                region = namespace._arg_region
-            namespace = namespace._arg_namespace
-
-        if not region:
-            raise BeakerException("Region or callable function namespace is required")
-        else:
-            region = self.regions[region]
-        
-        cache = self.get_cache(namespace, **region)
-        cache_key = " ".join(str(x) for x in args)
-        cache.remove_value(cache_key)
-
-    def cache(self, *args, **kwargs):
-        """Decorate a function to cache itself with supplied parameters
-
-        args
-            Used to make the key unique for this function, as in region()
-            above.
-
-        kwargs
-            Parameters to be passed to get_cache(), will override defaults
-
-        Example::
-
-            # Assuming a cache object is available like:
-            cache = CacheManager(dict_of_config_options)
-            
-            
-            def populate_things():
-                
-                @cache.cache('mycache', expire=15)
-                def load(search_term, limit, offset):
-                    return load_the_data(search_term, limit, offset)
-                
-                return load('rabbits', 20, 0)
-        
-        .. note::
-            
-            The function being decorated must only be called with
-            positional arguments. 
-
-        """
-        cache = [None]
-        key = " ".join(str(x) for x in args)
-        
-        def decorate(func):
-            namespace = util.func_namespace(func)
-            def cached(*args):
-                if not cache[0]:
-                    cache[0] = self.get_cache(namespace, **kwargs)
-                cache_key = key + " " + " ".join(str(x) for x in args)
-                def go():
-                    return func(*args)
-                return cache[0].get_value(cache_key, createfunc=go)
-            cached._arg_namespace = namespace
-            return cached
-        return decorate
-
-    def invalidate(self, func, *args, **kwargs):
-        """Invalidate a cache decorated function
-        
-        This function only invalidates cache spaces created with the
-        cache decorator.
-        
-        func
-            Decorated function to invalidate
-        
-        args
-            Used to make the key unique for this function, as in region()
-            above.
-
-        kwargs
-            Parameters that were passed for use by get_cache(), note that
-            this is only required if a ``type`` was specified for the
-            function
-
-        Example::
-            
-            # Assuming a cache object is available like:
-            cache = CacheManager(dict_of_config_options)
-            
-            
-            def populate_things(invalidate=False):
-                
-                @cache.cache('mycache', type="file", expire=15)
-                def load(search_term, limit, offset):
-                    return load_the_data(search_term, limit, offset)
-                
-                # If the results should be invalidated first
-                if invalidate:
-                    cache.invalidate(load, 'mycache', 'rabbits', 20, 0, type="file")
-                return load('rabbits', 20, 0)
-        
-        """
-        namespace = func._arg_namespace
-
-        cache = self.get_cache(namespace, **kwargs)
-        cache_key = " ".join(str(x) for x in args)
-        cache.remove_value(cache_key)

+ 0 - 600
desktop/core/ext-py/Beaker/beaker/container.py

@@ -1,600 +0,0 @@
-"""Container and Namespace classes"""
-import anydbm
-import cPickle
-import logging
-import os.path
-import time
-
-import beaker.util as util
-from beaker.exceptions import CreationAbortedError, MissingCacheParameter
-from beaker.synchronization import _threading, file_synchronizer, \
-     mutex_synchronizer, NameLock, null_synchronizer
-
-__all__ = ['Value', 'Container', 'ContainerContext',
-           'MemoryContainer', 'DBMContainer', 'NamespaceManager',
-           'MemoryNamespaceManager', 'DBMNamespaceManager', 'FileContainer',
-           'OpenResourceNamespaceManager',
-           'FileNamespaceManager', 'CreationAbortedError']
-
-
-logger = logging.getLogger('beaker.container')
-if logger.isEnabledFor(logging.DEBUG):
-    debug = logger.debug
-else:
-    def debug(message, *args):
-        pass
-
-
-class NamespaceManager(object):
-    """Handles dictionary operations and locking for a namespace of
-    values.
-    
-    The implementation for setting and retrieving the namespace data is
-    handled by subclasses.
-    
-    NamespaceManager may be used alone, or may be privately accessed by
-    one or more Container objects.  Container objects provide per-key
-    services like expiration times and automatic recreation of values.
-    
-    Multiple NamespaceManagers created with a particular name will all
-    share access to the same underlying datasource and will attempt to
-    synchronize against a common mutex object.  The scope of this
-    sharing may be within a single process or across multiple
-    processes, depending on the type of NamespaceManager used.
-    
-    The NamespaceManager itself is generally threadsafe, except in the
-    case of the DBMNamespaceManager in conjunction with the gdbm dbm
-    implementation.
-
-    """
-    def __init__(self, namespace):
-        self.namespace = namespace
-        
-    def get_creation_lock(self, key):
-        raise NotImplementedError()
-
-    def do_remove(self):
-        raise NotImplementedError()
-
-    def acquire_read_lock(self):
-        pass
-
-    def release_read_lock(self):
-        pass
-
-    def acquire_write_lock(self, wait=True):
-        return True
-
-    def release_write_lock(self):
-        pass
-
-    def has_key(self, key):
-        return self.__contains__(key)
-
-    def __getitem__(self, key):
-        raise NotImplementedError()
-        
-    def __setitem__(self, key, value):
-        raise NotImplementedError()
-    
-    def set_value(self, key, value, expiretime=None):
-        """Optional set_value() method called by Value.
-        
-        Allows an expiretime to be passed, for namespace
-        implementations which can prune their collections
-        using expiretime.
-        
-        """
-        self[key] = value
-        
-    def __contains__(self, key):
-        raise NotImplementedError()
-
-    def __delitem__(self, key):
-        raise NotImplementedError()
-    
-    def keys(self):
-        raise NotImplementedError()
-    
-    def remove(self):
-        self.do_remove()
-        
-
-class OpenResourceNamespaceManager(NamespaceManager):
-    """A NamespaceManager where read/write operations require opening/
-    closing of a resource which is possibly mutexed.
-    
-    """
-    def __init__(self, namespace):
-        NamespaceManager.__init__(self, namespace)
-        self.access_lock = self.get_access_lock()
-        self.openers = 0
-        self.mutex = _threading.Lock()
-
-    def get_access_lock(self):
-        raise NotImplementedError()
-
-    def do_open(self, flags): 
-        raise NotImplementedError()
-
-    def do_close(self): 
-        raise NotImplementedError()
-
-    def acquire_read_lock(self): 
-        self.access_lock.acquire_read_lock()
-        try:
-            self.open('r', checkcount = True)
-        except:
-            self.access_lock.release_read_lock()
-            raise
-            
-    def release_read_lock(self):
-        try:
-            self.close(checkcount = True)
-        finally:
-            self.access_lock.release_read_lock()
-        
-    def acquire_write_lock(self, wait=True): 
-        r = self.access_lock.acquire_write_lock(wait)
-        try:
-            if (wait or r): 
-                self.open('c', checkcount = True)
-            return r
-        except:
-            self.access_lock.release_write_lock()
-            raise
-            
-    def release_write_lock(self): 
-        try:
-            self.close(checkcount=True)
-        finally:
-            self.access_lock.release_write_lock()
-
-    def open(self, flags, checkcount=False):
-        self.mutex.acquire()
-        try:
-            if checkcount:
-                if self.openers == 0: 
-                    self.do_open(flags)
-                self.openers += 1
-            else:
-                self.do_open(flags)
-                self.openers = 1
-        finally:
-            self.mutex.release()
-
-    def close(self, checkcount=False):
-        self.mutex.acquire()
-        try:
-            if checkcount:
-                self.openers -= 1
-                if self.openers == 0: 
-                    self.do_close()
-            else:
-                if self.openers > 0:
-                    self.do_close()
-                self.openers = 0
-        finally:
-            self.mutex.release()
-
-    def remove(self):
-        self.access_lock.acquire_write_lock()
-        try:
-            self.close(checkcount=False)
-            self.do_remove()
-        finally:
-            self.access_lock.release_write_lock()
-
-class Value(object):
-    __slots__ = 'key', 'createfunc', 'expiretime', 'expire_argument', 'starttime', 'storedtime',\
-                'namespace'
-
-    def __init__(self, key, namespace, createfunc=None, expiretime=None, starttime=None):
-        self.key = key
-        self.createfunc = createfunc
-        self.expire_argument = expiretime
-        self.starttime = starttime
-        self.storedtime = -1
-        self.namespace = namespace
-
-    def has_value(self):
-        """return true if the container has a value stored.
-
-        This is regardless of it being expired or not.
-
-        """
-        self.namespace.acquire_read_lock()
-        try:    
-            return self.namespace.has_key(self.key)
-        finally:
-            self.namespace.release_read_lock()
-
-    def can_have_value(self):
-        return self.has_current_value() or self.createfunc is not None  
-
-    def has_current_value(self):
-        self.namespace.acquire_read_lock()
-        try:    
-            has_value = self.namespace.has_key(self.key)
-            if has_value:
-                value = self.__get_value()
-                return not self._is_expired()
-            else:
-                return False
-        finally:
-            self.namespace.release_read_lock()
-
-    def _is_expired(self):
-        """Return true if this container's value is expired.
-        
-        Note that this method is only correct if has_current_value()
-        or get_value() have been called already.
-        
-        """
-        return (
-            (
-                self.starttime is not None and
-                self.storedtime < self.starttime
-            )
-            or
-            (
-                self.expiretime is not None and
-                time.time() >= self.expiretime + self.storedtime
-            )
-        )
-
-    def get_value(self):
-        self.namespace.acquire_read_lock()
-        try:
-            has_value = self.has_value()
-            if has_value:
-                try:
-                    value = self.__get_value()
-                    if not self._is_expired():
-                        return value
-                except KeyError:
-                    # guard against un-mutexed backends raising KeyError
-                    pass
-                    
-            if not self.createfunc:
-                raise KeyError(self.key)
-        finally:
-            self.namespace.release_read_lock()
-
-        has_createlock = False
-        creation_lock = self.namespace.get_creation_lock(self.key)
-        if has_value:
-            if not creation_lock.acquire(wait=False):
-                debug("get_value returning old value while new one is created")
-                return value
-            else:
-                debug("lock_creatfunc (didnt wait)")
-                has_createlock = True
-
-        if not has_createlock:
-            debug("lock_createfunc (waiting)")
-            creation_lock.acquire()
-            debug("lock_createfunc (waited)")
-
-        try:
-            # see if someone created the value already
-            self.namespace.acquire_read_lock()
-            try:
-                if self.has_value():
-                    try:
-                        value = self.__get_value()
-                        if not self._is_expired():
-                            return value
-                    except KeyError:
-                        # guard against un-mutexed backends raising KeyError
-                        pass
-            finally:
-                self.namespace.release_read_lock()
-
-            debug("get_value creating new value")
-            v = self.createfunc()
-            self.set_value(v)
-            return v
-        finally:
-            creation_lock.release()
-            debug("released create lock")
-
-    def __get_value(self):
-        value = self.namespace[self.key]
-        try:
-            self.storedtime, self.expiretime, value = value
-        except ValueError:
-            if not len(value) == 2:
-                raise
-            # Old format: upgrade
-            self.storedtime, value = value
-            self.expiretime = self.expire_argument = None
-            debug("get_value upgrading time %r expire time %r", self.storedtime, self.expire_argument)
-            self.namespace.release_read_lock()
-            self.set_value(value)
-            self.namespace.acquire_read_lock()
-        except TypeError:
-            # occurs when the value is None.  memcached 
-            # may yank the rug from under us in which case 
-            # that's the result
-            raise KeyError(self.key)            
-        return value
-
-    def set_value(self, value):
-        self.namespace.acquire_write_lock()
-        try:
-            self.storedtime = time.time()
-            debug("set_value stored time %r expire time %r", self.storedtime, self.expire_argument)
-            self.namespace.set_value(self.key, (self.storedtime, self.expire_argument, value))
-        finally:
-            self.namespace.release_write_lock()
-
-    def clear_value(self):
-        self.namespace.acquire_write_lock()
-        try:
-            debug("clear_value")
-            if self.namespace.has_key(self.key):
-                try:
-                    del self.namespace[self.key]
-                except KeyError:
-                    # guard against un-mutexed backends raising KeyError
-                    pass
-            self.storedtime = -1
-        finally:
-            self.namespace.release_write_lock()
-
-
-class MemoryNamespaceManager(NamespaceManager):
-    namespaces = util.SyncDict()
-
-    def __init__(self, namespace, **kwargs):
-        NamespaceManager.__init__(self, namespace)
-        self.dictionary = MemoryNamespaceManager.namespaces.get(self.namespace,
-                                                                dict)
-    def get_creation_lock(self, key):
-        return NameLock(
-            identifier="memorycontainer/funclock/%s/%s" % (self.namespace, key),
-            reentrant=True
-        )
-
-    def __getitem__(self, key): 
-        return self.dictionary[key]
-
-    def __contains__(self, key): 
-        return self.dictionary.__contains__(key)
-
-    def has_key(self, key): 
-        return self.dictionary.__contains__(key)
-        
-    def __setitem__(self, key, value):
-        self.dictionary[key] = value
-    
-    def __delitem__(self, key):
-        del self.dictionary[key]
-
-    def do_remove(self):
-        self.dictionary.clear()
-        
-    def keys(self):
-        return self.dictionary.keys()
-
-
-class DBMNamespaceManager(OpenResourceNamespaceManager):
-    def __init__(self, namespace, dbmmodule=None, data_dir=None, 
-            dbm_dir=None, lock_dir=None, digest_filenames=True, **kwargs):
-        self.digest_filenames = digest_filenames
-        
-        if not dbm_dir and not data_dir:
-            raise MissingCacheParameter("data_dir or dbm_dir is required")
-        elif dbm_dir:
-            self.dbm_dir = dbm_dir
-        else:
-            self.dbm_dir = data_dir + "/container_dbm"
-        util.verify_directory(self.dbm_dir)
-        
-        if not lock_dir and not data_dir:
-            raise MissingCacheParameter("data_dir or lock_dir is required")
-        elif lock_dir:
-            self.lock_dir = lock_dir
-        else:
-            self.lock_dir = data_dir + "/container_dbm_lock"
-        util.verify_directory(self.lock_dir)
-
-        self.dbmmodule = dbmmodule or anydbm
-
-        self.dbm = None
-        OpenResourceNamespaceManager.__init__(self, namespace)
-
-        self.file = util.encoded_path(root= self.dbm_dir,
-                                      identifiers=[self.namespace],
-                                      extension='.dbm',
-                                      digest_filenames=self.digest_filenames)
-        
-        debug("data file %s", self.file)
-        self._checkfile()
-
-    def get_access_lock(self):
-        return file_synchronizer(identifier=self.namespace,
-                                 lock_dir=self.lock_dir)
-                                 
-    def get_creation_lock(self, key):
-        return file_synchronizer(
-                    identifier = "dbmcontainer/funclock/%s" % self.namespace, 
-                    lock_dir=self.lock_dir
-                )
-
-    def file_exists(self, file):
-        if os.access(file, os.F_OK): 
-            return True
-        else:
-            for ext in ('db', 'dat', 'pag', 'dir'):
-                if os.access(file + os.extsep + ext, os.F_OK):
-                    return True
-                    
-        return False
-    
-    def _checkfile(self):
-        if not self.file_exists(self.file):
-            g = self.dbmmodule.open(self.file, 'c') 
-            g.close()
-                
-    def get_filenames(self):
-        list = []
-        if os.access(self.file, os.F_OK):
-            list.append(self.file)
-            
-        for ext in ('pag', 'dir', 'db', 'dat'):
-            if os.access(self.file + os.extsep + ext, os.F_OK):
-                list.append(self.file + os.extsep + ext)
-        return list
-
-    def do_open(self, flags):
-        debug("opening dbm file %s", self.file)
-        try:
-            self.dbm = self.dbmmodule.open(self.file, flags)
-        except:
-            self._checkfile()
-            self.dbm = self.dbmmodule.open(self.file, flags)
-
-    def do_close(self):
-        if self.dbm is not None:
-            debug("closing dbm file %s", self.file)
-            self.dbm.close()
-        
-    def do_remove(self):
-        for f in self.get_filenames():
-            os.remove(f)
-        
-    def __getitem__(self, key): 
-        return cPickle.loads(self.dbm[key])
-
-    def __contains__(self, key): 
-        return self.dbm.has_key(key)
-        
-    def __setitem__(self, key, value):
-        self.dbm[key] = cPickle.dumps(value)
-
-    def __delitem__(self, key):
-        del self.dbm[key]
-
-    def keys(self):
-        return self.dbm.keys()
-
-
-class FileNamespaceManager(OpenResourceNamespaceManager):
-    def __init__(self, namespace, data_dir=None, file_dir=None, lock_dir=None,
-                 digest_filenames=True, **kwargs):
-        self.digest_filenames = digest_filenames
-        
-        if not file_dir and not data_dir:
-            raise MissingCacheParameter("data_dir or file_dir is required")
-        elif file_dir:
-            self.file_dir = file_dir
-        else:
-            self.file_dir = data_dir + "/container_file"
-        util.verify_directory(self.file_dir)
-
-        if not lock_dir and not data_dir:
-            raise MissingCacheParameter("data_dir or lock_dir is required")
-        elif lock_dir:
-            self.lock_dir = lock_dir
-        else:
-            self.lock_dir = data_dir + "/container_file_lock"
-        util.verify_directory(self.lock_dir)
-        OpenResourceNamespaceManager.__init__(self, namespace)
-
-        self.file = util.encoded_path(root=self.file_dir, 
-                                      identifiers=[self.namespace],
-                                      extension='.cache',
-                                      digest_filenames=self.digest_filenames)
-        self.hash = {}
-        
-        debug("data file %s", self.file)
-
-    def get_access_lock(self):
-        return file_synchronizer(identifier=self.namespace,
-                                 lock_dir=self.lock_dir)
-                                 
-    def get_creation_lock(self, key):
-        return file_synchronizer(
-                identifier = "filecontainer/funclock/%s" % self.namespace, 
-                lock_dir = self.lock_dir
-                )
-        
-    def file_exists(self, file):
-        return os.access(file, os.F_OK)
-
-    def do_open(self, flags):
-        if self.file_exists(self.file):
-            fh = open(self.file, 'rb')
-            try:
-                self.hash = cPickle.load(fh)
-            except (IOError, OSError, EOFError, cPickle.PickleError, ValueError):
-                pass
-            fh.close()
-
-        self.flags = flags
-        
-    def do_close(self):
-        if self.flags == 'c' or self.flags == 'w':
-            fh = open(self.file, 'wb')
-            cPickle.dump(self.hash, fh)
-            fh.close()
-
-        self.hash = {}
-        self.flags = None
-                
-    def do_remove(self):
-        os.remove(self.file)
-        self.hash = {}
-        
-    def __getitem__(self, key): 
-        return self.hash[key]
-
-    def __contains__(self, key): 
-        return self.hash.has_key(key)
-        
-    def __setitem__(self, key, value):
-        self.hash[key] = value
-
-    def __delitem__(self, key):
-        del self.hash[key]
-
-    def keys(self):
-        return self.hash.keys()
-
-
-#### legacy stuff to support the old "Container" class interface
-
-namespace_classes = {}
-
-ContainerContext = dict
-    
-class ContainerMeta(type):
-    def __init__(cls, classname, bases, dict_):
-        namespace_classes[cls] = cls.namespace_class
-        return type.__init__(cls, classname, bases, dict_)
-    def __call__(self, key, context, namespace, createfunc=None,
-                 expiretime=None, starttime=None, **kwargs):
-        if namespace in context:
-            ns = context[namespace]
-        else:
-            nscls = namespace_classes[self]
-            context[namespace] = ns = nscls(namespace, **kwargs)
-        return Value(key, ns, createfunc=createfunc,
-                     expiretime=expiretime, starttime=starttime)
-
-class Container(object):
-    __metaclass__ = ContainerMeta
-    namespace_class = NamespaceManager
-
-class FileContainer(Container):
-    namespace_class = FileNamespaceManager
-
-class MemoryContainer(Container):
-    namespace_class = MemoryNamespaceManager
-
-class DBMContainer(Container):
-    namespace_class = DBMNamespaceManager
-
-DbmContainer = DBMContainer

+ 0 - 26
desktop/core/ext-py/Beaker/beaker/converters.py

@@ -1,26 +0,0 @@
-# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
-# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
-def asbool(obj):
-    if isinstance(obj, (str, unicode)):
-        obj = obj.strip().lower()
-        if obj in ['true', 'yes', 'on', 'y', 't', '1']:
-            return True
-        elif obj in ['false', 'no', 'off', 'n', 'f', '0']:
-            return False
-        else:
-            raise ValueError(
-                "String is not true/false: %r" % obj)
-    return bool(obj)
-
-def aslist(obj, sep=None, strip=True):
-    if isinstance(obj, (str, unicode)):
-        lst = obj.split(sep)
-        if strip:
-            lst = [v.strip() for v in lst]
-        return lst
-    elif isinstance(obj, (list, tuple)):
-        return obj
-    elif obj is None:
-        return []
-    else:
-        return [obj]

+ 0 - 35
desktop/core/ext-py/Beaker/beaker/crypto/__init__.py

@@ -1,35 +0,0 @@
-from warnings import warn
-
-from beaker.crypto.pbkdf2 import PBKDF2, strxor
-from beaker.exceptions import InvalidCryptoBackendError
-
-_implementations = ('pycrypto', 'jcecrypto')
-
-keyLength = None
-for impl_name in _implementations:
-    try:
-        package = 'beaker.crypto.%s' % impl_name
-        module = __import__(package, fromlist=('aesEncrypt', 'getKeyLength'))
-        keyLength = module.getKeyLength()
-        aesEncrypt = module.aesEncrypt
-        if keyLength >= 32:
-            break
-    except:
-        pass
-
-if not keyLength:
-    raise InvalidCryptoBackendError
-
-if keyLength < 32:
-    warn('Crypto implementation only supports key lengths up to %d bits. '
-         'Generated session cookies may be incompatible with other '
-         'environments' % (keyLength * 8))
-
-def generateCryptoKeys(master_key, salt, iterations):
-    # NB: We XOR parts of the keystream into the randomly-generated parts, just
-    # in case os.urandom() isn't as random as it should be.  Note that if
-    # os.urandom() returns truly random data, this will have no effect on the
-    # overall security.
-    keystream = PBKDF2(master_key, salt, iterations=iterations)
-    cipher_key = keystream.read(keyLength)
-    return cipher_key

+ 0 - 28
desktop/core/ext-py/Beaker/beaker/crypto/jcecrypto.py

@@ -1,28 +0,0 @@
-"""
-Encryption module that uses the Java Cryptography Extensions (JCE).
-
-Note that in default installations of the Java Runtime Environment, the
-maximum key length is limited to 128 bits due to US export
-restrictions. This makes the generated keys incompatible with the ones
-generated by pycryptopp, which has no such restrictions. To fix this,
-download the "Unlimited Strength Jurisdiction Policy Files" from Sun,
-which will allow encryption using 256 bit AES keys.
-"""
-from javax.crypto import Cipher
-from javax.crypto.spec import SecretKeySpec, IvParameterSpec
-
-import jarray
-
-# Initialization vector filled with zeros
-_iv = IvParameterSpec(jarray.zeros(16, 'b'))
-
-def aesEncrypt(data, key):
-    cipher = Cipher.getInstance('AES/CTR/NoPadding')
-    skeySpec = SecretKeySpec(key, 'AES')
-    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, _iv)
-    return cipher.doFinal(data).tostring()
-
-
-def getKeyLength():
-    maxlen = Cipher.getMaxAllowedKeyLength('AES/CTR/NoPadding')
-    return min(maxlen, 256) / 8

+ 0 - 358
desktop/core/ext-py/Beaker/beaker/crypto/pbkdf2.py

@@ -1,358 +0,0 @@
-#!/usr/bin/python
-# -*- coding: ascii -*-
-###########################################################################
-# PBKDF2.py - PKCS#5 v2.0 Password-Based Key Derivation
-#
-# Copyright (C) 2007 Dwayne C. Litzenberger <dlitz@dlitz.net>
-# All rights reserved.
-# 
-# Permission to use, copy, modify, and distribute this software and its
-# documentation for any purpose and without fee is hereby granted,
-# provided that the above copyright notice appear in all copies and that
-# both that copyright notice and this permission notice appear in
-# supporting documentation.
-# 
-# THE AUTHOR PROVIDES THIS SOFTWARE ``AS IS'' AND ANY EXPRESSED OR 
-# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
-# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  
-# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 
-# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
-# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# Country of origin: Canada
-#
-###########################################################################
-# Sample PBKDF2 usage:
-#   from Crypto.Cipher import AES
-#   from PBKDF2 import PBKDF2
-#   import os
-#
-#   salt = os.urandom(8)    # 64-bit salt
-#   key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
-#   iv = os.urandom(16)     # 128-bit IV
-#   cipher = AES.new(key, AES.MODE_CBC, iv)
-#     ...
-#
-# Sample crypt() usage:
-#   from PBKDF2 import crypt
-#   pwhash = crypt("secret")
-#   alleged_pw = raw_input("Enter password: ")
-#   if pwhash == crypt(alleged_pw, pwhash):
-#       print "Password good"
-#   else:
-#       print "Invalid password"
-#
-###########################################################################
-# History:
-#
-#  2007-07-27 Dwayne C. Litzenberger <dlitz@dlitz.net>
-#   - Initial Release (v1.0)
-#
-#  2007-07-31 Dwayne C. Litzenberger <dlitz@dlitz.net>
-#   - Bugfix release (v1.1)
-#   - SECURITY: The PyCrypto XOR cipher (used, if available, in the _strxor
-#   function in the previous release) silently truncates all keys to 64
-#   bytes.  The way it was used in the previous release, this would only be
-#   problem if the pseudorandom function that returned values larger than
-#   64 bytes (so SHA1, SHA256 and SHA512 are fine), but I don't like
-#   anything that silently reduces the security margin from what is
-#   expected.
-#
-###########################################################################
-
-__version__ = "1.1"
-
-from struct import pack
-from binascii import b2a_hex
-from random import randint
-
-from beaker.util import b64encode
-
-try:
-    # Use PyCrypto (if available)
-    from Crypto.Hash import HMAC, SHA as SHA1
-
-except ImportError:
-    # PyCrypto not available.  Use the Python standard library.
-    import hmac as HMAC
-    import sys
-    # When using the stdlib, we have to make sure the hmac version and sha
-    # version are compatible
-    if sys.version_info[0:2] <= (2,4):
-        # hmac in python2.4 or less require the sha module
-        import sha as SHA1
-    else:
-        # NOTE: We have to use the callable with hashlib (hashlib.sha1),
-        # otherwise hmac only accepts the sha module object itself
-        from hashlib import sha1 as SHA1
-
-def strxor(a, b):
-    return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
-
-class PBKDF2(object):
-    """PBKDF2.py : PKCS#5 v2.0 Password-Based Key Derivation
-    
-    This implementation takes a passphrase and a salt (and optionally an
-    iteration count, a digest module, and a MAC module) and provides a
-    file-like object from which an arbitrarily-sized key can be read.
-
-    If the passphrase and/or salt are unicode objects, they are encoded as
-    UTF-8 before they are processed.
-
-    The idea behind PBKDF2 is to derive a cryptographic key from a
-    passphrase and a salt.
-    
-    PBKDF2 may also be used as a strong salted password hash.  The
-    'crypt' function is provided for that purpose.
-    
-    Remember: Keys generated using PBKDF2 are only as strong as the
-    passphrases they are derived from.
-    """
-
-    def __init__(self, passphrase, salt, iterations=1000,
-                 digestmodule=SHA1, macmodule=HMAC):
-        if not callable(macmodule):
-            macmodule = macmodule.new
-        self.__macmodule = macmodule
-        self.__digestmodule = digestmodule
-        self._setup(passphrase, salt, iterations, self._pseudorandom)
-
-    def _pseudorandom(self, key, msg):
-        """Pseudorandom function.  e.g. HMAC-SHA1"""
-        return self.__macmodule(key=key, msg=msg,
-            digestmod=self.__digestmodule).digest()
-    
-    def read(self, bytes):
-        """Read the specified number of key bytes."""
-        if self.closed:
-            raise ValueError("file-like object is closed")
-
-        size = len(self.__buf)
-        blocks = [self.__buf]
-        i = self.__blockNum
-        while size < bytes:
-            i += 1
-            if i > 0xffffffff:
-                # We could return "" here, but 
-                raise OverflowError("derived key too long")
-            block = self.__f(i)
-            blocks.append(block)
-            size += len(block)
-        buf = "".join(blocks)
-        retval = buf[:bytes]
-        self.__buf = buf[bytes:]
-        self.__blockNum = i
-        return retval
-    
-    def __f(self, i):
-        # i must fit within 32 bits
-        assert (1 <= i and i <= 0xffffffff)
-        U = self.__prf(self.__passphrase, self.__salt + pack("!L", i))
-        result = U
-        for j in xrange(2, 1+self.__iterations):
-            U = self.__prf(self.__passphrase, U)
-            result = strxor(result, U)
-        return result
-    
-    def hexread(self, octets):
-        """Read the specified number of octets. Return them as hexadecimal.
-
-        Note that len(obj.hexread(n)) == 2*n.
-        """
-        return b2a_hex(self.read(octets))
-
-    def _setup(self, passphrase, salt, iterations, prf):
-        # Sanity checks:
-        
-        # passphrase and salt must be str or unicode (in the latter
-        # case, we convert to UTF-8)
-        if isinstance(passphrase, unicode):
-            passphrase = passphrase.encode("UTF-8")
-        if not isinstance(passphrase, str):
-            raise TypeError("passphrase must be str or unicode")
-        if isinstance(salt, unicode):
-            salt = salt.encode("UTF-8")
-        if not isinstance(salt, str):
-            raise TypeError("salt must be str or unicode")
-
-        # iterations must be an integer >= 1
-        if not isinstance(iterations, (int, long)):
-            raise TypeError("iterations must be an integer")
-        if iterations < 1:
-            raise ValueError("iterations must be at least 1")
-        
-        # prf must be callable
-        if not callable(prf):
-            raise TypeError("prf must be callable")
-
-        self.__passphrase = passphrase
-        self.__salt = salt
-        self.__iterations = iterations
-        self.__prf = prf
-        self.__blockNum = 0
-        self.__buf = ""
-        self.closed = False
-    
-    def close(self):
-        """Close the stream."""
-        if not self.closed:
-            del self.__passphrase
-            del self.__salt
-            del self.__iterations
-            del self.__prf
-            del self.__blockNum
-            del self.__buf
-            self.closed = True
-
-def crypt(word, salt=None, iterations=None):
-    """PBKDF2-based unix crypt(3) replacement.
-    
-    The number of iterations specified in the salt overrides the 'iterations'
-    parameter.
-
-    The effective hash length is 192 bits.
-    """
-    
-    # Generate a (pseudo-)random salt if the user hasn't provided one.
-    if salt is None:
-        salt = _makesalt()
-
-    # salt must be a string or the us-ascii subset of unicode
-    if isinstance(salt, unicode):
-        salt = salt.encode("us-ascii")
-    if not isinstance(salt, str):
-        raise TypeError("salt must be a string")
-
-    # word must be a string or unicode (in the latter case, we convert to UTF-8)
-    if isinstance(word, unicode):
-        word = word.encode("UTF-8")
-    if not isinstance(word, str):
-        raise TypeError("word must be a string or unicode")
-
-    # Try to extract the real salt and iteration count from the salt
-    if salt.startswith("$p5k2$"):
-        (iterations, salt, dummy) = salt.split("$")[2:5]
-        if iterations == "":
-            iterations = 400
-        else:
-            converted = int(iterations, 16)
-            if iterations != "%x" % converted:  # lowercase hex, minimum digits
-                raise ValueError("Invalid salt")
-            iterations = converted
-            if not (iterations >= 1):
-                raise ValueError("Invalid salt")
-    
-    # Make sure the salt matches the allowed character set
-    allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"
-    for ch in salt:
-        if ch not in allowed:
-            raise ValueError("Illegal character %r in salt" % (ch,))
-
-    if iterations is None or iterations == 400:
-        iterations = 400
-        salt = "$p5k2$$" + salt
-    else:
-        salt = "$p5k2$%x$%s" % (iterations, salt)
-    rawhash = PBKDF2(word, salt, iterations).read(24)
-    return salt + "$" + b64encode(rawhash, "./")
-
-# Add crypt as a static method of the PBKDF2 class
-# This makes it easier to do "from PBKDF2 import PBKDF2" and still use
-# crypt.
-PBKDF2.crypt = staticmethod(crypt)
-
-def _makesalt():
-    """Return a 48-bit pseudorandom salt for crypt().
-    
-    This function is not suitable for generating cryptographic secrets.
-    """
-    binarysalt = "".join([pack("@H", randint(0, 0xffff)) for i in range(3)])
-    return b64encode(binarysalt, "./")
-
-def test_pbkdf2():
-    """Module self-test"""
-    from binascii import a2b_hex
-    
-    #
-    # Test vectors from RFC 3962
-    #
-
-    # Test 1
-    result = PBKDF2("password", "ATHENA.MIT.EDUraeburn", 1).read(16)
-    expected = a2b_hex("cdedb5281bb2f801565a1122b2563515")
-    if result != expected:
-        raise RuntimeError("self-test failed")
-
-    # Test 2
-    result = PBKDF2("password", "ATHENA.MIT.EDUraeburn", 1200).hexread(32)
-    expected = ("5c08eb61fdf71e4e4ec3cf6ba1f5512b"
-                "a7e52ddbc5e5142f708a31e2e62b1e13")
-    if result != expected:
-        raise RuntimeError("self-test failed")
-
-    # Test 3
-    result = PBKDF2("X"*64, "pass phrase equals block size", 1200).hexread(32)
-    expected = ("139c30c0966bc32ba55fdbf212530ac9"
-                "c5ec59f1a452f5cc9ad940fea0598ed1")
-    if result != expected:
-        raise RuntimeError("self-test failed")
-    
-    # Test 4
-    result = PBKDF2("X"*65, "pass phrase exceeds block size", 1200).hexread(32)
-    expected = ("9ccad6d468770cd51b10e6a68721be61"
-                "1a8b4d282601db3b36be9246915ec82a")
-    if result != expected:
-        raise RuntimeError("self-test failed")
-    
-    #
-    # Other test vectors
-    #
-    
-    # Chunked read
-    f = PBKDF2("kickstart", "workbench", 256)
-    result = f.read(17)
-    result += f.read(17)
-    result += f.read(1)
-    result += f.read(2)
-    result += f.read(3)
-    expected = PBKDF2("kickstart", "workbench", 256).read(40)
-    if result != expected:
-        raise RuntimeError("self-test failed")
-    
-    #
-    # crypt() test vectors
-    #
-
-    # crypt 1
-    result = crypt("cloadm", "exec")
-    expected = '$p5k2$$exec$r1EWMCMk7Rlv3L/RNcFXviDefYa0hlql'
-    if result != expected:
-        raise RuntimeError("self-test failed")
-    
-    # crypt 2
-    result = crypt("gnu", '$p5k2$c$u9HvcT4d$.....')
-    expected = '$p5k2$c$u9HvcT4d$Sd1gwSVCLZYAuqZ25piRnbBEoAesaa/g'
-    if result != expected:
-        raise RuntimeError("self-test failed")
-
-    # crypt 3
-    result = crypt("dcl", "tUsch7fU", iterations=13)
-    expected = "$p5k2$d$tUsch7fU$nqDkaxMDOFBeJsTSfABsyn.PYUXilHwL"
-    if result != expected:
-        raise RuntimeError("self-test failed")
-    
-    # crypt 4 (unicode)
-    result = crypt(u'\u0399\u03c9\u03b1\u03bd\u03bd\u03b7\u03c2',
-        '$p5k2$$KosHgqNo$9mjN8gqjt02hDoP0c2J0ABtLIwtot8cQ')
-    expected = '$p5k2$$KosHgqNo$9mjN8gqjt02hDoP0c2J0ABtLIwtot8cQ'
-    if result != expected:
-        raise RuntimeError("self-test failed")
-
-if __name__ == '__main__':
-    test_pbkdf2()
-
-# vim:set ts=4 sw=4 sts=4 expandtab:

+ 0 - 12
desktop/core/ext-py/Beaker/beaker/crypto/pycrypto.py

@@ -1,12 +0,0 @@
-"""
-Encryption module that uses pycryptopp.
-"""
-from pycryptopp.cipher import aes
-
-def aesEncrypt(data, key):
-    cipher = aes.AES(key)
-    return cipher.process(data)
-
-
-def getKeyLength():
-    return 32

+ 0 - 27
desktop/core/ext-py/Beaker/beaker/exceptions.py

@@ -1,27 +0,0 @@
-"""Beaker exception classes"""
-
-class BeakerException(Exception):
-    pass
-
-
-class CreationAbortedError(Exception):
-    """Deprecated."""
-
-
-class InvalidCacheBackendError(BeakerException, ImportError):
-    pass
-
-
-class MissingCacheParameter(BeakerException):
-    pass
-
-
-class LockError(BeakerException):
-    pass
-
-
-class InvalidCryptoBackendError(BeakerException, ImportError):
-
-    def __init__(self):
-        Exception.__init__(self,
-                           'No supported crypto implementation was found')

+ 0 - 0
desktop/core/ext-py/Beaker/beaker/ext/__init__.py


+ 0 - 167
desktop/core/ext-py/Beaker/beaker/ext/database.py

@@ -1,167 +0,0 @@
-import cPickle
-import logging
-import pickle
-from datetime import datetime
-
-from beaker.container import OpenResourceNamespaceManager, Container
-from beaker.exceptions import InvalidCacheBackendError, MissingCacheParameter
-from beaker.synchronization import file_synchronizer, null_synchronizer
-from beaker.util import verify_directory, SyncDict
-
-sa_version = None
-
-log = logging.getLogger(__name__)
-
-try:
-    import sqlalchemy as sa
-    import sqlalchemy.pool as pool
-    from sqlalchemy import types
-    sa_version = '0.3'
-except ImportError:
-    raise InvalidCacheBackendError("Database cache backend requires the 'sqlalchemy' library")
-
-if not hasattr(sa, 'BoundMetaData'):
-    sa_version = '0.4'
-
-class DatabaseNamespaceManager(OpenResourceNamespaceManager):
-    metadatas = SyncDict()
-    tables = SyncDict()
-    
-    def __init__(self, namespace, url=None, sa_opts=None, optimistic=False,
-                 table_name='beaker_cache', data_dir=None, lock_dir=None,
-                 **params):
-        """Creates a database namespace manager
-        
-        ``url``
-            SQLAlchemy compliant db url
-        ``sa_opts``
-            A dictionary of SQLAlchemy keyword options to initialize the engine
-            with.
-        ``optimistic``
-            Use optimistic session locking, note that this will result in an
-            additional select when updating a cache value to compare version
-            numbers.
-        ``table_name``
-            The table name to use in the database for the cache.
-        """
-        OpenResourceNamespaceManager.__init__(self, namespace)
-        
-        if sa_opts is None:
-            sa_opts = params
-
-        if lock_dir:
-            self.lock_dir = lock_dir
-        elif data_dir:
-            self.lock_dir = data_dir + "/container_db_lock"
-        if self.lock_dir:
-            verify_directory(self.lock_dir)            
-        
-        # Check to see if the table's been created before
-        url = url or sa_opts['sa.url']
-        table_key = url + table_name
-        def make_cache():
-            # Check to see if we have a connection pool open already
-            meta_key = url + table_name
-            def make_meta():
-                if sa_version == '0.3':
-                    if url.startswith('mysql') and not sa_opts:
-                        sa_opts['poolclass'] = pool.QueuePool
-                    engine = sa.create_engine(url, **sa_opts)
-                    meta = sa.BoundMetaData(engine)
-                else:
-                    # SQLAlchemy pops the url, this ensures it sticks around
-                    # later
-                    sa_opts['sa.url'] = url
-                    engine = sa.engine_from_config(sa_opts, 'sa.')
-                    meta = sa.MetaData()
-                    meta.bind = engine
-                return meta
-            meta = DatabaseNamespaceManager.metadatas.get(meta_key, make_meta)
-            # Create the table object and cache it now
-            cache = sa.Table(table_name, meta,
-                             sa.Column('id', types.Integer, primary_key=True),
-                             sa.Column('namespace', types.String(255), nullable=False),
-                             sa.Column('accessed', types.DateTime, nullable=False),
-                             sa.Column('created', types.DateTime, nullable=False),
-                             sa.Column('data', types.PickleType, nullable=False),
-                             sa.UniqueConstraint('namespace')
-            )
-            cache.create(checkfirst=True)
-            return cache
-        self.hash = {}
-        self._is_new = False
-        self.loaded = False
-        self.cache = DatabaseNamespaceManager.tables.get(table_key, make_cache)
-    
-    def get_access_lock(self):
-        return null_synchronizer()
-
-    def get_creation_lock(self, key):
-        return file_synchronizer(
-            identifier ="databasecontainer/funclock/%s" % self.namespace,
-            lock_dir = self.lock_dir)
-
-    def do_open(self, flags):
-        # If we already loaded the data, don't bother loading it again
-        if self.loaded:
-            self.flags = flags
-            return
-        
-        cache = self.cache
-        result = sa.select([cache.c.data], 
-                           cache.c.namespace==self.namespace
-                          ).execute().fetchone()
-        if not result:
-            self._is_new = True
-            self.hash = {}
-        else:
-            self._is_new = False
-            try:
-                self.hash = result['data']
-            except (IOError, OSError, EOFError, cPickle.PickleError,
-                    pickle.PickleError):
-                log.debug("Couln't load pickle data, creating new storage")
-                self.hash = {}
-                self._is_new = True
-        self.flags = flags
-        self.loaded = True
-    
-    def do_close(self):
-        if self.flags is not None and (self.flags == 'c' or self.flags == 'w'):
-            cache = self.cache
-            if self._is_new:
-                cache.insert().execute(namespace=self.namespace, data=self.hash,
-                                       accessed=datetime.now(),
-                                       created=datetime.now())
-                self._is_new = False
-            else:
-                cache.update(cache.c.namespace==self.namespace).execute(
-                    data=self.hash, accessed=datetime.now())
-        self.flags = None
-    
-    def do_remove(self):
-        cache = self.cache
-        cache.delete(cache.c.namespace==self.namespace).execute()
-        self.hash = {}
-        
-        # We can retain the fact that we did a load attempt, but since the
-        # file is gone this will be a new namespace should it be saved.
-        self._is_new = True
-
-    def __getitem__(self, key): 
-        return self.hash[key]
-
-    def __contains__(self, key): 
-        return self.hash.has_key(key)
-        
-    def __setitem__(self, key, value):
-        self.hash[key] = value
-
-    def __delitem__(self, key):
-        del self.hash[key]
-
-    def keys(self):
-        return self.hash.keys()
-
-class DatabaseContainer(Container):
-    namespace_manager = DatabaseNamespaceManager

+ 0 - 115
desktop/core/ext-py/Beaker/beaker/ext/google.py

@@ -1,115 +0,0 @@
-from __future__ import absolute_import
-import cPickle
-import logging
-from datetime import datetime
-
-from beaker.container import OpenResourceNamespaceManager, Container
-from beaker.exceptions import InvalidCacheBackendError
-from beaker.synchronization import null_synchronizer
-
-log = logging.getLogger(__name__)
-
-try:
-    from google.appengine.ext import db
-except ImportError:
-    raise InvalidCacheBackendError("Datastore cache backend requires the "
-                                   "'google.appengine.ext' library")
-
-
-class GoogleNamespaceManager(OpenResourceNamespaceManager):
-    tables = {}
-    
-    def __init__(self, namespace, table_name='beaker_cache', **params):
-        """Creates a datastore namespace manager"""
-        OpenResourceNamespaceManager.__init__(self, namespace)
-        
-        def make_cache():
-            table_dict = dict(created=db.DateTimeProperty(),
-                              accessed=db.DateTimeProperty(),
-                              data=db.BlobProperty())
-            table = type(table_name, (db.Model,), table_dict)
-            return table
-        self.table_name = table_name
-        self.cache = GoogleNamespaceManager.tables.setdefault(table_name, make_cache())
-        self.hash = {}
-        self._is_new = False
-        self.loaded = False
-        self.log_debug = logging.DEBUG >= log.getEffectiveLevel()
-        
-        # Google wants namespaces to start with letters, change the namespace
-        # to start with a letter
-        self.namespace = 'p%s' % self.namespace
-    
-    def get_access_lock(self):
-        return null_synchronizer()
-
-    def get_creation_lock(self, key):
-        # this is weird, should probably be present
-        return null_synchronizer()
-
-    def do_open(self, flags):
-        # If we already loaded the data, don't bother loading it again
-        if self.loaded:
-            self.flags = flags
-            return
-        
-        item = self.cache.get_by_key_name(self.namespace)
-        
-        if not item:
-            self._is_new = True
-            self.hash = {}
-        else:
-            self._is_new = False
-            try:
-                self.hash = cPickle.loads(str(item.data))
-            except (IOError, OSError, EOFError, cPickle.PickleError):
-                if self.log_debug:
-                    log.debug("Couln't load pickle data, creating new storage")
-                self.hash = {}
-                self._is_new = True
-        self.flags = flags
-        self.loaded = True
-    
-    def do_close(self):
-        if self.flags is not None and (self.flags == 'c' or self.flags == 'w'):
-            if self._is_new:
-                item = self.cache(key_name=self.namespace)
-                item.data = cPickle.dumps(self.hash)
-                item.created = datetime.now()
-                item.accessed = datetime.now()
-                item.put()
-                self._is_new = False
-            else:
-                item = self.cache.get_by_key_name(self.namespace)
-                item.data = cPickle.dumps(self.hash)
-                item.accessed = datetime.now()
-                item.put()
-        self.flags = None
-    
-    def do_remove(self):
-        item = self.cache.get_by_key_name(self.namespace)
-        item.delete()
-        self.hash = {}
-        
-        # We can retain the fact that we did a load attempt, but since the
-        # file is gone this will be a new namespace should it be saved.
-        self._is_new = True
-
-    def __getitem__(self, key):
-        return self.hash[key]
-
-    def __contains__(self, key): 
-        return self.hash.has_key(key)
-        
-    def __setitem__(self, key, value):
-        self.hash[key] = value
-
-    def __delitem__(self, key):
-        del self.hash[key]
-
-    def keys(self):
-        return self.hash.keys()
-        
-
-class GoogleContainer(Container):
-    namespace_class = GoogleNamespaceManager

+ 0 - 69
desktop/core/ext-py/Beaker/beaker/ext/memcached.py

@@ -1,69 +0,0 @@
-from beaker.container import NamespaceManager, Container
-from beaker.exceptions import InvalidCacheBackendError, MissingCacheParameter
-from beaker.synchronization import file_synchronizer, null_synchronizer
-from beaker.util import verify_directory, SyncDict
-
-try:
-    import cmemcache as memcache
-except ImportError:
-    try:
-        import memcache
-    except ImportError:
-        raise InvalidCacheBackendError("Memcached cache backend requires either the 'memcache' or 'cmemcache' library")
-
-class MemcachedNamespaceManager(NamespaceManager):
-    clients = SyncDict()
-    
-    def __init__(self, namespace, url=None, data_dir=None, lock_dir=None, **params):
-        NamespaceManager.__init__(self, namespace)
-       
-        if not url:
-            raise MissingCacheParameter("url is required") 
-        
-        if lock_dir:
-            self.lock_dir = lock_dir
-        elif data_dir:
-            self.lock_dir = data_dir + "/container_mcd_lock"
-        if self.lock_dir:
-            verify_directory(self.lock_dir)            
-        
-        self.mc = MemcachedNamespaceManager.clients.get(url, 
-            memcache.Client, url.split(';'), debug=0)
-
-    def get_creation_lock(self, key):
-        return file_synchronizer(
-            identifier="memcachedcontainer/funclock/%s" % self.namespace,lock_dir = self.lock_dir)
-
-    def _format_key(self, key):
-        return self.namespace + '_' + key.replace(' ', '\302\267')
-
-    def __getitem__(self, key):
-        return self.mc.get(self._format_key(key))
-
-    def __contains__(self, key):
-        value = self.mc.get(self._format_key(key))
-        return value is not None
-
-    def has_key(self, key):
-        return key in self
-
-    def set_value(self, key, value, expiretime=None):
-        if expiretime:
-            self.mc.set(self._format_key(key), value, time=expiretime)
-        else:
-            self.mc.set(self._format_key(key), value)
-
-    def __setitem__(self, key, value):
-        self.set_value(key, value)
-        
-    def __delitem__(self, key):
-        self.mc.delete(self._format_key(key))
-
-    def do_remove(self):
-        self.mc.flush_all()
-    
-    def keys(self):
-        raise NotImplementedError("Memcache caching does not support iteration of all cache keys")
-
-class MemcachedContainer(Container):
-    namespace_class = MemcachedNamespaceManager

+ 0 - 124
desktop/core/ext-py/Beaker/beaker/ext/sqla.py

@@ -1,124 +0,0 @@
-import cPickle
-import logging
-import pickle
-from datetime import datetime
-
-from beaker.container import OpenResourceNamespaceManager, Container
-from beaker.exceptions import InvalidCacheBackendError, MissingCacheParameter
-from beaker.synchronization import file_synchronizer, null_synchronizer
-from beaker.util import verify_directory, SyncDict
-
-try:
-    import sqlalchemy as sa
-except ImportError:
-    raise InvalidCacheBackendError('SQLAlchemy, which is required by this backend, is not installed')
-
-log = logging.getLogger(__name__)
-
-class SqlaNamespaceManager(OpenResourceNamespaceManager):
-    binds = SyncDict()
-    tables = SyncDict()
-
-    def __init__(self, namespace, bind, table, data_dir=None, lock_dir=None,
-                 **kwargs):
-        """Create a namespace manager for use with a database table via
-        SQLAlchemy.
-
-        ``bind``
-            SQLAlchemy ``Engine`` or ``Connection`` object
-
-        ``table``
-            SQLAlchemy ``Table`` object in which to store namespace data.
-            This should usually be something created by ``make_cache_table``.
-        """
-        OpenResourceNamespaceManager.__init__(self, namespace)
-
-        if lock_dir:
-            self.lock_dir = lock_dir
-        elif data_dir:
-            self.lock_dir = data_dir + "/container_db_lock"
-        if self.lock_dir:
-            verify_directory(self.lock_dir)            
-
-        self.bind = self.__class__.binds.get(str(bind.url), lambda: bind)
-        self.table = self.__class__.tables.get('%s:%s' % (bind.url, table.name),
-                                               lambda: table)
-        self.hash = {}
-        self._is_new = False
-        self.loaded = False
-
-    def get_access_lock(self):
-        return null_synchronizer()
-
-    def get_creation_lock(self, key):
-        return file_synchronizer(
-            identifier ="databasecontainer/funclock/%s" % self.namespace,
-            lock_dir=self.lock_dir)
-
-    def do_open(self, flags):
-        if self.loaded:
-            self.flags = flags
-            return
-        select = sa.select([self.table.c.data],
-                           (self.table.c.namespace == self.namespace))
-        result = self.bind.execute(select).fetchone()
-        if not result:
-            self._is_new = True
-            self.hash = {}
-        else:
-            self._is_new = False
-            try:
-                self.hash = result['data']
-            except (IOError, OSError, EOFError, cPickle.PickleError,
-                    pickle.PickleError):
-                log.debug("Couln't load pickle data, creating new storage")
-                self.hash = {}
-                self._is_new = True
-        self.flags = flags
-        self.loaded = True
-
-    def do_close(self):
-        if self.flags is not None and (self.flags == 'c' or self.flags == 'w'):
-            if self._is_new:
-                insert = self.table.insert()
-                self.bind.execute(insert, namespace=self.namespace, data=self.hash,
-                                  accessed=datetime.now(), created=datetime.now())
-                self._is_new = False
-            else:
-                update = self.table.update(self.table.c.namespace == self.namespace)
-                self.bind.execute(update, data=self.hash, accessed=datetime.now())
-        self.flags = None
-
-    def do_remove(self):
-        delete = self.table.delete(self.table.c.namespace == self.namespace)
-        self.bind.execute(delete)
-        self.hash = {}
-        self._is_new = True
-
-    def __getitem__(self, key):
-        return self.hash[key]
-
-    def __contains__(self, key):
-        return self.hash.has_key(key)
-
-    def __setitem__(self, key, value):
-        self.hash[key] = value
-
-    def __delitem__(self, key):
-        del self.hash[key]
-
-    def keys(self):
-        return self.hash.keys()
-
-
-class SqlaContainer(Container):
-    namespace_manager = SqlaNamespaceManager
-
-def make_cache_table(metadata, table_name='beaker_cache'):
-    """Return a ``Table`` object suitable for storing cached values for the
-    namespace manager.  Do not create the table."""
-    return sa.Table(table_name, metadata,
-                    sa.Column('namespace', sa.String(255), primary_key=True),
-                    sa.Column('accessed', sa.DateTime, nullable=False),
-                    sa.Column('created', sa.DateTime, nullable=False),
-                    sa.Column('data', sa.PickleType, nullable=False))

+ 0 - 165
desktop/core/ext-py/Beaker/beaker/middleware.py

@@ -1,165 +0,0 @@
-import warnings
-
-try:
-    from paste.registry import StackedObjectProxy
-    beaker_session = StackedObjectProxy(name="Beaker Session")
-    beaker_cache = StackedObjectProxy(name="Cache Manager")
-except:
-    beaker_cache = None
-    beaker_session = None
-
-from beaker.cache import CacheManager
-from beaker.session import Session, SessionObject
-from beaker.util import coerce_cache_params, coerce_session_params, \
-    parse_cache_config_options
-
-
-class CacheMiddleware(object):
-    cache = beaker_cache
-    
-    def __init__(self, app, config=None, environ_key='beaker.cache', **kwargs):
-        """Initialize the Cache Middleware
-        
-        The Cache middleware will make a Cache instance available
-        every request under the ``environ['beaker.cache']`` key by
-        default. The location in environ can be changed by setting
-        ``environ_key``.
-        
-        ``config``
-            dict  All settings should be prefixed by 'cache.'. This
-            method of passing variables is intended for Paste and other
-            setups that accumulate multiple component settings in a
-            single dictionary. If config contains *no cache. prefixed
-            args*, then *all* of the config options will be used to
-            intialize the Cache objects.
-        
-        ``environ_key``
-            Location where the Cache instance will keyed in the WSGI
-            environ
-        
-        ``**kwargs``
-            All keyword arguments are assumed to be cache settings and
-            will override any settings found in ``config``
-
-        """
-        self.app = app
-        config = config or {}
-        
-        self.options = {}
-        
-        # Update the options with the parsed config
-        self.options.update(parse_cache_config_options(config))
-        
-        # Add any options from kwargs, but leave out the defaults this
-        # time
-        self.options.update(
-            parse_cache_config_options(kwargs, include_defaults=False))
-                
-        # Assume all keys are intended for cache if none are prefixed with
-        # 'cache.'
-        if not self.options and config:
-            self.options = config
-        
-        self.options.update(kwargs)
-        self.cache_manager = CacheManager(**self.options)
-        self.environ_key = environ_key
-    
-    def __call__(self, environ, start_response):
-        if environ.get('paste.registry'):
-            if environ['paste.registry'].reglist:
-                environ['paste.registry'].register(self.cache,
-                                                   self.cache_manager)
-        environ[self.environ_key] = self.cache_manager
-        return self.app(environ, start_response)
-
-
-class SessionMiddleware(object):
-    session = beaker_session
-    
-    def __init__(self, wrap_app, config=None, environ_key='beaker.session',
-                 **kwargs):
-        """Initialize the Session Middleware
-        
-        The Session middleware will make a lazy session instance
-        available every request under the ``environ['beaker.session']``
-        key by default. The location in environ can be changed by
-        setting ``environ_key``.
-        
-        ``config``
-            dict  All settings should be prefixed by 'session.'. This
-            method of passing variables is intended for Paste and other
-            setups that accumulate multiple component settings in a
-            single dictionary. If config contains *no cache. prefixed
-            args*, then *all* of the config options will be used to
-            intialize the Cache objects.
-        
-        ``environ_key``
-            Location where the Session instance will keyed in the WSGI
-            environ
-        
-        ``**kwargs``
-            All keyword arguments are assumed to be session settings and
-            will override any settings found in ``config``
-
-        """
-        config = config or {}
-        
-        # Load up the default params
-        self.options = dict(invalidate_corrupt=True, type=None, 
-                           data_dir=None, key='beaker.session.id', 
-                           timeout=None, secret=None, log_file=None)
-
-        # Pull out any config args meant for beaker session. if there are any
-        for dct in [config, kwargs]:
-            for key, val in dct.iteritems():
-                if key.startswith('beaker.session.'):
-                    self.options[key[15:]] = val
-                if key.startswith('session.'):
-                    self.options[key[8:]] = val
-                if key.startswith('session_'):
-                    warnings.warn('Session options should start with session. '
-                                  'instead of session_.', DeprecationWarning, 2)
-                    self.options[key[8:]] = val
-        
-        # Coerce and validate session params
-        coerce_session_params(self.options)
-        
-        # Assume all keys are intended for cache if none are prefixed with
-        # 'cache.'
-        if not self.options and config:
-            self.options = config
-        
-        self.options.update(kwargs)
-        self.wrap_app = wrap_app
-        self.environ_key = environ_key
-        
-    def __call__(self, environ, start_response):
-        session = SessionObject(environ, **self.options)
-        if environ.get('paste.registry'):
-            if environ['paste.registry'].reglist:
-                environ['paste.registry'].register(self.session, session)
-        environ[self.environ_key] = session
-        environ['beaker.get_session'] = self._get_session
-        
-        def session_start_response(status, headers, exc_info = None):
-            if session.accessed():
-                session.persist()
-                if session.__dict__['_headers']['set_cookie']:
-                    cookie = session.__dict__['_headers']['cookie_out']
-                    if cookie:
-                        headers.append(('Set-cookie', cookie))
-            return start_response(status, headers, exc_info)
-        return self.wrap_app(environ, session_start_response)
-    
-    def _get_session(self):
-        return Session({}, use_cookies=False, **self.options)
-
-
-def session_filter_factory(global_conf, **kwargs):
-    def filter(app):
-        return SessionMiddleware(app, global_conf, **kwargs)
-    return filter
-
-
-def session_filter_app_factory(app, global_conf, **kwargs):
-    return SessionMiddleware(app, global_conf, **kwargs)

+ 0 - 618
desktop/core/ext-py/Beaker/beaker/session.py

@@ -1,618 +0,0 @@
-import cPickle
-import Cookie
-import hmac
-import os
-import random
-import time
-from datetime import datetime, timedelta
-try:
-    from hashlib import md5
-except ImportError:
-    from md5 import md5
-try:
-    # Use PyCrypto (if available)
-    from Crypto.Hash import HMAC, SHA as SHA1
-
-except ImportError:
-    # PyCrypto not available.  Use the Python standard library.
-    import hmac as HMAC
-    import sys
-    # When using the stdlib, we have to make sure the hmac version and sha
-    # version are compatible
-    if sys.version_info[0:2] <= (2,4):
-        # hmac in python2.4 or less require the sha module
-        import sha as SHA1
-    else:
-        # NOTE: We have to use the callable with hashlib (hashlib.sha1),
-        # otherwise hmac only accepts the sha module object itself
-        from hashlib import sha1 as SHA1
-
-# Check for pycryptopp encryption for AES
-try:
-    from beaker.crypto import generateCryptoKeys, aesEncrypt
-    crypto_ok = True
-except:
-    crypto_ok = False
-
-from beaker.cache import clsmap
-from beaker.exceptions import BeakerException
-from beaker.util import b64decode, b64encode, Set
-
-__all__ = ['SignedCookie', 'Session']
-
-getpid = hasattr(os, 'getpid') and os.getpid or (lambda : '')
-
-class SignedCookie(Cookie.BaseCookie):
-    """Extends python cookie to give digital signature support"""
-    def __init__(self, secret, input=None):
-        self.secret = secret
-        Cookie.BaseCookie.__init__(self, input)
-    
-    def value_decode(self, val):
-        val = val.strip('"')
-        sig = HMAC.new(self.secret, val[40:], SHA1).hexdigest()
-        if sig != val[:40]:
-            return None, val
-        else:
-            return val[40:], val
-    
-    def value_encode(self, val):
-        sig = HMAC.new(self.secret, val, SHA1).hexdigest()
-        return str(val), ("%s%s" % (sig, val))
-
-
-class Session(dict):
-    """Session object that uses container package for storage"""
-    def __init__(self, request, id=None, invalidate_corrupt=False,
-                 use_cookies=True, type=None, data_dir=None,
-                 key='beaker.session.id', timeout=None, cookie_expires=True,
-                 cookie_domain=None, secret=None, secure=False,
-                 namespace_class=None, **namespace_args):
-        if not type:
-            if data_dir:
-                self.type = 'file'
-            else:
-                self.type = 'memory'
-        else:
-            self.type = type
-
-        self.namespace_class = namespace_class or clsmap[self.type]
-
-        self.namespace_args = namespace_args
-        
-        self.request = request
-        self.data_dir = data_dir
-        self.key = key
-        
-        self.timeout = timeout
-        self.use_cookies = use_cookies
-        self.cookie_expires = cookie_expires
-        
-        # Default cookie domain/path
-        self._domain = cookie_domain
-        self._path = '/'
-        self.was_invalidated = False
-        self.secret = secret
-        self.secure = secure
-        self.id = id
-        self.accessed_dict = {}
-        
-        if self.use_cookies:
-            cookieheader = request.get('cookie', '')
-            if secret:
-                try:
-                    self.cookie = SignedCookie(secret, input=cookieheader)
-                except Cookie.CookieError:
-                    self.cookie = SignedCookie(secret, input=None)
-            else:
-                self.cookie = Cookie.SimpleCookie(input=cookieheader)
-            
-            if not self.id and self.key in self.cookie:
-                self.id = self.cookie[self.key].value
-        
-        self.is_new = self.id is None
-        if self.is_new:
-            self._create_id()
-            self['_accessed_time'] = self['_creation_time'] = time.time()
-        else:
-            try:
-                self.load()
-            except:
-                if invalidate_corrupt:
-                    self.invalidate()
-                else:
-                    raise
-        
-    def _create_id(self):
-        self.id = md5(
-            md5("%f%s%f%s" % (time.time(), id({}), random.random(),
-                              getpid())).hexdigest(), 
-        ).hexdigest()
-        self.is_new = True
-        self.last_accessed = None
-        if self.use_cookies:
-            self.cookie[self.key] = self.id
-            if self._domain:
-                self.cookie[self.key]['domain'] = self._domain
-            if self.secure:
-                self.cookie[self.key]['secure'] = True
-            self.cookie[self.key]['path'] = self._path
-            if self.cookie_expires is not True:
-                if self.cookie_expires is False:
-                    expires = datetime.fromtimestamp( 0x7FFFFFFF )
-                elif isinstance(self.cookie_expires, timedelta):
-                    expires = datetime.today() + self.cookie_expires
-                elif isinstance(self.cookie_expires, datetime):
-                    expires = self.cookie_expires
-                else:
-                    raise ValueError("Invalid argument for cookie_expires: %s"
-                                     % repr(self.cookie_expires))
-                self.cookie[self.key]['expires'] = \
-                    expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT" )
-            self.request['cookie_out'] = self.cookie[self.key].output(header='')
-            self.request['set_cookie'] = False
-    
-    def created(self):
-        return self['_creation_time']
-    created = property(created)
-    
-    def _set_domain(self, domain):
-        self['_domain'] = domain
-        self.cookie[self.key]['domain'] = domain
-        self.request['cookie_out'] = self.cookie[self.key].output(header='')
-        self.request['set_cookie'] = True
-    
-    def _get_domain(self, domain):
-        return self._domain
-    
-    domain = property(_get_domain, _set_domain)
-    
-    def _set_path(self, path):
-        self['_path'] = path
-        self.cookie[self.key]['path'] = path
-        self.request['cookie_out'] = self.cookie[self.key].output(header='')
-        self.request['set_cookie'] = True
-    
-    def _get_path(self, domain):
-        return self._path
-    
-    path = property(_get_path, _set_path)
-
-    def _delete_cookie(self):
-        self.request['set_cookie'] = True
-        self.cookie[self.key] = self.id
-        if self._domain:
-            self.cookie[self.key]['domain'] = self._domain
-        if self.secure:
-            self.cookie[self.key]['secure'] = True
-        self.cookie[self.key]['path'] = '/'
-        expires = datetime.today().replace(year=2003)
-        self.cookie[self.key]['expires'] = \
-            expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT" )
-        self.request['cookie_out'] = self.cookie[self.key].output(header='')
-        self.request['set_cookie'] = True
-
-    def delete(self):
-        """Deletes the session from the persistent storage, and sends
-        an expired cookie out"""
-        if self.use_cookies:
-            self._delete_cookie()
-        self.clear()
-
-    def invalidate(self):
-        """Invalidates this session, creates a new session id, returns
-        to the is_new state"""
-        self.clear()
-        self.was_invalidated = True
-        self._create_id()
-        self.load()
-    
-    def load(self):
-        "Loads the data from this session from persistent storage"
-        self.namespace = self.namespace_class(self.id,
-            data_dir=self.data_dir, digest_filenames=False,
-            **self.namespace_args)
-        now = time.time()
-        self.request['set_cookie'] = True
-        
-        self.namespace.acquire_read_lock()
-        timed_out = False
-        try:
-            self.clear()
-            try:
-                session_data = self.namespace['session']
-
-                # Memcached always returns a key, its None when its not
-                # present
-                if session_data is None:
-                    session_data = {
-                        '_creation_time':now,
-                        '_accessed_time':now
-                    }
-                    self.is_new = True
-            except (KeyError, TypeError):
-                session_data = {
-                    '_creation_time':now,
-                    '_accessed_time':now
-                }
-                self.is_new = True
-            
-            if self.timeout is not None and \
-               now - session_data['_accessed_time'] > self.timeout:
-                timed_out= True
-            else:
-                # Properly set the last_accessed time, which is different
-                # than the *currently* _accessed_time
-                if self.is_new or '_accessed_time' not in session_data:
-                    self.last_accessed = None
-                else:
-                    self.last_accessed = session_data['_accessed_time']
-                
-                # Update the current _accessed_time
-                session_data['_accessed_time'] = now
-                self.update(session_data)
-                self.accessed_dict = session_data.copy()                
-        finally:
-            self.namespace.release_read_lock()
-        if timed_out:
-            self.invalidate()
-    
-    def save(self, accessed_only=False):
-        """Saves the data for this session to persistent storage
-        
-        If accessed_only is True, then only the original data loaded
-        at the beginning of the request will be saved, with the updated
-        last accessed time.
-        
-        """
-        # Look to see if its a new session that was only accessed
-        # Don't save it under that case
-        if accessed_only and self.is_new:
-            return None
-        
-        if not hasattr(self, 'namespace'):
-            self.namespace = self.namespace_class(
-                                    self.id, 
-                                    data_dir=self.data_dir,
-                                    digest_filenames=False, 
-                                    **self.namespace_args)
-        
-        self.namespace.acquire_write_lock()
-        try:
-            if accessed_only:
-                data = dict(self.accessed_dict.items())
-            else:
-                data = dict(self.items())
-            
-            # Save the data
-            if not data and 'session' in self.namespace:
-                del self.namespace['session']
-            else:
-                self.namespace['session'] = data
-        finally:
-            self.namespace.release_write_lock()
-        if self.is_new:
-            self.request['set_cookie'] = True
-    
-    def revert(self):
-        """Revert the session to its original state from its first
-        access in the request"""
-        self.clear()
-        self.update(self.accessed_dict)
-    
-    # TODO: I think both these methods should be removed.  They're from
-    # the original mod_python code i was ripping off but they really
-    # have no use here.
-    def lock(self):
-        """Locks this session against other processes/threads.  This is
-        automatic when load/save is called.
-        
-        ***use with caution*** and always with a corresponding 'unlock'
-        inside a "finally:" block, as a stray lock typically cannot be
-        unlocked without shutting down the whole application.
-
-        """
-        self.namespace.acquire_write_lock()
-
-    def unlock(self):
-        """Unlocks this session against other processes/threads.  This
-        is automatic when load/save is called.
-
-        ***use with caution*** and always within a "finally:" block, as
-        a stray lock typically cannot be unlocked without shutting down
-        the whole application.
-
-        """
-        self.namespace.release_write_lock()
-
-class CookieSession(Session):
-    """Pure cookie-based session
-    
-    Options recognized when using cookie-based sessions are slightly
-    more restricted than general sessions.
-    
-    ``key``
-        The name the cookie should be set to.
-    ``timeout``
-        How long session data is considered valid. This is used 
-        regardless of the cookie being present or not to determine
-        whether session data is still valid.
-    ``encrypt_key``
-        The key to use for the session encryption, if not provided the
-        session will not be encrypted.
-    ``validate_key``
-        The key used to sign the encrypted session
-    ``cookie_domain``
-        Domain to use for the cookie.
-    ``secure``
-        Whether or not the cookie should only be sent over SSL.
-    
-    """
-    def __init__(self, request, key='beaker.session.id', timeout=None,
-                 cookie_expires=True, cookie_domain=None, encrypt_key=None,
-                 validate_key=None, secure=False, **kwargs):
-        if not crypto_ok and encrypt_key:
-            raise BeakerException("pycryptopp is not installed, can't use "
-                                  "encrypted cookie-only Session.")
-        
-        self.request = request
-        self.key = key
-        self.timeout = timeout
-        self.cookie_expires = cookie_expires
-        self.encrypt_key = encrypt_key
-        self.validate_key = validate_key
-        self.request['set_cookie'] = False
-        self.secure = secure
-        self._domain = cookie_domain
-        self._path = '/'
-        
-        try:
-            cookieheader = request['cookie']
-        except KeyError:
-            cookieheader = ''
-        
-        if validate_key is None:
-            raise BeakerException("No validate_key specified for Cookie only "
-                                  "Session.")
-        
-        try:
-            self.cookie = SignedCookie(validate_key, input=cookieheader)
-        except Cookie.CookieError:
-            self.cookie = SignedCookie(validate_key, input=None)
-        
-        self['_id'] = self._make_id()
-        self.is_new = True
-        
-        # If we have a cookie, load it
-        if self.key in self.cookie and self.cookie[self.key].value is not None:
-            self.is_new = False
-            try:
-                self.update(self._decrypt_data())
-            except:
-                pass
-            if self.timeout is not None and time.time() - \
-               self['_accessed_time'] > self.timeout:
-                self.clear()
-            self.accessed_dict = self.copy()
-            self._create_cookie()
-    
-    def created(self):
-        return self['_creation_time']
-    created = property(created)
-    
-    def id(self):
-        return self['_id']
-    id = property(id)
-
-    def _set_domain(self, domain):
-        self['_domain'] = domain
-        self._domain = domain
-        
-    def _get_domain(self, domain):
-        return self._domain
-    
-    domain = property(_get_domain, _set_domain)
-    
-    def _set_path(self, path):
-        self['_path'] = path
-        self._path = path
-    
-    def _get_path(self, domain):
-        return self._path
-    
-    path = property(_get_path, _set_path)
-
-    def _encrypt_data(self):
-        """Serialize, encipher, and base64 the session dict"""
-        if self.encrypt_key:
-            nonce = b64encode(os.urandom(40))[:8]
-            encrypt_key = generateCryptoKeys(self.encrypt_key,
-                                             self.validate_key + nonce, 1)
-            data = cPickle.dumps(self.copy(), 2)
-            return nonce + b64encode(aesEncrypt(data, encrypt_key))
-        else:
-            data = cPickle.dumps(self.copy(), 2)
-            return b64encode(data)
-    
-    def _decrypt_data(self):
-        """Bas64, decipher, then un-serialize the data for the session
-        dict"""
-        if self.encrypt_key:
-            nonce = self.cookie[self.key].value[:8]
-            encrypt_key = generateCryptoKeys(self.encrypt_key,
-                                             self.validate_key + nonce, 1)
-            payload = b64decode(self.cookie[self.key].value[8:])
-            data = aesEncrypt(payload, encrypt_key)
-            return cPickle.loads(data)
-        else:
-            data = b64decode(self.cookie[self.key].value)
-            return cPickle.loads(data)
-    
-    def _make_id(self):
-        return md5(md5(
-            "%f%s%f%d" % (time.time(), id({}), random.random(), getpid())
-            ).hexdigest()
-        ).hexdigest()
-    
-    def save(self, accessed_only=False):
-        """Saves the data for this session to persistent storage"""
-        if accessed_only and self.is_new:
-            return
-        if accessed_only:
-            self.clear()
-            self.update(self.accessed_dict)
-        self._create_cookie()
-    
-    def expire(self):
-        """Delete the 'expires' attribute on this Session, if any."""
-        
-        self.pop('_expires', None)
-        
-    def _create_cookie(self):
-        if '_creation_time' not in self:
-            self['_creation_time'] = time.time()
-        if '_id' not in self:
-            self['_id'] = self._make_id()
-        self['_accessed_time'] = time.time()
-        
-        if self.cookie_expires is not True:
-            if self.cookie_expires is False:
-                expires = datetime.fromtimestamp( 0x7FFFFFFF )
-            elif isinstance(self.cookie_expires, timedelta):
-                expires = datetime.today() + self.cookie_expires
-            elif isinstance(self.cookie_expires, datetime):
-                expires = self.cookie_expires
-            else:
-                raise ValueError("Invalid argument for cookie_expires: %s"
-                                 % repr(self.cookie_expires))
-            self['_expires'] = expires
-        elif '_expires' in self:
-            expires = self['_expires']
-        else:
-            expires = None
-
-        val = self._encrypt_data()
-        if len(val) > 4064:
-            raise BeakerException("Cookie value is too long to store")
-        
-        self.cookie[self.key] = val
-        if '_domain' in self:
-            self.cookie[self.key]['domain'] = self['_domain']
-        elif self._domain:
-            self.cookie[self.key]['domain'] = self._domain
-        if self.secure:
-            self.cookie[self.key]['secure'] = True
-        
-        self.cookie[self.key]['path'] = self.get('_path', '/')
-        
-        if expires:
-            self.cookie[self.key]['expires'] = \
-                expires.strftime("%a, %d-%b-%Y %H:%M:%S GMT" )
-        self.request['cookie_out'] = self.cookie[self.key].output(header='')
-        self.request['set_cookie'] = True
-    
-    def delete(self):
-        """Delete the cookie, and clear the session"""
-        # Send a delete cookie request
-        self._delete_cookie()
-        self.clear()
-    
-    def invalidate(self):
-        """Clear the contents and start a new session"""
-        self.delete()
-        self['_id'] = self._make_id()
-
-
-class SessionObject(object):
-    """Session proxy/lazy creator
-    
-    This object proxies access to the actual session object, so that in
-    the case that the session hasn't been used before, it will be
-    setup. This avoid creating and loading the session from persistent
-    storage unless its actually used during the request.
-    
-    """
-    def __init__(self, environ, **params):
-        self.__dict__['_params'] = params
-        self.__dict__['_environ'] = environ
-        self.__dict__['_sess'] = None
-        self.__dict__['_headers'] = []
-    
-    def _session(self):
-        """Lazy initial creation of session object"""
-        if self.__dict__['_sess'] is None:
-            params = self.__dict__['_params']
-            environ = self.__dict__['_environ']
-            self.__dict__['_headers'] = req = {'cookie_out':None}
-            req['cookie'] = environ.get('HTTP_COOKIE')
-            if params.get('type') == 'cookie':
-                self.__dict__['_sess'] = CookieSession(req, **params)
-            else:
-                self.__dict__['_sess'] = Session(req, use_cookies=True,
-                                                 **params)
-        return self.__dict__['_sess']
-    
-    def __getattr__(self, attr):
-        return getattr(self._session(), attr)
-    
-    def __setattr__(self, attr, value):
-        setattr(self._session(), attr, value)
-    
-    def __delattr__(self, name):
-        self._session().__delattr__(name)
-    
-    def __getitem__(self, key):
-        return self._session()[key]
-    
-    def __setitem__(self, key, value):
-        self._session()[key] = value
-    
-    def __delitem__(self, key):
-        self._session().__delitem__(key)
-    
-    def __repr__(self):
-        return self._session().__repr__()
-    
-    def __iter__(self):
-        """Only works for proxying to a dict"""
-        return iter(self._session().keys())
-    
-    def __contains__(self, key):
-        return self._session().has_key(key)
-    
-    def get_by_id(self, id):
-        params = self.__dict__['_params']
-        session = Session({}, use_cookies=False, id=id, **params)
-        if session.is_new:
-            return None
-        return session
-    
-    def save(self):
-        self.__dict__['_dirty'] = True
-    
-    def delete(self):
-        self.__dict__['_dirty'] = True
-        self._session().delete()
-    
-    def persist(self):
-        """Persist the session to the storage
-        
-        If its set to autosave, then the entire session will be saved
-        regardless of if save() has been called. Otherwise, just the
-        accessed time will be updated if save() was not called, or
-        the session will be saved if save() was called.
-        
-        """
-        if self.__dict__['_params'].get('auto'):
-            self._session().save()
-        else:
-            if self.__dict__.get('_dirty'):
-                self._session().save()
-            else:
-                self._session().save(accessed_only=True)
-    
-    def dirty(self):
-        return self.__dict__.get('_dirty', False)
-    
-    def accessed(self):
-        return self.__dict__['_sess'] is not None

+ 0 - 381
desktop/core/ext-py/Beaker/beaker/synchronization.py

@@ -1,381 +0,0 @@
-"""Synchronization functions.
-
-File- and mutex-based mutual exclusion synchronizers are provided,
-as well as a name-based mutex which locks within an application
-based on a string name.
-
-"""
-
-import os
-import sys
-import tempfile
-
-try:
-    import threading as _threading
-except ImportError:
-    import dummy_threading as _threading
-
-# check for fcntl module
-try:
-    sys.getwindowsversion()
-    has_flock = False
-except:
-    try:
-        import fcntl
-        has_flock = True
-    except ImportError:
-        has_flock = False
-
-from beaker import util
-from beaker.exceptions import LockError
-
-__all__  = ["file_synchronizer", "mutex_synchronizer", "null_synchronizer",
-            "NameLock", "_threading"]
-
-
-class NameLock(object):
-    """a proxy for an RLock object that is stored in a name based
-    registry.  
-    
-    Multiple threads can get a reference to the same RLock based on the
-    name alone, and synchronize operations related to that name.
-
-    """     
-    locks = util.WeakValuedRegistry()
-
-    class NLContainer(object):
-        def __init__(self, reentrant):
-            if reentrant:
-                self.lock = _threading.RLock()
-            else:
-                self.lock = _threading.Lock()
-        def __call__(self):
-            return self.lock
-
-    def __init__(self, identifier = None, reentrant = False):
-        if identifier is None:
-            self._lock = NameLock.NLContainer(reentrant)
-        else:
-            self._lock = NameLock.locks.get(identifier, NameLock.NLContainer,
-                                            reentrant)
-
-    def acquire(self, wait = True):
-        return self._lock().acquire(wait)
-
-    def release(self):
-        self._lock().release()
-
-
-_synchronizers = util.WeakValuedRegistry()
-def _synchronizer(identifier, cls, **kwargs):
-    return _synchronizers.sync_get((identifier, cls), cls, identifier, **kwargs)
-
-
-def file_synchronizer(identifier, **kwargs):
-    if not has_flock or 'lock_dir' not in kwargs:
-        return mutex_synchronizer(identifier)
-    else:
-        return _synchronizer(identifier, FileSynchronizer, **kwargs)
-
-
-def mutex_synchronizer(identifier, **kwargs):
-    return _synchronizer(identifier, ConditionSynchronizer, **kwargs)
-
-
-class null_synchronizer(object):
-    def acquire_write_lock(self, wait=True):
-        return True
-    def acquire_read_lock(self):
-        pass
-    def release_write_lock(self):
-        pass
-    def release_read_lock(self):
-        pass
-    acquire = acquire_write_lock
-    release = release_write_lock
-
-
-class SynchronizerImpl(object):
-    def __init__(self):
-        self._state = util.ThreadLocal()
-
-    class SyncState(object):
-        __slots__ = 'reentrantcount', 'writing', 'reading'
-
-        def __init__(self):
-            self.reentrantcount = 0
-            self.writing = False
-            self.reading = False
-
-    def state(self):
-        if not self._state.has():
-            state = SynchronizerImpl.SyncState()
-            self._state.put(state)
-            return state
-        else:
-            return self._state.get()
-    state = property(state)
-    
-    def release_read_lock(self):
-        state = self.state
-
-        if state.writing: 
-            raise LockError("lock is in writing state")
-        if not state.reading: 
-            raise LockError("lock is not in reading state")
-        
-        if state.reentrantcount == 1:
-            self.do_release_read_lock()
-            state.reading = False
-
-        state.reentrantcount -= 1
-        
-    def acquire_read_lock(self, wait = True):
-        state = self.state
-
-        if state.writing: 
-            raise LockError("lock is in writing state")
-        
-        if state.reentrantcount == 0:
-            x = self.do_acquire_read_lock(wait)
-            if (wait or x):
-                state.reentrantcount += 1
-                state.reading = True
-            return x
-        elif state.reading:
-            state.reentrantcount += 1
-            return True
-            
-    def release_write_lock(self):
-        state = self.state
-
-        if state.reading: 
-            raise LockError("lock is in reading state")
-        if not state.writing: 
-            raise LockError("lock is not in writing state")
-
-        if state.reentrantcount == 1:
-            self.do_release_write_lock()
-            state.writing = False
-
-        state.reentrantcount -= 1
-    
-    release = release_write_lock
-    
-    def acquire_write_lock(self, wait  = True):
-        state = self.state
-
-        if state.reading: 
-            raise LockError("lock is in reading state")
-        
-        if state.reentrantcount == 0:
-            x = self.do_acquire_write_lock(wait)
-            if (wait or x): 
-                state.reentrantcount += 1
-                state.writing = True
-            return x
-        elif state.writing:
-            state.reentrantcount += 1
-            return True
-
-    acquire = acquire_write_lock
-
-    def do_release_read_lock(self):
-        raise NotImplementedError()
-    
-    def do_acquire_read_lock(self):
-        raise NotImplementedError()
-    
-    def do_release_write_lock(self):
-        raise NotImplementedError()
-    
-    def do_acquire_write_lock(self):
-        raise NotImplementedError()
-
-
-class FileSynchronizer(SynchronizerImpl):
-    """a synchronizer which locks using flock().
-
-    Adapted for Python/multithreads from Apache::Session::Lock::File,
-    http://search.cpan.org/src/CWEST/Apache-Session-1.81/Session/Lock/File.pm
-    
-    This module does not unlink temporary files, 
-    because it interferes with proper locking.  This can cause 
-    problems on certain systems (Linux) whose file systems (ext2) do not 
-    perform well with lots of files in one directory.  To prevent this
-    you should use a script to clean out old files from your lock directory.
-    
-    """
-    def __init__(self, identifier, lock_dir):
-        super(FileSynchronizer, self).__init__()
-        self._filedescriptor = util.ThreadLocal()
-        
-        if lock_dir is None:
-            lock_dir = tempfile.gettempdir()
-        else:
-            lock_dir = lock_dir
-
-        self.filename = util.encoded_path(
-                            lock_dir, 
-                            [identifier], 
-                            extension='.lock'
-                        )
-
-    def _filedesc(self):
-        return self._filedescriptor.get()
-    _filedesc = property(_filedesc)
-        
-    def _open(self, mode):
-        filedescriptor = self._filedesc
-        if filedescriptor is None:
-            filedescriptor = os.open(self.filename, mode)
-            self._filedescriptor.put(filedescriptor)
-        return filedescriptor
-            
-    def do_acquire_read_lock(self, wait):
-        filedescriptor = self._open(os.O_CREAT | os.O_RDONLY)
-        if not wait:
-            try:
-                fcntl.flock(filedescriptor, fcntl.LOCK_SH | fcntl.LOCK_NB)
-                return True
-            except IOError:
-                os.close(filedescriptor)
-                self._filedescriptor.remove()
-                return False
-        else:
-            fcntl.flock(filedescriptor, fcntl.LOCK_SH)
-            return True
-
-    def do_acquire_write_lock(self, wait):
-        filedescriptor = self._open(os.O_CREAT | os.O_WRONLY)
-        if not wait:
-            try:
-                fcntl.flock(filedescriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
-                return True
-            except IOError:
-                os.close(filedescriptor)
-                self._filedescriptor.remove()
-                return False
-        else:
-            fcntl.flock(filedescriptor, fcntl.LOCK_EX)
-            return True
-    
-    def do_release_read_lock(self):
-        self._release_all_locks()
-    
-    def do_release_write_lock(self):
-        self._release_all_locks()
-    
-    def _release_all_locks(self):
-        filedescriptor = self._filedesc
-        if filedescriptor is not None:
-            fcntl.flock(filedescriptor, fcntl.LOCK_UN)
-            os.close(filedescriptor)
-            self._filedescriptor.remove()
-
-
-class ConditionSynchronizer(SynchronizerImpl):
-    """a synchronizer using a Condition."""
-    
-    def __init__(self, identifier):
-        super(ConditionSynchronizer, self).__init__()
-
-        # counts how many asynchronous methods are executing
-        self.async = 0
-
-        # pointer to thread that is the current sync operation
-        self.current_sync_operation = None
-
-        # condition object to lock on
-        self.condition = _threading.Condition(_threading.Lock())
-
-    def do_acquire_read_lock(self, wait = True):    
-        self.condition.acquire()
-        try:
-            # see if a synchronous operation is waiting to start
-            # or is already running, in which case we wait (or just
-            # give up and return)
-            if wait:
-                while self.current_sync_operation is not None:
-                    self.condition.wait()
-            else:
-                if self.current_sync_operation is not None:
-                    return False
-
-            self.async += 1
-        finally:
-            self.condition.release()
-
-        if not wait: 
-            return True
-        
-    def do_release_read_lock(self):
-        self.condition.acquire()
-        try:
-            self.async -= 1
-        
-            # check if we are the last asynchronous reader thread 
-            # out the door.
-            if self.async == 0:
-                # yes. so if a sync operation is waiting, notifyAll to wake
-                # it up
-                if self.current_sync_operation is not None:
-                    self.condition.notifyAll()
-            elif self.async < 0:
-                raise LockError("Synchronizer error - too many "
-                                "release_read_locks called")
-        finally:
-            self.condition.release()
-    
-    def do_acquire_write_lock(self, wait = True):
-        self.condition.acquire()
-        try:
-            # here, we are not a synchronous reader, and after returning,
-            # assuming waiting or immediate availability, we will be.
-        
-            if wait:
-                # if another sync is working, wait
-                while self.current_sync_operation is not None:
-                    self.condition.wait()
-            else:
-                # if another sync is working,
-                # we dont want to wait, so forget it
-                if self.current_sync_operation is not None:
-                    return False
-            
-            # establish ourselves as the current sync 
-            # this indicates to other read/write operations
-            # that they should wait until this is None again
-            self.current_sync_operation = _threading.currentThread()
-
-            # now wait again for asyncs to finish
-            if self.async > 0:
-                if wait:
-                    # wait
-                    self.condition.wait()
-                else:
-                    # we dont want to wait, so forget it
-                    self.current_sync_operation = None
-                    return False
-        finally:
-            self.condition.release()
-        
-        if not wait: 
-            return True
-
-    def do_release_write_lock(self):
-        self.condition.acquire()
-        try:
-            if self.current_sync_operation is not _threading.currentThread():
-                raise LockError("Synchronizer error - current thread doesnt "
-                                "have the write lock")
-
-            # reset the current sync operation so 
-            # another can get it
-            self.current_sync_operation = None
-
-            # tell everyone to get ready
-            self.condition.notifyAll()
-        finally:
-            # everyone go !!
-            self.condition.release()

+ 0 - 364
desktop/core/ext-py/Beaker/beaker/util.py

@@ -1,364 +0,0 @@
-"""Beaker utilities"""
-try:
-    import thread as _thread
-    import threading as _threading
-except ImportError:
-    import dummy_thread as _thread
-    import dummy_threading as _threading
-
-from datetime import datetime, timedelta
-import os
-import string
-import types
-import weakref
-import warnings
-
-try:
-    Set = set
-except NameError:
-    from sets import Set
-try:
-    from hashlib import sha1
-except ImportError:
-    from sha import sha as sha1
-
-from beaker.converters import asbool
-
-try:
-    from base64 import b64encode, b64decode
-except ImportError:
-    import binascii
-
-    _translation = [chr(_x) for _x in range(256)]
-
-    # From Python 2.5 base64.py
-    def _translate(s, altchars):
-        translation = _translation[:]
-        for k, v in altchars.items():
-            translation[ord(k)] = v
-        return s.translate(''.join(translation))
-
-    def b64encode(s, altchars=None):
-        """Encode a string using Base64.
-
-        s is the string to encode.  Optional altchars must be a string of at least
-        length 2 (additional characters are ignored) which specifies an
-        alternative alphabet for the '+' and '/' characters.  This allows an
-        application to e.g. generate url or filesystem safe Base64 strings.
-
-        The encoded string is returned.
-        """
-        # Strip off the trailing newline
-        encoded = binascii.b2a_base64(s)[:-1]
-        if altchars is not None:
-            return _translate(encoded, {'+': altchars[0], '/': altchars[1]})
-        return encoded
-
-    def b64decode(s, altchars=None):
-        """Decode a Base64 encoded string.
-
-        s is the string to decode.  Optional altchars must be a string of at least
-        length 2 (additional characters are ignored) which specifies the
-        alternative alphabet used instead of the '+' and '/' characters.
-
-        The decoded string is returned.  A TypeError is raised if s were
-        incorrectly padded or if there are non-alphabet characters present in the
-        string.
-        """
-        if altchars is not None:
-            s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
-        try:
-            return binascii.a2b_base64(s)
-        except binascii.Error, msg:
-            # Transform this exception for consistency
-            raise TypeError(msg)
-
-try:
-    from threading import local as _tlocal
-except ImportError:
-    try:
-        from dummy_threading import local as _tlocal
-    except ImportError:
-        class _tlocal(object):
-            def __init__(self):
-                self.__dict__['_tdict'] = {}
-
-            def __delattr__(self, key):
-                try:
-                    del self._tdict[(thread.get_ident(), key)]
-                except KeyError:
-                    raise AttributeError(key)
-
-            def __getattr__(self, key):
-                try:
-                    return self._tdict[(thread.get_ident(), key)]
-                except KeyError:
-                    raise AttributeError(key)
-
-            def __setattr__(self, key, value):
-                self._tdict[(thread.get_ident(), key)] = value
-
-
-__all__  = ["ThreadLocal", "Registry", "WeakValuedRegistry", "SyncDict",
-            "encoded_path", "verify_directory"]
-
-
-def verify_directory(dir):
-    """verifies and creates a directory.  tries to
-    ignore collisions with other threads and processes."""
-
-    tries = 0
-    while not os.access(dir, os.F_OK):
-        try:
-            tries += 1
-            os.makedirs(dir)
-        except:
-            if tries > 5:
-                raise
-
-    
-def deprecated(func, message):
-    def deprecated_method(*args, **kargs):
-        warnings.warn(message, DeprecationWarning, 2)
-        return func(*args, **kargs)
-    try:
-        deprecated_method.__name__ = func.__name__
-    except TypeError: # Python < 2.4
-        pass
-    deprecated_method.__doc__ = "%s\n\n%s" % (message, func.__doc__)
-    return deprecated_method
-
-class ThreadLocal(object):
-    """stores a value on a per-thread basis"""
-
-    __slots__ = 'tlocal'
-
-    def __init__(self):
-        self.tlocal = _tlocal()
-    
-    def put(self, value):
-        self.tlocal.value = value
-    
-    def has(self):
-        return hasattr(self.tlocal, 'value')
-            
-    def get(self, default=None):
-        return getattr(self.tlocal, 'value', default)
-            
-    def remove(self):
-        del self.tlocal.value
-    
-class SyncDict(object):
-    """
-    An efficient/threadsafe singleton map algorithm, a.k.a.
-    "get a value based on this key, and create if not found or not
-    valid" paradigm:
-    
-        exists && isvalid ? get : create
-
-    Works with weakref dictionaries and the LRUCache to handle items
-    asynchronously disappearing from the dictionary.  
-
-    Use python 2.3.3 or greater !  a major bug was just fixed in Nov.
-    2003 that was driving me nuts with garbage collection/weakrefs in
-    this section.
-
-    """    
-    def __init__(self):
-        self.mutex = _thread.allocate_lock()
-        self.dict = {}
-        
-    def get(self, key, createfunc, *args, **kwargs):
-        try:
-            if self.has_key(key):
-                return self.dict[key]
-            else:
-                return self.sync_get(key, createfunc, *args, **kwargs)
-        except KeyError:
-            return self.sync_get(key, createfunc, *args, **kwargs)
-
-    def sync_get(self, key, createfunc, *args, **kwargs):
-        self.mutex.acquire()
-        try:
-            try:
-                if self.has_key(key):
-                    return self.dict[key]
-                else:
-                    return self._create(key, createfunc, *args, **kwargs)
-            except KeyError:
-                return self._create(key, createfunc, *args, **kwargs)
-        finally:
-            self.mutex.release()
-
-    def _create(self, key, createfunc, *args, **kwargs):
-        self[key] = obj = createfunc(*args, **kwargs)
-        return obj
-
-    def has_key(self, key):
-        return self.dict.has_key(key)
-        
-    def __contains__(self, key):
-        return self.dict.__contains__(key)
-    def __getitem__(self, key):
-        return self.dict.__getitem__(key)
-    def __setitem__(self, key, value):
-        self.dict.__setitem__(key, value)
-    def __delitem__(self, key):
-        return self.dict.__delitem__(key)
-    def clear(self):
-        self.dict.clear()
-
-
-class WeakValuedRegistry(SyncDict):
-    def __init__(self):
-        self.mutex = _threading.RLock()
-        self.dict = weakref.WeakValueDictionary()
-
-            
-def encoded_path(root, identifiers, extension = ".enc", depth = 3,
-                 digest_filenames=True):
-    """Generate a unique file-accessible path from the given list of
-    identifiers starting at the given root directory."""
-    ident = string.join(identifiers, "_")
-
-    if digest_filenames:
-        ident = sha1(ident).hexdigest()
-    
-    ident = os.path.basename(ident)
-
-    tokens = []
-    for d in range(1, depth):
-        tokens.append(ident[0:d])
-    
-    dir = os.path.join(root, *tokens)
-    verify_directory(dir)
-    
-    return os.path.join(dir, ident + extension)
-
-
-def verify_options(opt, types, error):
-    if not isinstance(opt, types):
-        if not isinstance(types, tuple):
-            types = (types,)
-        coerced = False
-        for typ in types:
-            try:
-                if typ in (list, tuple):
-                    opt = [x.strip() for x in opt.split(',')]
-                else:
-                    if typ == bool:
-                        typ = asbool
-                    opt = typ(opt)
-                coerced = True
-            except:
-                pass
-            if coerced:
-                break
-        if not coerced:
-            raise Exception(error)
-    elif isinstance(opt, str) and not opt.strip():
-        raise Exception("Empty strings are invalid for: %s" % error)
-    return opt
-
-
-def verify_rules(params, ruleset):
-    for key, types, message in ruleset:
-        if key in params:
-            params[key] = verify_options(params[key], types, message)
-    return params
-
-
-def coerce_session_params(params):
-    rules = [
-        ('data_dir', (str, types.NoneType), "data_dir must be a string "
-         "referring to a directory."),
-        ('lock_dir', (str,), "lock_dir must be a string referring to a "
-         "directory."),
-        ('type', (str, types.NoneType), "Session type must be a string."),
-        ('cookie_expires', (bool, datetime, timedelta), "Cookie expires was "
-         "not a boolean, datetime, or timedelta instance."),
-        ('cookie_domain', (str, types.NoneType), "Cookie domain must be a "
-         "string."),
-        ('id', (str,), "Session id must be a string."),
-        ('key', (str,), "Session key must be a string."),
-        ('secret', (str, types.NoneType), "Session secret must be a string."),
-        ('validate_key', (str, types.NoneType), "Session encrypt_key must be "
-         "a string."),
-        ('encrypt_key', (str, types.NoneType), "Session validate_key must be "
-         "a string."),
-        ('secure', (bool, types.NoneType), "Session secure must be a boolean."),
-        ('timeout', (int, types.NoneType), "Session timeout must be an "
-         "integer."),
-        ('auto', (bool, types.NoneType), "Session is created if accessed."),
-    ]
-    return verify_rules(params, rules)
-
-
-def coerce_cache_params(params):
-    rules = [
-        ('data_dir', (str, types.NoneType), "data_dir must be a string "
-         "referring to a directory."),
-        ('lock_dir', (str,), "lock_dir must be a string referring to a "
-         "directory."),
-        ('type', (str,), "Cache type must be a string."),
-        ('enabled', (bool, types.NoneType), "enabled must be true/false "
-         "if present."),
-        ('expire', (int, types.NoneType), "expire must be an integer representing "
-         "how many seconds the cache is valid for"),
-        ('regions', (list, tuple, types.NoneType), "Regions must be a "
-         "comma seperated list of valid regions")
-    ]
-    return verify_rules(params, rules)
-
-
-def parse_cache_config_options(config, include_defaults=True):
-    """Parse configuration options and validate for use with the
-    CacheManager"""
-    # Load default cache options
-    if include_defaults:
-        options= dict(type='memory', data_dir=None, expire=None, 
-                           log_file=None)
-    else:
-        options = {}
-    for key, val in config.iteritems():
-        if key.startswith('beaker.cache.'):
-            options[key[13:]] = val
-        if key.startswith('cache.'):
-            options[key[6:]] = val
-    coerce_cache_params(options)
-    
-    # Set cache to enabled if not turned off
-    if 'enabled' not in options:
-        options['enabled'] = True
-    
-    # Configure region dict if regions are available
-    regions = options.pop('regions', None)
-    if regions:
-        region_configs = {}
-        for region in regions:
-            # Setup the default cache options
-            region_options = dict(data_dir=options.get('data_dir'),
-                                  lock_dir=options.get('lock_dir'),
-                                  type=options.get('type'),
-                                  enabled=options['enabled'],
-                                  expire=options.get('expire'))
-            region_len = len(region) + 1
-            for key in options.keys():
-                if key.startswith('%s.' % region):
-                    region_options[key[region_len:]] = options.pop(key)
-            coerce_cache_params(region_options)
-            region_configs[region] = region_options
-        options['cache_regions'] = region_configs
-    return options
-
-def func_namespace(func):
-    """Generates a unique namespace for a function"""
-    kls = None
-    if hasattr(func, 'im_func'):
-        kls = func.im_class
-        func = func.im_func
-    
-    if kls:
-        return '%s.%s' % (kls.__module__, kls.__name__)
-    else:
-        return func.__module__

+ 0 - 11
desktop/core/ext-py/Beaker/setup.cfg

@@ -1,11 +0,0 @@
-[egg_info]
-tag_build = 
-tag_date = 0
-tag_svn_revision = 0
-
-[nosetests]
-detailed-errors = True
-where = tests
-verbose = True
-with-doctest = True
-

+ 0 - 107
desktop/core/ext-py/Beaker/setup.py

@@ -1,107 +0,0 @@
-import sys
-
-from setuptools import setup, find_packages
-
-version = '1.4.2'
-
-pycryptopp = 'pycryptopp>=0.5.12'
-tests_require = ['nose', 'webtest']
-if not sys.platform.startswith('java') and not sys.platform == 'cli':
-    tests_require.extend([pycryptopp, 'SQLALchemy'])
-    try:
-        import sqlite3
-    except ImportError:
-        tests_require.append('pysqlite')
-
-setup(name='Beaker',
-      version=version,
-      description="A Session and Caching library with WSGI Middleware",
-      long_description="""\
-Cache and Session Library
-+++++++++++++++++++++++++
-
-About
-=====
-
-Beaker is a web session and general caching library that includes WSGI 
-middleware for use in web applications.
-
-As a general caching library, Beaker can handle storing for various times
-any Python object that can be pickled with optional back-ends on a 
-fine-grained basis.
-
-Beaker was built largely on the code from MyghtyUtils, then refactored and
-extended with database support.
-
-Beaker includes Cache and Session WSGI middleware to ease integration with
-WSGI capable frameworks, and is automatically used by `Pylons 
-<http://pylonshq.com/>`_.
-
-
-Features
-========
-
-* Fast, robust performance
-* Multiple reader/single writer lock system to avoid duplicate simultaneous 
-  cache creation
-* Cache back-ends include dbm, file, memory, memcached, and database (Using
-  SQLAlchemy for multiple-db vendor support)
-* Signed cookie's to prevent session hijacking/spoofing
-* Cookie-only sessions to remove the need for a db or file backend (ideal 
-  for clustered systems)
-* Extensible Container object to support new back-ends
-* Cache's can be divided into namespaces (to represent templates, objects, 
-  etc.) then keyed for different copies
-* Create functions for automatic call-backs to create new cache copies after
-  expiration
-* Fine-grained toggling of back-ends, keys, and expiration per Cache object
-
-
-Documentation
-=============
-
-Documentation can be found on the `Official Beaker Docs site
-<http://beaker.groovie.org/>`_.
-
-
-Source
-======
-
-The latest developer version is available in a `Mercurial repository
-<http://bitbucket.org/bbangert/beaker/get/tip.gz#egg=Beaker-dev>`_.
-""",
-      classifiers=[
-      'Development Status :: 5 - Production/Stable',
-      'Environment :: Web Environment',
-      'Intended Audience :: Developers',
-      'License :: OSI Approved :: BSD License',
-      'Programming Language :: Python',
-      'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
-      ],
-      keywords='wsgi myghty session web cache middleware',
-      author='Ben Bangart, Mike Bayer, Philip Jenvey',
-      author_email='ben@groovie.org, pjenvey@groovie.org',
-      url='http://beaker.groovie.org',
-      license='BSD',
-      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
-      zip_safe=False,
-      install_requires=[],
-      extras_require={
-          'crypto':[pycryptopp]
-      },
-      test_suite='nose.collector',
-      tests_require=tests_require,
-      entry_points="""
-          [paste.filter_factory]
-          beaker_session = beaker.middleware:session_filter_factory
-          
-          [paste.filter_app_factory]
-          beaker_session = beaker.middleware:session_filter_app_factory
-          
-          [beaker.backends]
-          database = beaker.ext.database:DatabaseNamespaceManager
-          memcached = beaker.ext.memcached:MemcachedNamespaceManager
-          google = beaker.ext.google:GoogleNamespaceManager
-          sqla = beaker.ext.sqla:SqlaNamespaceManager
-      """,
-)

+ 0 - 251
desktop/core/ext-py/Beaker/tests/test_cache.py

@@ -1,251 +0,0 @@
-# coding: utf-8
-import os
-import shutil
-import tarfile
-import tempfile
-import time
-from beaker.middleware import CacheMiddleware
-from beaker.cache import Cache
-from webtest import TestApp
-
-# Tarballs of the output of:
-# >>> from beaker.cache import Cache
-# >>> c = Cache('test', data_dir='db', type='dbm')
-# >>> c['foo'] = 'bar'
-# in the old format, Beaker @ revision: 24f57102d310
-dbm_cache_tar = """\
-eJzt3EtOwkAAgOEBjTHEBDfu2ekKZ6bTTnsBL+ABzPRB4osSRBMXHsNruXDl3nMYLaEbpYRAaIn6
-f8kwhFcn/APLSeNTUTdZsL4/m4Pg21wSqiCt9D1PC6mUZ7Xo+bWvrHB/N3HjXk+MrrLhQ/a48HXL
-nv+l0vg0yYcTdznMxhdpfFvHbpj1lyv0N8oq+jdhrr/b/A5Yo79R9G9ERX8XbXgLrNHfav7/G1Hd
-30XGhYPMT5JYRbELVGISGVov9SKVRaGNQj2I49TrF+8oxpJrTAMHxizob+b7ay+Y/v5lE1/AP+8v
-9o5ccdsWYvdViMPpIwdCtMRsiP3yTrucd8r5pJxbz8On9/KT2uVo3H5rG1cFAAAAAOD3aIuP7lv3
-pRjbXgkAAAAAAFjVyc1Idc6U1lYGgbSmL0Mjpe248+PYjY87I91x/UGeb3udAAAAAACgfh+fAAAA
-AADgr/t5/sPFTZ5cb/38D19Lzn9pRHX/zR4CtEZ/o+nfiEX9N3kI0Gr9vWl/W0z0BwAAAAAAAAAA
-AAAAAAAAqPAFyOvcKA==
-""".decode('base64').decode('zlib')
-
-# dumbdbm format
-dumbdbm_cache_tar = """\
-eJzt191qgzAYBmCPvYqc2UGx+ZKY6A3scCe7gJKoha6binOD3f2yn5Ouf3TTlNH3AQlEJcE3nyGV
-W0RT457Jsq9W6632W0Se0JI49/1E0vCIZZPPzHt5HmzPWNQ91M1r/XbwuVP3/6nKLcq2Gey6qftl
-5Z6mWA3n56/IKOQfwk7+dvwV8Iv8FSH/IPbkb4uRl8BZ+fvg/WUE8g9if/62UDZf1VlZOiqc1VSq
-kudGVrKgushNkYuVc5VM/Rups5vjY3wErJU6nD+Z7fyFNFpEjIf4AFeef7Jq22TOZnzOpLiJLz0d
-CGyE+q/scHyMk/Wv+E79G0L9hzC7JSFMpv0PN0+J4rv7xNk+iTuKh07E6aXnB9Mao/7X/fExzt//
-FecS9R8C9v/r9rP+l49tubnk+e/z/J8JjvMfAAAAAAAAAADAn70DFJAAwQ==
-""".decode('base64').decode('zlib')
-
-def simple_app(environ, start_response):
-    clear = False
-    if environ.get('beaker.clear'):
-        clear = True
-    cache = environ['beaker.cache'].get_cache('testcache')
-    if clear:
-        cache.clear()
-    try:
-        value = cache.get_value('value')
-    except:
-        value = 0
-    cache.set_value('value', value+1)
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    return ['The current value is: %s' % cache.get_value('value')]
-
-def cache_manager_app(environ, start_response):
-    cm = environ['beaker.cache']
-    cm.get_cache('test')['test_key'] = 'test value'
-
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    yield "test_key is: %s\n" % cm.get_cache('test')['test_key']
-    cm.get_cache('test').clear()
-
-    try:
-        test_value = cm.get_cache('test')['test_key']
-    except KeyError:
-        yield "test_key cleared"
-    else:
-        yield "test_key wasn't cleared, is: %s\n" % \
-            cm.get_cache('test')['test_key']
-
-def test_has_key():
-    cache = Cache('test', data_dir='./cache', type='dbm')
-    o = object()
-    cache.set_value("test", o)
-    assert cache.has_key("test")
-    assert "test" in cache
-    assert not cache.has_key("foo")
-    assert "foo" not in cache
-    cache.remove_value("test")
-    assert not cache.has_key("test")
-
-def test_expire_changes():
-    cache = Cache('test_bar', data_dir='./cache', type='dbm')
-    cache.set_value('test', 10)
-    assert cache.has_key('test')
-    assert cache['test'] == 10
-    
-    # ensure that we can change a never-expiring value
-    cache.set_value('test', 20, expiretime=1)
-    assert cache.has_key('test')
-    assert cache['test'] == 20
-    time.sleep(1)
-    assert not cache.has_key('test')
-    
-    # test that we can change it before its expired
-    cache.set_value('test', 30, expiretime=50)
-    assert cache.has_key('test')
-    assert cache['test'] == 30
-    
-    cache.set_value('test', 40, expiretime=3)
-    assert cache.has_key('test')
-    assert cache['test'] == 40
-    time.sleep(3)
-    assert not cache.has_key('test')
-
-def test_fresh_createfunc():
-    cache = Cache('test_foo', data_dir='./cache', type='dbm')
-    x = cache.get_value('test', createfunc=lambda: 10, expiretime=2)
-    assert x == 10
-    x = cache.get_value('test', createfunc=lambda: 12, expiretime=2)
-    assert x == 10
-    x = cache.get_value('test', createfunc=lambda: 14, expiretime=2)
-    assert x == 10
-    time.sleep(2)
-    x = cache.get_value('test', createfunc=lambda: 16, expiretime=2)
-    assert x == 16
-    x = cache.get_value('test', createfunc=lambda: 18, expiretime=2)
-    assert x == 16
-    
-    cache.remove_value('test')
-    assert not cache.has_key('test')
-    x = cache.get_value('test', createfunc=lambda: 20, expiretime=2)
-    assert x == 20
-    
-    
-    
-def test_has_key_multicache():
-    cache = Cache('test', data_dir='./cache', type='dbm')
-    o = object()
-    cache.set_value("test", o)
-    assert cache.has_key("test")
-    assert "test" in cache
-    cache = Cache('test', data_dir='./cache', type='dbm')
-    assert cache.has_key("test")
-
-def test_unicode_keys():    
-    cache = Cache('test', data_dir='./cache', type='dbm')
-    o = object()
-    cache.set_value(u'hiŏ', o)
-    assert u'hiŏ' in cache
-    assert u'hŏa' not in cache
-    cache.remove_value(u'hiŏ')
-    assert u'hiŏ' not in cache
-
-def test_multi_keys():
-    cache = Cache('newtests', data_dir='./cache', type='dbm')
-    cache.clear()
-    called = {}
-    def create_func():
-        called['here'] = True
-        return 'howdy'
-    
-    try:
-        cache.get_value('key1')
-    except KeyError:
-        pass
-    else:
-        raise Exception("Failed to keyerror on nonexistent key")
-
-    assert 'howdy' == cache.get_value('key2', createfunc=create_func)
-    assert called['here'] == True
-    del called['here']
-
-    try:
-        cache.get_value('key3')
-    except KeyError:
-        pass
-    else:
-        raise Exception("Failed to keyerror on nonexistent key")
-    try:
-        cache.get_value('key1')
-    except KeyError:
-        pass
-    else:
-        raise Exception("Failed to keyerror on nonexistent key")
-    
-    assert 'howdy' == cache.get_value('key2', createfunc=create_func)
-    assert called == {}
-
-def test_increment():
-    app = TestApp(CacheMiddleware(simple_app))
-    res = app.get('/', extra_environ={'beaker.type':type, 'beaker.clear':True})
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    assert 'current value is: 2' in res
-    res = app.get('/')
-    assert 'current value is: 3' in res
-
-def test_cache_manager():
-    app = TestApp(CacheMiddleware(cache_manager_app))
-    res = app.get('/')
-    assert 'test_key is: test value' in res
-    assert 'test_key cleared' in res
-    
-def test_legacy_cache():
-    cache = Cache('newtests', data_dir='./cache', type='dbm')
-    
-    cache.set_value('x', '1')
-    assert cache.get_value('x') == '1'
-    
-    cache.set_value('x', '2', type='file', data_dir='./cache')
-    assert cache.get_value('x') == '1'
-    assert cache.get_value('x', type='file', data_dir='./cache') == '2'
-    
-    cache.remove_value('x')
-    cache.remove_value('x', type='file', data_dir='./cache')
-    
-    assert cache.get_value('x', expiretime=1, createfunc=lambda: '5') == '5'
-    assert cache.get_value('x', expiretime=1, createfunc=lambda: '6', type='file', data_dir='./cache') == '6'
-    assert cache.get_value('x', expiretime=1, createfunc=lambda: '7') == '5'
-    assert cache.get_value('x', expiretime=1, createfunc=lambda: '8', type='file', data_dir='./cache') == '6'
-    time.sleep(1)
-    assert cache.get_value('x', expiretime=1, createfunc=lambda: '9') == '9'
-    assert cache.get_value('x', expiretime=1, createfunc=lambda: '10', type='file', data_dir='./cache') == '10'
-    assert cache.get_value('x', expiretime=1, createfunc=lambda: '11') == '9'
-    assert cache.get_value('x', expiretime=1, createfunc=lambda: '12', type='file', data_dir='./cache') == '10'
-    
-
-def test_upgrade():
-    for test in _test_upgrade_has_key, _test_upgrade_in, _test_upgrade_setitem:
-        for mod, tar in (('dbm', dbm_cache_tar),
-                         ('dumbdbm', dumbdbm_cache_tar)):
-            try:
-                __import__(mod)
-            except ImportError:
-                continue
-            dir = tempfile.mkdtemp()
-            fd, name = tempfile.mkstemp(dir=dir)
-            fp = os.fdopen(fd, 'w')
-            fp.write(tar)
-            fp.close()
-            tar = tarfile.open(name)
-            for member in tar.getmembers():
-                tar.extract(member, dir)
-            tar.close()
-            try:
-                test(os.path.join(dir, 'db'))
-            finally:
-                shutil.rmtree(dir)
-
-def _test_upgrade_has_key(dir):
-    cache = Cache('test', data_dir=dir, type='dbm')
-    assert cache.has_key('foo')
-    assert cache.has_key('foo')
-
-def _test_upgrade_in(dir):
-    cache = Cache('test', data_dir=dir, type='dbm')
-    assert 'foo' in cache
-    assert 'foo' in cache
-
-def _test_upgrade_setitem(dir):
-    cache = Cache('test', data_dir=dir, type='dbm')
-    assert cache['foo'] == 'bar'
-    assert cache['foo'] == 'bar'

+ 0 - 180
desktop/core/ext-py/Beaker/tests/test_container.py

@@ -1,180 +0,0 @@
-import os
-import random
-import time
-import unittest
-from beaker.container import *
-from beaker.synchronization import _synchronizers
-from beaker.cache import clsmap
-import thread
-
-def create(delay=0):
-    global baton, totalcreates
-    assert baton is None, "baton is not none , ident %r, this thread %r" % (baton, thread.get_ident())
-
-    baton = thread.get_ident()
-    try:    
-        obj = object()
-        time.sleep(delay)
-        totalcreates += 1
-        return obj
-    finally:
-        baton = None
-        
-def runthread(cls, id, runningids, value, delay, kwargs):
-    print "create thread %d starting" % id
-    runningids.add(id)
-
-    try:
-        if not value:
-            expiretime = kwargs.pop('expiretime', None)
-            starttime = kwargs.pop('starttime', None)
-            value = Value('test', cls('test', **kwargs), createfunc=lambda:create(delay), expiretime=expiretime, starttime=starttime)
-            
-        global running, totalgets
-        try:
-            while running:
-                item = value.get_value()
-                assert item is not None
-                item = None
-                totalgets += 1
-                time.sleep(random.random() * .00001)
-        except:
-            running = False
-            raise
-    finally:
-        print "create thread %d exiting" % id
-        runningids.remove(id)
-
-def _runtest(cls, totaltime, expiretime, delay, threadlocal):
-    print "\ntesting %s for %d secs with expiretime %s delay %d" % (
-        cls, totaltime, expiretime, delay)
-
-    global running, starttime, baton, totalcreates, totalgets
-    
-    running = False
-    starttime = time.time()
-    baton = None
-
-    runningids = set()
-    totalcreates = 0
-
-    totalgets = 0
-    
-    kwargs = dict(
-        expiretime=expiretime, 
-        starttime = starttime,
-        data_dir='./cache'
-        )
-    
-    if not threadlocal:
-        expiretime = kwargs.pop('expiretime', None)
-        starttime = kwargs.pop('starttime', None)
-        value = Value('test', cls('test', **kwargs), createfunc=lambda:create(delay), expiretime=expiretime, starttime=starttime)
-        value.clear_value()
-    else:
-        value = None
-        
-    running = True    
-    for t in range(1, 20):
-        thread.start_new_thread(runthread, (cls, t, runningids, value, delay, kwargs))
-        
-    time.sleep(totaltime)
-    
-    failed = not running
-
-    running = False
-
-    while runningids:
-        time.sleep(1)
-
-    assert not failed
-
-    print "total object creates %d" % totalcreates
-    print "total object gets %d" % totalgets
-    
-    if expiretime is None:
-        assert totalcreates == 1
-    else:
-        assert abs(totaltime / expiretime - totalcreates) <= 2
-
-def test_memory_container(totaltime=10, expiretime=None, delay=0, threadlocal=False):
-    _runtest(clsmap['memory'],
-                  totaltime, expiretime, delay, threadlocal)
-
-def test_dbm_container(totaltime=10, expiretime=None, delay=0):
-    _runtest(clsmap['dbm'], totaltime, expiretime, delay, False)
-
-def test_file_container(totaltime=10, expiretime=None, delay=0, threadlocal=False):
-    _runtest(clsmap['file'], totaltime, expiretime, delay, threadlocal)
-
-def test_memory_container_tlocal():
-    test_memory_container(expiretime=5, delay=2, threadlocal=True)
-    
-def test_memory_container_2():
-    test_memory_container(expiretime=2)
-
-def test_memory_container_3():
-    test_memory_container(expiretime=5, delay=2)
-
-def test_dbm_container_2():
-    test_dbm_container(expiretime=2)
-
-def test_dbm_container_3():
-    test_dbm_container(expiretime=5, delay=2)
-
-def test_file_container_2():
-    test_file_container(expiretime=2)
-    
-def test_file_container_3():
-    test_file_container(expiretime=5, delay=2)
-
-def test_file_container_tlocal():
-    test_file_container(expiretime=5, delay=2, threadlocal=True)
-
-def test_file_open_bug():
-    """ensure errors raised during reads or writes don't lock the namespace open."""
-    
-    value = Value('test', clsmap['file']('reentrant_test', data_dir='./cache'))
-    if os.path.exists(value.namespace.file):
-        os.remove(value.namespace.file)
-    
-    value.set_value("x")
-
-    f = open(value.namespace.file, 'w')
-    f.write("BLAH BLAH BLAH")
-    f.close()
-    
-    # TODO: do we have an assertRaises() in nose to use here ?
-    try:
-        value.set_value("y")
-        assert False
-    except:
-        pass
-        
-    _synchronizers.clear()
-
-    value = Value('test', clsmap['file']('reentrant_test', data_dir='./cache'))
-
-    # TODO: do we have an assertRaises() in nose to use here ?
-    try:
-        value.set_value("z")
-        assert False
-    except:
-        pass
-
-
-def test_removing_file_refreshes():
-    """test that the cache doesn't ignore file removals"""
-    
-    x = [0]
-    def create():
-        x[0] += 1
-        return x[0]
-        
-    value = Value('test', clsmap['file']('refresh_test', data_dir='./cache'), createfunc=create, starttime=time.time())
-    if os.path.exists(value.namespace.file):
-        os.remove(value.namespace.file)
-    assert value.get_value() == 1
-    assert value.get_value() == 1
-    os.remove(value.namespace.file)
-    assert value.get_value() == 2

+ 0 - 120
desktop/core/ext-py/Beaker/tests/test_cookie_only.py

@@ -1,120 +0,0 @@
-import re
-import os
-
-import beaker.session
-from beaker.middleware import SessionMiddleware
-from nose import SkipTest
-from webtest import TestApp
-
-if not beaker.session.crypto_ok:
-    raise SkipTest("No usable crypto library found, can't test cookie-only "
-                   "Sessions")
-
-def simple_app(environ, start_response):
-    session = environ['beaker.session']
-    if not session.has_key('value'):
-        session['value'] = 0
-    session['value'] += 1
-    if not environ['PATH_INFO'].startswith('/nosave'):
-        session.save()
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    return ['The current value is: %d and cookie is %s' % (session['value'], session)]
-
-def test_increment():
-    options = {'session.validate_key':'hoobermas', 'session.type':'cookie'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    assert 'current value is: 2' in res
-    res = app.get('/')
-    assert 'current value is: 3' in res
-
-def test_different_sessions():
-    options = {'session.validate_key':'hoobermas', 'session.type':'cookie'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    app2 = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app2.get('/')
-    assert 'current value is: 1' in res
-    res = app2.get('/')
-    res = app2.get('/')
-    res = app2.get('/')
-    res2 = app.get('/')
-    assert 'current value is: 2' in res2
-    assert 'current value is: 4' in res
-
-def test_nosave():
-    options = {'session.validate_key':'hoobermas', 'session.type':'cookie'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/nosave')
-    assert 'current value is: 1' in res
-    assert [] == res.headers.getall('Set-Cookie')
-    res = app.get('/nosave')
-    assert 'current value is: 1' in res
-    
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    assert len(res.headers.getall('Set-Cookie')) > 0
-    res = app.get('/')
-    assert 'current value is: 2' in res
-
-def test_increment_with_encryption():
-    options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
-               'session.type':'cookie'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    assert 'current value is: 2' in res
-    res = app.get('/')
-    assert 'current value is: 3' in res
-
-def test_different_sessions_with_encryption():
-    options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
-               'session.type':'cookie'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    app2 = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app2.get('/')
-    assert 'current value is: 1' in res
-    res = app2.get('/')
-    res = app2.get('/')
-    res = app2.get('/')
-    res2 = app.get('/')
-    assert 'current value is: 2' in res2
-    assert 'current value is: 4' in res
-
-def test_nosave_with_encryption():
-    options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
-               'session.type':'cookie'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/nosave')
-    assert 'current value is: 1' in res
-    assert [] == res.headers.getall('Set-Cookie')
-    res = app.get('/nosave')
-    assert 'current value is: 1' in res
-    
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    assert len(res.headers.getall('Set-Cookie')) > 0
-    res = app.get('/')
-    assert 'current value is: 2' in res
-
-def test_cookie_id():
-    options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas',
-               'session.type':'cookie'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/')
-    assert "_id':" in res
-    sess_id = re.sub(r".*'_id': '(.*?)'.*", r'\1', res.body)
-    res = app.get('/')
-    new_id = re.sub(r".*'_id': '(.*?)'.*", r'\1', res.body)
-    assert new_id == sess_id
-
-if __name__ == '__main__':
-    from paste import httpserver
-    wsgi_app = SessionMiddleware(simple_app, {})
-    httpserver.serve(wsgi_app, host='127.0.0.1', port=8080)

+ 0 - 99
desktop/core/ext-py/Beaker/tests/test_database.py

@@ -1,99 +0,0 @@
-# coding: utf-8
-from beaker.cache import clsmap, Cache
-from beaker.middleware import CacheMiddleware
-from nose import SkipTest
-from webtest import TestApp
-
-if isinstance(clsmap.get('ext:database'), Exception):
-    raise SkipTest("'sqlalchemy' is not installed, can't test database "
-                   "backend")
-
-db_url = 'sqlite:///test.db'
-
-def simple_app(environ, start_response):
-    extra_args = {}
-    clear = False
-    if environ.get('beaker.clear'):
-        clear = True
-    extra_args['type'] = 'ext:database'
-    extra_args['url'] = db_url
-    extra_args['data_dir'] = './cache'
-    cache = environ['beaker.cache'].get_cache('testcache', **extra_args)
-    if clear:
-        cache.clear()
-    try:
-        value = cache.get_value('value')
-    except:
-        value = 0
-    cache.set_value('value', value+1)
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    return ['The current value is: %s' % cache.get_value('value')]
-
-def cache_manager_app(environ, start_response):
-    cm = environ['beaker.cache']
-    cm.get_cache('test')['test_key'] = 'test value'
-
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    yield "test_key is: %s\n" % cm.get_cache('test')['test_key']
-    cm.get_cache('test').clear()
-
-    try:
-        test_value = cm.get_cache('test')['test_key']
-    except KeyError:
-        yield "test_key cleared"
-    else:
-        yield "test_key wasn't cleared, is: %s\n" % \
-            cm.get_cache('test')['test_key']
-
-def test_has_key():
-    cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database')
-    o = object()
-    cache.set_value("test", o)
-    assert cache.has_key("test")
-    assert "test" in cache
-    assert not cache.has_key("foo")
-    assert "foo" not in cache
-    cache.remove_value("test")
-    assert not cache.has_key("test")
-
-def test_has_key_multicache():
-    cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database')
-    o = object()
-    cache.set_value("test", o)
-    assert cache.has_key("test")
-    assert "test" in cache
-    cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database')
-    assert cache.has_key("test")
-    cache.remove_value('test')
-
-def test_clear():
-    cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database')
-    o = object()
-    cache.set_value("test", o)
-    assert cache.has_key("test")
-    cache.clear()
-    assert not cache.has_key("test")
-
-def test_unicode_keys():
-    cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database')
-    o = object()
-    cache.set_value(u'hiŏ', o)
-    assert u'hiŏ' in cache
-    assert u'hŏa' not in cache
-    cache.remove_value(u'hiŏ')
-    assert u'hiŏ' not in cache
-    
-def test_increment():
-    app = TestApp(CacheMiddleware(simple_app))
-    res = app.get('/', extra_environ={'beaker.clear':True})
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    assert 'current value is: 2' in res
-    res = app.get('/')
-    assert 'current value is: 3' in res
-
-def test_cache_manager():
-    app = TestApp(CacheMiddleware(cache_manager_app))
-    res = app.get('/')
-    assert 'test_key is: test value' in res
-    assert 'test_key cleared' in res

+ 0 - 174
desktop/core/ext-py/Beaker/tests/test_increment.py

@@ -1,174 +0,0 @@
-import re
-import os
-
-from beaker.middleware import SessionMiddleware
-from webtest import TestApp
-
-loc = os.path.sep.join([os.path.dirname(os.path.abspath(__file__)), 'sessions'])
-
-def no_save_app(environ, start_response):
-    session = environ['beaker.session']
-    sess_id = environ.get('SESSION_ID')
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    return ['The current value is: %s, session id is %s' % (session.get('value'),
-                                                            session.id)]
-    
-def simple_app(environ, start_response):
-    session = environ['beaker.session']
-    sess_id = environ.get('SESSION_ID')
-    if sess_id:
-        session = session.get_by_id(sess_id)
-    if not session:
-        start_response('200 OK', [('Content-type', 'text/plain')])
-        return ["No session id of %s found." % sess_id]
-    if not session.has_key('value'):
-        session['value'] = 0
-    session['value'] += 1
-    if not environ['PATH_INFO'].startswith('/nosave'):
-        session.save()
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    return ['The current value is: %d, session id is %s' % (session['value'],
-                                                            session.id)]
-
-def simple_auto_app(environ, start_response):
-    """Like the simple_app, but assume that sessions auto-save"""
-    session = environ['beaker.session']
-    sess_id = environ.get('SESSION_ID')
-    if sess_id:
-        session = session.get_by_id(sess_id)
-    if not session:
-        start_response('200 OK', [('Content-type', 'text/plain')])
-        return ["No session id of %s found." % sess_id]
-    if not session.has_key('value'):
-        session['value'] = 0
-    session['value'] += 1
-    if environ['PATH_INFO'].startswith('/nosave'):
-        session.revert()
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    return ['The current value is: %d, session id is %s' % (session.get('value', 0),
-                                                            session.id)]
-
-def test_no_save():
-    options = {'session.data_dir':loc, 'session.secret':'blah'}
-    app = TestApp(SessionMiddleware(no_save_app, **options))
-    res = app.get('/')
-    assert 'current value is: None' in res
-    assert [] == res.headers.getall('Set-Cookie')
-
-
-def test_increment():
-    options = {'session.data_dir':loc, 'session.secret':'blah'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    assert 'current value is: 2' in res
-    res = app.get('/')
-    assert 'current value is: 3' in res
-
-def test_increment_auto():
-    options = {'session.data_dir':loc, 'session.secret':'blah'}
-    app = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    assert 'current value is: 2' in res
-    res = app.get('/')
-    assert 'current value is: 3' in res
-
-
-def test_different_sessions():
-    options = {'session.data_dir':loc, 'session.secret':'blah'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    app2 = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app2.get('/')
-    assert 'current value is: 1' in res
-    res = app2.get('/')
-    res = app2.get('/')
-    res = app2.get('/')
-    res2 = app.get('/')
-    assert 'current value is: 2' in res2
-    assert 'current value is: 4' in res
-
-def test_different_sessions_auto():
-    options = {'session.data_dir':loc, 'session.secret':'blah'}
-    app = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options))
-    app2 = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app2.get('/')
-    assert 'current value is: 1' in res
-    res = app2.get('/')
-    res = app2.get('/')
-    res = app2.get('/')
-    res2 = app.get('/')
-    assert 'current value is: 2' in res2
-    assert 'current value is: 4' in res
-
-def test_nosave():
-    options = {'session.data_dir':loc, 'session.secret':'blah'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/nosave')
-    assert 'current value is: 1' in res
-    res = app.get('/nosave')
-    assert 'current value is: 1' in res
-    
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    assert 'current value is: 2' in res
-
-def test_revert():
-    options = {'session.data_dir':loc, 'session.secret':'blah'}
-    app = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options))
-    res = app.get('/nosave')
-    assert 'current value is: 0' in res
-    res = app.get('/nosave')
-    assert 'current value is: 0' in res
-    
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    assert [] == res.headers.getall('Set-Cookie')
-    res = app.get('/')
-    assert [] == res.headers.getall('Set-Cookie')
-    assert 'current value is: 2' in res
-    
-    # Finally, ensure that reverting shows the proper one
-    res = app.get('/nosave')
-    assert [] == res.headers.getall('Set-Cookie')
-    assert 'current value is: 2' in res
-
-def test_load_session_by_id():
-    options = {'session.data_dir':loc, 'session.secret':'blah'}
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    res = app.get('/')
-    assert 'current value is: 3' in res
-    old_id = re.sub(r'^.*?session id is (\S+)$', r'\1', res.body, re.M)
-    
-    # Clear the cookies and do a new request
-    app = TestApp(SessionMiddleware(simple_app, **options))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    
-    # Load a bogus session to see that its not there
-    res = app.get('/', extra_environ={'SESSION_ID':'jil2j34il2j34ilj23'})
-    assert 'No session id of' in res
-    
-    # Saved session was at 3, now it'll be 4
-    res = app.get('/', extra_environ={'SESSION_ID':old_id})
-    assert 'current value is: 4' in res
-    
-    # Prior request is now up to 2
-    res = app.get('/')
-    assert 'current value is: 2' in res
-
-
-if __name__ == '__main__':
-    from paste import httpserver
-    wsgi_app = SessionMiddleware(simple_app, {})
-    httpserver.serve(wsgi_app, host='127.0.0.1', port=8080)

+ 0 - 220
desktop/core/ext-py/Beaker/tests/test_memcached.py

@@ -1,220 +0,0 @@
-# coding: utf-8
-import os
-
-from beaker.cache import clsmap, Cache
-from beaker.middleware import CacheMiddleware, SessionMiddleware
-from nose import SkipTest
-from webtest import TestApp
-
-if isinstance(clsmap.get('ext:memcached'), Exception):
-    raise SkipTest("'memcache' or 'cmemcache' is not installed, can't test "
-                   "memcached backend")
-
-mc_url = '127.0.0.1:11211'
-loc = os.path.sep.join([os.path.dirname(os.path.abspath(__file__)), 'sessions'])
-
-def simple_session_app(environ, start_response):
-    session = environ['beaker.session']
-    sess_id = environ.get('SESSION_ID')
-    if environ['PATH_INFO'].startswith('/invalid'):
-        # Attempt to access the session
-        id = session.id
-        session['value'] = 2
-    else:
-        if sess_id:
-            session = session.get_by_id(sess_id)
-        if not session:
-            start_response('200 OK', [('Content-type', 'text/plain')])
-            return ["No session id of %s found." % sess_id]
-        if not session.has_key('value'):
-            session['value'] = 0
-        session['value'] += 1
-        if not environ['PATH_INFO'].startswith('/nosave'):
-            session.save()
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    return ['The current value is: %d, session id is %s' % (session['value'],
-                                                            session.id)]
-
-def simple_app(environ, start_response):
-    extra_args = {}
-    clear = False
-    if environ.get('beaker.clear'):
-        clear = True
-    extra_args['type'] = 'ext:memcached'
-    extra_args['url'] = mc_url
-    extra_args['data_dir'] = './cache'
-    cache = environ['beaker.cache'].get_cache('testcache', **extra_args)
-    if clear:
-        cache.clear()
-    try:
-        value = cache.get_value('value')
-    except:
-        value = 0
-    cache.set_value('value', value+1)
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    return ['The current value is: %s' % cache.get_value('value')]
-
-
-def using_none_app(environ, start_response):
-    extra_args = {}
-    clear = False
-    if environ.get('beaker.clear'):
-        clear = True
-    extra_args['type'] = 'ext:memcached'
-    extra_args['url'] = mc_url
-    extra_args['data_dir'] = './cache'
-    cache = environ['beaker.cache'].get_cache('testcache', **extra_args)
-    if clear:
-        cache.clear()
-    try:
-        value = cache.get_value('value')
-    except:
-        value = 10
-    cache.set_value('value', None)
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    return ['The current value is: %s' % value]
-
-
-def cache_manager_app(environ, start_response):
-    cm = environ['beaker.cache']
-    cm.get_cache('test')['test_key'] = 'test value'
-
-    start_response('200 OK', [('Content-type', 'text/plain')])
-    yield "test_key is: %s\n" % cm.get_cache('test')['test_key']
-    cm.get_cache('test').clear()
-
-    try:
-        test_value = cm.get_cache('test')['test_key']
-    except KeyError:
-        yield "test_key cleared"
-    else:
-        yield "test_key wasn't cleared, is: %s\n" % \
-            cm.get_cache('test')['test_key']
-
-
-def test_session():
-    app = TestApp(SessionMiddleware(simple_session_app, data_dir='./cache', type='ext:memcached', url=mc_url))
-    res = app.get('/')
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    assert 'current value is: 2' in res
-    res = app.get('/')
-    assert 'current value is: 3' in res
-
-
-def test_session_invalid():
-    app = TestApp(SessionMiddleware(simple_session_app, data_dir='./cache', type='ext:memcached', url=mc_url))
-    res = app.get('/invalid', headers=dict(Cookie='beaker.session.id=df7324911e246b70b5781c3c58328442; Path=/'))
-    assert 'current value is: 2' in res
-
-
-def test_has_key():
-    cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached')
-    o = object()
-    cache.set_value("test", o)
-    assert cache.has_key("test")
-    assert "test" in cache
-    assert not cache.has_key("foo")
-    assert "foo" not in cache
-    cache.remove_value("test")
-    assert not cache.has_key("test")
-
-def test_dropping_keys():
-    cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached')
-    cache.set_value('test', 20)
-    cache.set_value('fred', 10)
-    assert cache.has_key('test')
-    assert 'test' in cache
-    assert cache.has_key('fred')
-    
-    # Directly nuke the actual key, to simulate it being removed by memcached
-    cache.namespace.mc.delete('test_test')
-    assert not cache.has_key('test')
-    assert cache.has_key('fred')
-    
-    # Nuke the keys dict, it might die, who knows
-    cache.namespace.mc.delete('test:keys')
-    assert cache.has_key('fred')
-    
-    # And we still need clear to work, even if it won't work well
-    cache.clear()
-
-def test_deleting_keys():
-    cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached')
-    cache.set_value('test', 20)
-    
-    # Nuke the keys dict, it might die, who knows
-    cache.namespace.mc.delete('test:keys')
-    
-    assert cache.has_key('test')
-    
-    # make sure we can still delete keys even though our keys dict got nuked
-    del cache['test']
-    
-    assert not cache.has_key('test')
-
-def test_has_key_multicache():
-    cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached')
-    o = object()
-    cache.set_value("test", o)
-    assert cache.has_key("test")
-    assert "test" in cache
-    cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached')
-    assert cache.has_key("test")
-
-def test_unicode_keys():    
-    cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached')
-    o = object()
-    cache.set_value(u'hiŏ', o)
-    assert u'hiŏ' in cache
-    assert u'hŏa' not in cache
-    cache.remove_value(u'hiŏ')
-    assert u'hiŏ' not in cache
-
-def test_spaces_in_unicode_keys():    
-    cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached')
-    o = object()
-    cache.set_value(u'hi ŏ', o)
-    assert u'hi ŏ' in cache
-    assert u'hŏa' not in cache
-    cache.remove_value(u'hi ŏ')
-    assert u'hi ŏ' not in cache
-
-def test_spaces_in_keys():
-    cache = Cache('test', data_dir='./cache', url=mc_url, type='ext:memcached')
-    cache.set_value("has space", 24)
-    assert cache.has_key("has space")
-    assert 24 == cache.get_value("has space")
-    cache.set_value("hasspace", 42)
-    assert cache.has_key("hasspace")
-    assert 42 == cache.get_value("hasspace")
-
-def test_increment():
-    app = TestApp(CacheMiddleware(simple_app))
-    res = app.get('/', extra_environ={'beaker.clear':True})
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    assert 'current value is: 2' in res
-    res = app.get('/')
-    assert 'current value is: 3' in res
-    
-    app = TestApp(CacheMiddleware(simple_app))
-    res = app.get('/', extra_environ={'beaker.clear':True})
-    assert 'current value is: 1' in res
-    res = app.get('/')
-    assert 'current value is: 2' in res
-    res = app.get('/')
-    assert 'current value is: 3' in res
-
-def test_cache_manager():
-    app = TestApp(CacheMiddleware(cache_manager_app))
-    res = app.get('/')
-    assert 'test_key is: test value' in res
-    assert 'test_key cleared' in res
-
-def test_store_none():
-    app = TestApp(CacheMiddleware(using_none_app))
-    res = app.get('/', extra_environ={'beaker.clear':True})
-    assert 'current value is: 10' in res
-    res = app.get('/')
-    assert 'current value is: None' in res

+ 0 - 149
desktop/core/ext-py/Beaker/tests/test_syncdict.py

@@ -1,149 +0,0 @@
-from beaker.util import SyncDict, WeakValuedRegistry
-import gc, random, sys, time, weakref
-
-# this script tests SyncDict for its thread safety, 
-# ability to always return a value even for a dictionary 
-# that loses data randomly,  and
-# insures that when used as a registry, only one instance
-# of a particular key/value exists at any one time.
-
-import thread
-    
-jython = sys.platform.startswith('java')
-
-def collect():
-    """The tests assume CPython GC behavior in regard to weakrefs, but
-    we can coerce Jython into passing by triggering GC when we expect
-    it to have happened on CPython
-    """
-    if jython:
-        gc.collect()
-
-
-class item:
-    
-    def __init__(self, id):
-        self.id = id
-        
-    def __str__(self):
-        return "item id %d" % self.id
-
-# keep running indicator
-running = False
-
-# one item is referenced at a time (to insure singleton pattern)
-theitem = weakref.ref(item(0))
-
-# creation func entrance detector to detect non-synchronized access
-# to the create function
-baton = None
-
-
-def create(id):
-    global baton
-    assert baton is None, "baton is not none !"
-
-    baton = True
-    try:    
-        global theitem
-        collect()
-        
-        assert theitem() is None, "create %d old item is still referenced" % id
-            
-        i = item(id)
-        theitem = weakref.ref(i)
-
-        global totalcreates
-        totalcreates += 1
-
-        return i
-    finally:
-        baton = None
-        
-def threadtest(s, id, statusdict):
-    print "create thread %d starting" % id
-    statusdict[id] = True
-
-    try:
-        global running
-        global totalgets
-        try:
-            while running:
-                s.get('test', lambda: create(id))
-                totalgets += 1
-                time.sleep(random.random() * .00001)
-        except:
-            e = sys.exc_info()[0]
-            running = False
-            print e
-    finally:
-        print "create thread %d exiting" % id
-        statusdict[id] = False
-
-def runtest(s):
-
-    statusdict = {}
-    global totalcreates
-    totalcreates = 0
-
-    global totalremoves
-    totalremoves = 0
-
-    global totalgets
-    totalgets = 0
-
-    global running
-    running = True    
-    for t in range(1, 10):
-        thread.start_new_thread(threadtest, (s, t, statusdict))
-        
-    time.sleep(1)
-    
-    for x in range (0,10):
-        if not running:
-            break
-        print "Removing item"
-        try: 
-            del s['test']
-            totalremoves += 1
-        except KeyError:
-            pass
-        sleeptime = random.random() * .89
-        time.sleep(sleeptime)
-
-    failed = not running
-
-    running = False
-
-    pause = True
-    while pause:
-        time.sleep(1)    
-        pause = False
-        for v in statusdict.values():
-            if v:
-                pause = True
-                break
-
-    if failed:
-        raise Exception("test failed")
-
-    print "total object creates %d" % totalcreates
-    print "total object gets %d" % totalgets
-    print "total object removes %d" % totalremoves
-
-    
-def test_dict():
-    # normal dictionary test, where we will remove the value
-    # periodically. the number of creates should be equal to
-    # the number of removes plus one.    
-    collect()
-    print "\ntesting with normal dict"
-    runtest(SyncDict())
-
-    assert(totalremoves + 1 == totalcreates)
-
-
-def test_weakdict():
-    collect()
-    print "\ntesting with weak dict"
-    runtest(WeakValuedRegistry())

+ 0 - 23
desktop/core/ext-py/Beaker/tests/test_synchronizer.py

@@ -1,23 +0,0 @@
-from beaker.synchronization import *
-
-# TODO: spawn threads, test locking.
-
-
-def test_reentrant_file():
-    sync1 = file_synchronizer('test', lock_dir='./')
-    sync2 = file_synchronizer('test', lock_dir='./')
-    sync1.acquire_write_lock()
-    sync2.acquire_write_lock()
-    sync2.release_write_lock()
-    sync1.release_write_lock()
-
-def test_null():
-    sync = null_synchronizer()
-    assert sync.acquire_write_lock()
-    sync.release_write_lock()
-    
-def test_mutex():
-    sync = mutex_synchronizer('someident')
-    sync.acquire_write_lock()
-    sync.release_write_lock()
-        

+ 0 - 32
desktop/core/ext-py/Twisted/INSTALL

@@ -1,32 +0,0 @@
-Requirements
-
-  Python 2.3 or later.
-
-  Zope Interfaces 3.0.1 (http://zope.org/Products/ZopeInterface) - if
-  you have ZopeX3 (at least version 3.0.0c1) installed that should
-  work too.
-
-  On Windows pywin32 is recommended (this is built in to ActivePython,
-  so no need to reinstall if you use it instead of standard Python)
-      http://sourceforge.net/project/showfiles.php?group_id=78018
-  The Windows IOCP reactor requires pywin32 build 205 or later.
-
-Installation
-
-  * Debian and Ubuntu
-    Packages are included in the main distribution.
-
-  * FreeBSD, Gentoo
-    Twisted is in their package repositories.
-
-  * Mac OS X
-    Packages are available from http://twistedmatrix.com/
-
-  * Win32
-    EXEs are available from http://twistedmatrix.com/
-
-  * Other
-    As with other Python packages, the standard way of installing from source
-    is:
-
-      python setup.py install

+ 0 - 52
desktop/core/ext-py/Twisted/LICENSE

@@ -1,52 +0,0 @@
-Copyright (c) 2001-2008
-Allen Short
-Andrew Bennetts
-Apple Computer, Inc.
-Benjamin Bruheim
-Bob Ippolito
-Canonical Limited
-Christopher Armstrong
-David Reid
-Donovan Preston
-Eric Mangold
-Itamar Shtull-Trauring
-James Knight
-Jason A. Mobarak
-Jean-Paul Calderone
-Jonathan Lange
-Jonathan D. Simms
-Jürgen Hermann
-Kevin Turner
-Mary Gardiner
-Matthew Lefkowitz
-Massachusetts Institute of Technology
-Moshe Zadka
-Paul Swartz
-Pavel Pergamenshchik
-Ralph Meijer
-Sean Riley
-Software Freedom Conservancy
-Travis B. Hartwell
-Thomas Herve
-Eyal Lotem
-Antoine Pitrou
-Andy Gayton
-
-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.

+ 0 - 766
desktop/core/ext-py/Twisted/NEWS

@@ -1,766 +0,0 @@
-Ticket numbers in this file can be looked up by visiting
-http://twistedmatrix.com/trac/ticket/<number>
-
-Core 8.2.0 (2008-12-16)
-=======================
-
-Features
---------
- - Reactors are slowly but surely becoming more isolated, thus improving
-   testability (#3198)
- - FilePath has gained a realpath method, and FilePath.walk no longer infinitely
-   recurses in the case of a symlink causing a self-recursing filesystem tree
-   (#3098)
- - FilePath's moveTo and copyTo methods now have an option to disable following
-   of symlinks (#3105)
- - Private APIs are now included in the API documentation (#3268)
- - hotshot is now the default profiler for the twistd --profile parameter and
-   using cProfile is now documented (#3355, #3356)
- - Process protocols can now implement a processExited method, which is
-   distinct from processEnded in that it is called immediately when the child
-   has died, instead of waiting for all the file descriptors to be closed
-   (#1291)
- - twistd now has a --umask option (#966, #3024)
- - A new deferToThreadPool function exists in twisted.internet.threads (#2845)
- - There is now an example of writing an FTP server in examples/ftpserver.py
-   (#1579)
- - A new runAsEffectiveUser function has been added to twisted.python.util
-   (#2607)
- - twisted.internet.utils.getProcessOutput now offers a mechanism for
-   waiting for the process to actually end, in the event of data received on
-   stderr (#3239)
- - A fullyQualifiedName function has been added to twisted.python.reflect
-   (#3254)
- - strports now defaults to managing access to a UNIX socket with a lock;
-   lockfile=0 can be included in the strports specifier to disable this
-   behavior (#2295)
- - FTPClient now has a 'rename' method (#3335)
- - FTPClient now has a 'makeDirectory' method (#3500)
- - FTPClient now has a 'removeFile' method (#3491)
- - flushWarnings, A new Trial method for testing warnings, has been added
-   (#3487, #3427, #3506)
- - The log observer can now be configured in .tac files (#3534)
-
-Fixes
------
- - TLS Session Tickets are now disabled by default, allowing connections to
-   certain servers which hang when an empty session ticket is received (like
-   GTalk) (#3463)
- - twisted.enterprise.adbapi.ConnectionPool's noisy attribute now defaults to
-   False, as documented (#1806)
- - Error handling and logging in adbapi is now much improved (#3244)
- - TCP listeners can now be restarted (#2913)
- - Doctests can now be rerun with trial's --until-failure option (#2713)
- - Some memory leaks have been fixed in trial's --until-failure
-   implementation (#3119, #3269)
- - Trial's summary reporter now prints correct runtime information and handles
-   the case of 0 tests (#3184)
- - Trial and any other user of the 'namedAny' function now has better error
-   reporting in the case of invalid module names (#3259)
- - Multiple instances of trial can now run in parallel in the same directory
-   by creating _trial_temp directories with an incremental suffix (#2338)
- - Trial's failUnlessWarns method now works on Python 2.6 (#3223)
- - twisted.python.log now hooks into the warnings system in a way compatible
-   with Python 2.6 (#3211)
- - The GTK2 reactor is now better supported on Windows, but still not passing
-   the entire test suite (#3203)
- - low-level failure handling in spawnProcess has been improved and no longer
-   leaks file descriptors (#2305, #1410)
- - Perspective Broker avatars now have their logout functions called in more
-   cases (#392)
- - Log observers which raise exceptions are no longer removed (#1069)
- - transport.getPeer now always includes an IP address in the Address returned
-   instead of a hostname (#3059)
- - Functions in twisted.internet.utils which spawn processes now avoid calling
-   chdir in the case where no working directory is passed, to avoid some
-   obscure permission errors (#3159)
- - twisted.spread.publish.Publishable no longer corrupts line endings on
-   Windows (#2327)
- - SelectReactor now properly detects when a TLS/TCP connection has been
-   disconnected (#3218)
- - twisted.python.lockfile no longer raises an EEXIST OSError and is much
-   better supported on Windows (#3367)
- - When ITLSTransport.startTLS is called while there is data in the write
-   buffer, TLS negotiation will now be delayed instead of the method raising
-   an exception (#686)
- - The userAnonymous argument to FTPFactory is now honored (#3390)
- - twisted.python.modules no longer tries to "fix" sys.modules after an import
-   error, which was just causing problems (#3388)
- - setup.py no longer attempts to build extension modules when run with Jython
-   (#3410)
- - AMP boxes can now be sent in IBoxReceiver.startReceivingBoxes (#3477)
- - AMP connections are closed as soon as a key length larger than 255 is
-   received (#3478)
- - Log events with timezone offsets between -1 and -59 minutes are now
-   correctly reported as negative (#3515)
-
-Deprecations and Removals
--------------------------
- - Trial's setUpClass and tearDownClass methods are now deprecated (#2903)
- - problemsFromTransport has been removed in favor of the argument passed to
-   connectionLost (#2874)
- - The mode parameter to methods of IReactorUNIX and IReactorUNIXDatagram are
-   deprecated in favor of applications taking other security precautions, since
-   the mode of a Unix socket is often not respected (#1068)
- - Index access on instances of twisted.internet.defer.FirstError has been
-   removed in favor of the subFailure attribute (#3298)
- - The 'changeDirectory' method of FTPClient has been deprecated in favor of
-   the 'cwd' method (#3491)
-
-Other
------
-
- - #3202, #2869, #3225, #2955, #3237, #3196, #2355, #2881, #3054, #2374, #2918,
-   #3210, #3052, #3267, #3288, #2985, #3295, #3297, #2512, #3302, #1222, #2631,
-   #3306, #3116, #3215, #1489, #3319, #3320, #3321, #1255, #2169, #3182, #3323,
-   #3301, #3318, #3029, #3338, #3346, #1144, #3173, #3165, #685, #3357, #2582,
-   #3370, #2438, #1253, #637, #1971, #2208, #979, #1790, #1888, #1882, #1793,
-   #754, #1890, #1931, #1246, #1025, #3177, #2496, #2567, #3400, #2213, #2027,
-   #3415, #1262, #3422, #2500, #3414, #3045, #3111, #2974, #2947, #3222, #2878,
-   #3402, #2909, #3423, #1328, #1852, #3382, #3393, #2029, #3489, #1853, #2026,
-   #2375, #3502, #3482, #3504, #3505, #3507, #2605, #3519, #3520, #3121, #3484,
-   #3439, #3216, #3511, #3524, #3521, #3197, #2486, #2449, #2748, #3381, #3236,
-   #671
-
-
-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
-
-
-Lore 8.2.0 (2008-12-16)
-=======================
-
-Other
------
- - #2207, #2514
-
-
-Mail 8.2.0 (2008-12-16)
-=======================
-
-Fixes
------
- - The mailmail tool now provides better error messages for usage errors (#3339)
- - The SMTP protocol implementation now works on PyPy (#2976)
-
-Other
------
- - #3475
-
-
-Names 8.2.0 (2008-12-16)
-========================
-
-Features
---------
- - The NAPTR record type is now supported (#2276)
-
-Fixes
------
- - Make client.Resolver less vulnerable to the Birthday Paradox attack by
-   avoiding sending duplicate queries when it's not necessary (#3347)
- - client.Resolver now uses a random source port for each DNS request (#3342)
- - client.Resolver now uses a full 16 bits of randomness for message IDs,
-   instead of 10 which it previously used (#3342)
- - All record types now have value-based equality and a string representation
-   (#2935)
-
-Other
------
- - #1622, #3424
-
-
-Web 8.2.0 (2008-12-16)
-======================
-
-Features
---------
- - The web server can now deal with multi-value headers in the new attributes of
-   Request, requestHeaders and responseHeaders (#165)
- - There is now a resource-wrapper which implements HTTP Basic and Digest auth
-   in terms of twisted.cred (#696)
- - It's now possible to limit the number of redirects that client.getPage will
-   follow (#2412)
- - The directory-listing code no longer uses Woven (#3257)
- - static.File now supports Range headers with a single range (#1493)
- - twisted.web now has a rudimentary WSGI container (#2753)
- - The web server now supports chunked encoding in requests (#3385)
-
-Fixes
------
- - The xmlrpc client now raises an error when the server sends an empty
-   response (#3399)
- - HTTPPageGetter no longer duplicates default headers when they're explicitly
-   overridden in the headers parameter (#1382)
- - The server will no longer timeout clients which are still sending request
-   data (#1903)
- - microdom's isEqualToNode now returns False when the nodes aren't equal
-   (#2542)
-
-Deprecations and Removals
--------------------------
-
- - Request.headers and Request.received_headers are not quite deprecated, but
-   they are discouraged in favor of requestHeaders and responseHeaders (#165)
-
-Other
------
- - #909, #687, #2938, #1152, #2930, #2025, #2683, #3471
-
-
-Web2 8.2.0 (2008-12-16)
-=======================
-
-Note: Twisted Web2 is being phased out in preference for Twisted Web, but some
-maintenance changes have been made.
-
-Fixes
------
- - The main twisted.web2 docstring now indicates the current state of the
-   project (#2028)
- - Headers which require unusual bytes are now quoted (#2346)
- - Some links in the introduction documentation have been fixed (#2552)
-
-
-Words 8.2.0 (2008-12-16)
-========================
-
-Feature
--------
- - There is now a standalone XMPP router included in twisted.words: it can be
-   used with the 'twistd xmpp-router' command line (#3407)
- - A server factory for Jabber XML Streams has been added (#3435)
- - Domish now allows for iterating child elements with specific qualified names
-   (#2429)
- - IRCClient now has a 'back' method which removes the away status (#3366)
- - IRCClient now has a 'whois' method (#3133)
-
-Fixes
------
- - The IRC Client implementation can now deal with compound mode changes (#3230)
- - The MSN protocol implementation no longer requires the CVR0 protocol to
-   be included in the VER command (#3394)
- - In the IRC server implementation, topic messages will no longer be sent for
-   a group which has no topic (#2204)
- - An infinite loop (which caused infinite memory usage) in irc.split has been
-   fixed.  This was triggered any time a message that starts with a delimiter
-   was sent (#3446)
- - Jabber's toResponse now generates a valid stanza even when stanzaType is not
-   specified (#3467)
- - The lifetime of authenticator instances in XmlStreamServerFactory is no
-   longer artificially extended (#3464)
-
-Other
------
- - #3365
-
-
-Core 8.1.0 (2008-05-18)
-=======================
-
-Features
---------
-
- - twisted.internet.error.ConnectionClosed is a new exception which is the
-   superclass of ConnectionLost and ConnectionDone (#3137)
- - Trial's CPU and memory performance should be better now (#3034)
- - twisted.python.filepath.FilePath now has a chmod method (#3124)
-
-Fixes
------
-
- - Some reactor re-entrancy regressions were fixed (#3146, #3168)
- - A regression was fixed whereby constructing a Failure for an exception and
-   traceback raised out of a Pyrex extension would fail (#3132)
- - CopyableFailures in PB can again be created from CopiedFailures (#3174)
- - FilePath.remove, when called on a FilePath representing a symlink to a
-   directory, no longer removes the contents of the targeted directory, and
-   instead removes the symlink (#3097)
- - FilePath now has a linkTo method for creating new symlinks (#3122)
- - The docstring for Trial's addCleanup method now correctly specifies when
-   cleanup functions are run (#3131)
- - assertWarns now deals better with multiple identical warnings (#2904)
- - Various windows installer bugs were fixed (#3115, #3144, #3150, #3151, #3164)
- - API links in the howto documentation have been corrected (#3130)
- - The Win32 Process transport object now has a pid attribute (#1836)
- - A doc bug in the twistd plugin howto which would inevitably lead to
-   confusion was fixed (#3183)
- - A regression breaking IOCP introduced after the last release was fixed
-   (#3200)
-
-Deprecations and Removals
--------------------------
-
- - mktap is now fully deprecated, and will emit DeprecationWarnings when used
-   (#3127)
-
-Other
------
- - #3079, #3118, #3120, #3145, #3069, #3149, #3186, #3208, #2762
-
-
-Conch 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)
-
-
-Lore 8.1.0 (2008-05-18)
-=======================
-
-Fixes
------
- - The deprecated mktap API is no longer used (#3127)
-
-
-News 8.1.0 (2008-05-18)
-=======================
-
-Fixes
------
- - The deprecated mktap API is no longer used (#3127)
-
-
-Web 8.1.0 (2008-05-18)
-======================
-
-Fixes
------
- - Fixed an XMLRPC bug whereby sometimes a callRemote Deferred would
-   accidentally be fired twice when a connection was lost during the handling of
-   a response (#3152)
- - Fixed a bug in the "Using Twisted Web" document which prevented an example
-   resource from being renderable (#3147)
- - The deprecated mktap API is no longer used (#3127)
-
-
-Words 8.1.0 (2008-05-18)
-========================
-
-Features
---------
- - JID objects now have a nice __repr__ (#3156)
- - Extending XMPP protocols is now easier (#2178)
-
-Fixes
------
- - The deprecated mktap API is no longer used (#3127)
- - A bug whereby one-time XMPP observers would be enabled permanently was fixed
-   (#3066)
-
-
-Mail 8.1.0 (2008-05-18)
-=======================
-
-Fixes
------
- - The deprecated mktap API is no longer used (#3127)
-
-
-Names 8.1.0 (2008-05-18)
-========================
-
-Fixes
------
- - The deprecated mktap API is no longer used (#3127)
-
-
-Web2 8.1.0 (2008-05-18)
-=======================
-
-Fixes
------
- - The deprecated mktap API is no longer used (#3127)
-
-
-Core 8.0.1 (2008-03-26)
-=======================
-
-Fixes
------
- - README no longer refers to obsolete trial command line option
- - twistd no longer causes a bizarre DeprecationWarning about mktap
-
-
-Core 8.0.0 (2008-03-17)
-=======================
-
-Features
---------
-
- - The IOCP reactor has had many changes and is now greatly improved
-   (#1760, #3055)
- - The main Twisted distribution is now easy_installable (#1286, #3110)
- - twistd can now profile with cProfile (#2469)
- - twisted.internet.defer contains a DeferredFilesystemLock which gives a
-   Deferred interface to lock file acquisition (#2180)
- - twisted.python.modules is a new system for representing and manipulating
-   module paths (i.e. sys.path) (#1951)
- - twisted.internet.fdesc now contains a writeToFD function, along with other
-   minor fixes (#2419)
- - twisted.python.usage now allows optional type enforcement (#739)
- - The reactor now has a blockingCallFromThread method for non-reactor threads
-   to use to wait for a reactor-scheduled call to return a result (#1042, #3030)
- - Exceptions raised inside of inlineCallbacks-using functions now have a
-   better chance of coming with a meaningful traceback (#2639, #2803)
- - twisted.python.randbytes now contains code for generating secure random
-   bytes (#2685)
- - The classes in twisted.application.internet now accept a reactor parameter
-   for specifying the reactor to use for underlying calls to allow for better
-   testability (#2937)
- - LoopingCall now allows you to specify the reactor to use to schedule new
-   calls, allowing much better testing techniques (#2633, #2634)
- - twisted.internet.task.deferLater is a new API for scheduling calls and
-   getting deferreds which are fired with their results (#1875)
- - objgrep now knows how to search through deque objects (#2323)
- - twisted.python.log now contains a Twisted log observer which can forward
-   messages to the Python logging system (#1351)
- - Log files now include seconds in the timestamps (#867)
- - It is now possible to limit the number of log files to create during log
-   rotation (#1095)
- - The interface required by the log context system is now documented as
-   ILoggingContext, and abstract.FileDescriptor now declares that it implements
-   it (#1272)
- - There is now an example cred checker that uses a database via adbapi (#460)
- - The epoll reactor is now documented in the choosing-reactors howto (#2539)
- - There were improvements to the client howto (#222)
- - Int8Receiver was added (#2315)
- - Various refactorings to AMP introduced better testability and public
-   interfaces (#2657, #2667, #2656, #2664, #2810)
- - twisted.protocol.policies.TrafficLoggingFactory now has a resetCounter
-   method (#2757)
- - The FTP client can be told which port range within which to bind passive
-   transfer ports (#1904)
- - twisted.protocols.memcache contains a new asynchronous memcache client
-   (#2506, #2957)
- - PB now supports anonymous login (#439, #2312)
- - twisted.spread.jelly now supports decimal objects (#2920)
- - twisted.spread.jelly now supports all forms of sets (#2958)
- - There is now an interface describing the API that process protocols must
-   provide (#3020)
- - Trial reporting to core unittest TestResult objects has been improved (#2495)
- - Trial's TestCase now has an addCleanup method which allows easy setup of
-   tear-down code (#2610, #2899)
- - Trial's TestCase now has an assertIsInstance method (#2749)
- - Trial's memory footprint and speed are greatly improved (#2275)
- - At the end of trial runs, "PASSED" and "FAILED" messages are now colorized
-   (#2856)
- - Tests which leave global state around in the reactor will now fail in
-   trial. A new option, --unclean-warnings, will convert these errors back into
-   warnings (#2091)
- - Trial now has a --without-module command line for testing code in an
-   environment that lacks a particular Python module (#1795)
- - Error reporting of failed assertEquals assertions now has much nicer
-   formatting (#2893)
- - Trial now has methods for monkey-patching (#2598)
- - Trial now has an ITestCase (#2898, #1950)
- - The trial reporter API now has a 'done' method which is called at the end of
-   a test run (#2883)
- - TestCase now has an assertWarns method which allows testing that functions
-   emit warnings (#2626, #2703)
- - There are now no string exceptions in the entire Twisted code base (#2063)
- - There is now a system for specifying credentials checkers with a string
-   (#2570)
-
-Fixes
------
-
- - Some tests which were asserting the value of stderr have been changed
-   because Python uncontrollably writes bytes to stderr (#2405)
- - Log files handle time zones with DST better (#2404)
- - Subprocesses using PTYs on OS X that are handled by Twisted will now be able
-   to more reliably write the final bytes before they exit, allowing Twisted
-   code to more reliably receive them (#2371, #2858)
- - Trial unit test reporting has been improved (#1901)
- - The kqueue reactor handles connection failures better (#2172)
- - It's now possible to run "trial foo/bar/" without an exception: trailing
-   slashes no longer cause problems (#2005)
- - cred portals now better deal with implementations of inherited interfaces
-   (#2523)
- - FTP error handling has been improved (#1160, 1107)
- - Trial behaves better with respect to file locking on Windows (#2482)
- - The FTP server now gives a better error when STOR is attempted during an
-   anonymous session (#1575)
- - Trial now behaves better with tests that use the reactor's threadpool (#1832)
- - twisted.python.reload now behaves better with new-style objects (#2297)
- - LogFile's defaultMode parameter is now better implemented, preventing
-   potential security exploits (#2586)
- - A minor obscure leak in thread pools was corrected (#1134)
- - twisted.internet.task.Clock now returns the correct DelayedCall from
-   callLater, instead of returning the one scheduled for the furthest in the
-   future (#2691)
- - twisted.spread.util.FilePager no longer unnecessarily buffers data in
-   memory (#1843, 2321)
- - Asking for twistd or trial to use an unavailable reactor no longer prints a
-   traceback (#2457)
- - System event triggers have fewer obscure bugs (#2509)
- - Plugin discovery code is much better behaved, allowing multiple
-   installations of a package with plugins (#2339, #2769)
- - Process and PTYProcess have been merged and some minor bugs have been fixed
-   (#2341)
- - The reactor has less global state (#2545)
- - Failure can now correctly represent and format errors caused by string
-   exceptions (#2830)
- - The epoll reactor now has better error handling which now avoids the bug
-   causing 100% CPU usage in some cases (#2809)
- - Errors raised during trial setUp or tearDown methods are now handled better
-   (#2837)
- - A problem when deferred callbacks add new callbacks to the deferred that
-   they are a callback of was fixed (#2849)
- - Log messages that are emitted during connectionMade now have the protocol
-   prefix correctly set (#2813)
- - The string representation of a TCP Server connection now contains the actual
-   port that it's bound to when it was configured to listen on port 0 (#2826)
- - There is better reporting of error codes for TCP failures on Windows (#2425)
- - Process spawning has been made slightly more robust by disabling garbage
-   collection temporarily immediately after forking so that finalizers cannot
-   be executed in an unexpected environment (#2483)
- - namedAny now detects import errors better (#698)
- - Many fixes and improvements to the twisted.python.zipstream module have
-   been made (#2996)
- - FilePager no longer blows up on empty files (#3023)
- - twisted.python.util.FancyEqMixin has been improved to cooperate with objects
-   of other types (#2944)
- - twisted.python.FilePath.exists now restats to prevent incorrect result
-   (#2896)
- - twisted.python.util.mergeFunctionMetadata now also merges the __module__
-   attribute (#3049)
- - It is now possible to call transport.pauseProducing within connectionMade on
-   TCP transports without it being ignored (#1780)
- - twisted.python.versions now understands new SVN metadata format for fetching
-   the SVN revision number (#3058)
- - It's now possible to use reactor.callWhenRunning(reactor.stop) on gtk2 and
-   glib2 reactors (#3011)
-
-Deprecations and removals
--------------------------
- - twisted.python.timeoutqueue is now deprecated (#2536)
- - twisted.enterprise.row and twisted.enterprise.reflector are now deprecated
-   (#2387)
- - twisted.enterprise.util is now deprecated (#3022)
- - The dispatch and dispatchWithCallback methods of ThreadPool are now
-   deprecated (#2684)
- - Starting the same reactor multiple times is now deprecated (#1785)
- - The visit method of various test classes in trial has been deprecated (#2897)
- - The --report-profile option to twistd and twisted.python.dxprofile are
-   deprecated (#2908)
- - The upDownError method of Trial reporters is deprecated (#2883)
-
-Other
------
-
- - #2396, #2211, #1921, #2378, #2247, #1603, #2463, #2530, #2426, #2356, #2574,
- - #1844, #2575, #2655, #2640, #2670, #2688, #2543, #2743, #2744, #2745, #2746,
- - #2742, #2741, #1730, #2831, #2216, #1192, #2848, #2767, #1220, #2727, #2643,
- - #2669, #2866, #2867, #1879, #2766, #2855, #2547, #2857, #2862, #1264, #2735,
- - #942, #2885, #2739, #2901, #2928, #2954, #2906, #2925, #2942, #2894, #2793,
- - #2761, #2977, #2968, #2895, #3000, #2990, #2919, #2969, #2921, #3005, #421,
- - #3031, #2940, #1181, #2783, #1049, #3053, #2847, #2941, #2876, #2886, #3086,
- - #3095, #3109
-
-
-Conch 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
-
-
-Lore 8.0.0 (2008-03-17)
-=======================
-
-Fixes
------
- - Change twisted.lore.tree.setIndexLin so that it removes node with index-link
-   class when the specified index filename is None. (#812)
- - Fix the conversion of the list of options in man pages to Lore format.
-   (#3017)
- - Fix conch man pages generation. (#3075)
- - Fix management of the interactive command tag in man2lore. (#3076)
-
-Misc
-----
- - #2847
-
-
-News 8.0.0 (2008-03-17)
-=======================
-
-Misc
-----
- - Remove all "API Stability" markers (#2847)
-
-
-Runner 8.0.0 (2008-03-17)
-=========================
-
-Misc
-----
- - Remove all "API Stability" markers (#2847)
-
-
-Web 8.0.0 (2008-03-17)
-======================
-
-Features
---------
- - Add support to twisted.web.client.getPage for the HTTP HEAD method. (#2750)
-
-Fixes
------
- - Set content-type in xmlrpc responses to "text/xml" (#2430)
- - Add more error checking in the xmlrpc.XMLRPC render method, and enforce
-   POST requests. (#2505)
- - Reject unicode input to twisted.web.client._parse to reject invalid
-   unicode URLs early. (#2628)
- - Correctly re-quote URL path segments when generating an URL string to
-   return from Request.prePathURL. (#2934)
- - Make twisted.web.proxy.ProxyClientFactory close the connection when
-   reporting a 501 error. (#1089)
- - Fix twisted.web.proxy.ReverseProxyResource to specify the port in the
-   host header if different from 80. (#1117)
- - Change twisted.web.proxy.ReverseProxyResource so that it correctly encodes
-   the request URI it sends on to the server for which it is a proxy. (#3013)
- - Make "twistd web --personal" use PBServerFactory (#2681)
-
-Misc
-----
- - #1996, #2382, #2211, #2633, #2634, #2640, #2752, #238, #2905
-
-
-Words 8.0.0 (2008-03-17)
-========================
-
-Features
---------
- - Provide function for creating XMPP response stanzas. (#2614, #2614)
- - Log exceptions raised in Xish observers. (#2616)
- - Add 'and' and 'or' operators for Xish XPath expressions. (#2502)
- - Make JIDs hashable. (#2770)
-
-Fixes
------
- - Respect the hostname and servername parameters to IRCClient.register. (#1649)
- - Make EventDispatcher remove empty callback lists. (#1652)
- - Use legacy base64 API to support Python 2.3 (#2461)
- - Fix support of DIGEST-MD5 challenge parsing with multi-valued directives.
-   (#2606)
- - Fix reuse of dict of prefixes in domish.Element.toXml (#2609)
- - Properly process XMPP stream headers (#2615)
- - Use proper namespace for XMPP stream errors. (#2630)
- - Properly parse XMPP stream errors. (#2771)
- - Fix toResponse for XMPP stanzas without an id attribute. (#2773)
- - Move XMPP stream header procesing to authenticators. (#2772)
-
-Misc
-----
- - #2617, #2640, #2741, #2063, #2570, #2847
-
-
-Mail 8.0.0 (2008-03-17)
-=======================
-
-Features
---------
- - Support CAPABILITY responses that include atoms of the form "FOO" and
-   "FOO=BAR" in IMAP4 (#2695)
- - Parameterize error handling behavior of imap4.encoder and imap4.decoder.
-   (#2929)
-
-Fixes
------
- - Handle empty passwords in SMTP auth. (#2521)
- - Fix IMAP4Client's parsing of literals which are not preceeded by whitespace.
-   (#2700)
- - Handle MX lookup suceeding without answers. (#2807)
- - Fix issues with aliases(5) process support. (#2729)
-
-Misc
-----
- - #2371, #2123, #2378, #739, #2640, #2746, #1917, #2266, #2864, #2832, #2063,
-   #2865, #2847
-
-
-Names 8.0.0 (2008-03-17)
-========================
-
-Fixes
------
-
- - Refactor DNSDatagramProtocol and DNSProtocol to use same base class (#2414)
- - Change Resolver to query specified nameservers in specified order, instead
-   of reverse order. (#2290)
- - Make SRVConnector work with bad results and NXDOMAIN responses.
-   (#1908, #2777)
- - Handle write errors happening in dns queries, to have correct deferred
-   failures. (#2492)
- - Fix the value of OP_NOTIFY and add a definition for OP_UPDATE. (#2945)
-
-Misc
-----
- - #2685, #2936, #2581, #2847
-

+ 0 - 116
desktop/core/ext-py/Twisted/README

@@ -1,116 +0,0 @@
-Twisted 8.2.0
-
-Quote of the Release:
-
-  <itamar> exarkun: how exactly are you approaching the web2/web tickets?
-  <exarkun> three man teams, radio silence, weapons-free rules of engagement
-
-For information on what's new in Twisted 8.2.0, see the NEWS file that
-comes with the distribution.
-
-What is this?
-=============
-
-  Twisted is an event-based framework for internet applications which works on
-  Python 2.3 through 2.6.  The following are some of the modules included
-  with Twisted::
-
-  - twisted.application
-    A "Service" system that allows you to organize your application in
-    hierarchies with well-defined startup and dependency semantics,
-  - twisted.cred
-    A general credentials and authentication system that facilitates
-    pluggable authentication backends,
-  - twisted.enterprise
-    Asynchronous database access, compatible with any Python DBAPI2.0
-    modules,
-  - twisted.internet
-    Low-level asynchronous networking APIs that allow you to define
-    your own protocols that run over certain transports,
-  - twisted.manhole
-    A tool for remote debugging of your services which gives you a
-    Python interactive interpreter,
-  - twisted.protocols
-    Basic protocol implementations and helpers for your own protocol
-    implementations,
-  - twisted.python
-    A large set of utilities for Python tricks, reflection, text
-    processing, and anything else,
-  - twisted.spread
-    A secure, fast remote object system,
-  - twisted.trial
-    A unit testing framework that integrates well with Twisted-based code.
-
-  Twisted supports integration of the Tk, GTK+, GTK+ 2, Qt, Mac OS X,
-  or wxPython event loop with its main event loop. The Win32 event
-  loop is also supported.
-
-  For more information, visit http://www.twistedmatrix.com, or join the list
-  at http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
-
-  There are many official Twisted subprojects, including clients and
-  servers for web, mail, DNS, and more. You can find out more about
-  these projects at http://twistedmatrix.com/trac/wiki/TwistedProjects
-
-
-Installing
-==========
-
-  Instructions for installing this software are in INSTALL.
-
-Unit Tests
-==========
-
-
-  See our unit tests run proving that the software is BugFree(TM)::
-
-   % trial twisted
-
-  Some of these tests may fail if you
-   * don't have the dependancies required for a particular subsystem installed,
-   * have a firewall blocking some ports (or things like Multicast, which Linux
-     NAT has shown itself to do), or
-   * run them as root.
-
-
-Documentation and Support
-=========================
-
-  Examples on how to use Twisted APIs are located in doc/examples;
-  this might ease the learning curve a little bit, since all these
-  files are kept as short as possible.  The file doc/howto/index.xhtml
-  contains an index of all the HOWTOs: this should be your starting
-  point when looking for documentation.
-
-  Help is available on the Twisted mailing list::
-
-    http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python
-  
-  There is also a very lively IRC channel, #twisted, on
-  irc.freenode.net.
-
-
-Copyright
-=========
-
-  All of the code in this distribution is Copyright (c) 2001-2008
-  Twisted Matrix Laboratories.
-
-  Twisted is made available under the MIT license. The included
-  LICENSE file describes this in detail.
-
-
-Warranty
-========
-
-  THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
-  EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
-  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
-  TO THE USE OF THIS SOFTWARE IS WITH YOU.
-
-  IN NO EVENT WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-  AND/OR REDISTRIBUTE THE LIBRARY, BE LIABLE TO YOU FOR ANY DAMAGES, EVEN IF
-  SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-  DAMAGES.
-
-  Again, see the included LICENSE file for specific legal details.

+ 0 - 21
desktop/core/ext-py/Twisted/bin/conch/cftp

@@ -1,21 +0,0 @@
-#!/usr/bin/env python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-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)
-### end of preamble
-
-from twisted.conch.scripts.cftp import run
-run()

+ 0 - 21
desktop/core/ext-py/Twisted/bin/conch/ckeygen

@@ -1,21 +0,0 @@
-#!/usr/bin/env python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-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)
-### end of preamble
-
-from twisted.conch.scripts.ckeygen import run
-run()

+ 0 - 21
desktop/core/ext-py/Twisted/bin/conch/conch

@@ -1,21 +0,0 @@
-#!/usr/bin/env python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-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)
-### end of preamble
-
-from twisted.conch.scripts.conch import run
-run()

+ 0 - 21
desktop/core/ext-py/Twisted/bin/conch/tkconch

@@ -1,21 +0,0 @@
-#!/usr/bin/python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-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)
-### end of preamble
-
-from twisted.conch.scripts.tkconch import run
-run()

+ 0 - 22
desktop/core/ext-py/Twisted/bin/lore/lore

@@ -1,22 +0,0 @@
-#!/usr/bin/python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-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)
-### end of preamble
-
-from twisted.lore.scripts.lore import run
-run()
-

+ 0 - 24
desktop/core/ext-py/Twisted/bin/mail/mailmail

@@ -1,24 +0,0 @@
-#!/usr/bin/python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""This script attempts to send some email."""
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-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)
-### end of preamble
-
-from twisted.mail.scripts import mailmail
-mailmail.run()
-

+ 0 - 21
desktop/core/ext-py/Twisted/bin/manhole

@@ -1,21 +0,0 @@
-#!/usr/bin/python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""This script runs GtkManhole, a client for Twisted.Manhole
-"""
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-import sys, os, string
-if string.find(os.path.abspath(sys.argv[0]), os.sep+'Twisted') != -1:
-    sys.path.insert(0, os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)))
-### end of preamble
-
-
-from twisted.scripts import manhole
-manhole.run()

+ 0 - 20
desktop/core/ext-py/Twisted/bin/mktap

@@ -1,20 +0,0 @@
-#!/usr/bin/python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-import sys, os, string
-if string.find(os.path.abspath(sys.argv[0]), os.sep+'Twisted') != -1:
-    sys.path.insert(0, os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)))
-if not hasattr(os, "getuid") or os.getuid() != 0:
-    sys.path.insert(0, os.getcwd())
-### end of preamble
-
-from twisted.scripts.mktap import run
-run()
-

+ 0 - 17
desktop/core/ext-py/Twisted/bin/pyhtmlizer

@@ -1,17 +0,0 @@
-#!/usr/bin/python
-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-import sys, os, string
-if string.find(os.path.abspath(sys.argv[0]), os.sep+'Twisted') != -1:
-    sys.path.insert(0, os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)))
-sys.path.insert(0, os.curdir)
-### end of preamble
-
-from twisted.scripts.htmlizer import run
-run()

+ 0 - 19
desktop/core/ext-py/Twisted/bin/tap2deb

@@ -1,19 +0,0 @@
-#!/usr/bin/python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""tap2deb"""
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-import sys, os, string
-if string.find(os.path.abspath(sys.argv[0]), os.sep+'Twisted') != -1:
-    sys.path.insert(0, os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)))
-### end of preamble
-
-from twisted.scripts import tap2deb
-tap2deb.run()

+ 0 - 17
desktop/core/ext-py/Twisted/bin/tap2rpm

@@ -1,17 +0,0 @@
-#!/usr/bin/python
-
-#  based off the tap2deb code
-#  tap2rpm built by Sean Reifschneider, <jafo@tummy.com>
-
-"""tap2rpm"""
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-import sys, os, string
-if string.find(os.path.abspath(sys.argv[0]), os.sep+'Twisted') != -1:
-    sys.path.insert(0, os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)))
-### end of preamble
-
-from twisted.scripts import tap2rpm
-tap2rpm.run()

+ 0 - 19
desktop/core/ext-py/Twisted/bin/tapconvert

@@ -1,19 +0,0 @@
-#!/usr/bin/env python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-import sys, os, string
-if string.find(os.path.abspath(sys.argv[0]), os.sep+'Twisted') != -1:
-    sys.path.insert(0, os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)))
-if not hasattr(os, "getuid") or os.getuid() != 0:
-    sys.path.insert(0, os.getcwd())
-### end of preamble
-
-from twisted.scripts.tapconvert import run
-run()

+ 0 - 24
desktop/core/ext-py/Twisted/bin/trial

@@ -1,24 +0,0 @@
-#!/usr/bin/python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-import sys, os, string
-if string.find(os.path.abspath(sys.argv[0]), os.sep+'Twisted') != -1:
-    sys.path.insert(0, os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)))
-if hasattr(os, "getuid") and os.getuid() != 0:
-    sys.path.insert(0, os.curdir)
-### end of preamble
-
-# begin chdir armor
-sys.path[:] = map(os.path.abspath, sys.path)
-# end chdir armor
-
-from twisted.scripts.trial import run
-run()

+ 0 - 21
desktop/core/ext-py/Twisted/bin/twistd

@@ -1,21 +0,0 @@
-#!/usr/bin/python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-import sys, os, string
-if string.find(os.path.abspath(sys.argv[0]), os.sep+'Twisted') != -1:
-    sys.path.insert(0, os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)))
-if hasattr(os, "getuid") and os.getuid() != 0:
-    sys.path.insert(0, os.path.abspath(os.getcwd()))
-### end of preamble
-
-
-from twisted.scripts.twistd import run
-run()

+ 0 - 22
desktop/core/ext-py/Twisted/bin/words/im

@@ -1,22 +0,0 @@
-#!/usr/bin/python
-
-# Twisted, the Framework of Your Internet
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-### Twisted Preamble
-# This makes sure that users don't have to set up their environment
-# specially in order to run these programs from bin/.
-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)
-### end of preamble
-
-from twisted.words.scripts import im
-im.run()
-

+ 0 - 15
desktop/core/ext-py/Twisted/doc/conch/benchmarks/README

@@ -1,15 +0,0 @@
-This directory contains various simple programs intended to exercise various
-features of Twisted Conch as a way to learn about and track their
-performance characteristics.  As there is currently no record of past
-benchmark results, the tracking aspect of this is currently somewhat
-fantastic.  However, the intent is for this to change at some future point.
-
-All (one) of the programs in this directory are currently intended to be
-invoked directly and to report some timing information on standard out.
-
-The following benchmarks are currently available:
-
-buffering_mixin.py:
-
-    This deals with twisted.conch.mixin.BufferingMixin which provides
-    Nagle-like write coalescing for Protocol classes.

+ 0 - 182
desktop/core/ext-py/Twisted/doc/conch/benchmarks/buffering_mixin.py

@@ -1,182 +0,0 @@
-# Copyright (c) 2006 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Benchmarks comparing the write performance of a "normal" Protocol instance
-and an instance of a Protocol class which has had L{twisted.conch.mixin}'s
-L{BufferingMixin<twisted.conch.mixin.BufferingMixin>} mixed in to perform
-Nagle-like write coalescing.
-"""
-
-from sys import stdout
-from pprint import pprint
-from time import time
-
-from twisted.python.usage import Options
-from twisted.python.log import startLogging
-
-from twisted.internet.protocol import ServerFactory, Protocol, ClientCreator
-from twisted.internet.defer import Deferred
-from twisted.internet import reactor
-
-from twisted.conch.mixin import BufferingMixin
-
-
-class BufferingBenchmark(Options):
-    """
-    Options for configuring the execution parameters of a benchmark run.
-    """
-
-    optParameters = [
-        ('scale', 's', '1',
-         'Work multiplier (bigger takes longer, might resist noise better)')]
-
-    def postOptions(self):
-        self['scale'] = int(self['scale'])
-
-
-
-class ServerProtocol(Protocol):
-    """
-    A silent protocol which only waits for a particular amount of input and
-    then fires a Deferred.
-    """
-    def __init__(self, expected, finished):
-        self.expected = expected
-        self.finished = finished
-
-
-    def dataReceived(self, bytes):
-        self.expected -= len(bytes)
-        if self.expected == 0:
-            finished, self.finished = self.finished, None
-            finished.callback(None)
-
-
-
-class BufferingProtocol(Protocol, BufferingMixin):
-    """
-    A protocol which uses the buffering mixin to provide a write method.
-    """
-
-
-
-class UnbufferingProtocol(Protocol):
-    """
-    A protocol which provides a naive write method which simply passes through
-    to the transport.
-    """
-
-    def connectionMade(self):
-        """
-        Bind write to the transport's write method and flush to a no-op
-        function in order to provide the same API as is provided by
-        BufferingProtocol.
-        """
-        self.write = self.transport.write
-        self.flush = lambda: None
-
-
-
-def _write(proto, byteCount):
-    write = proto.write
-    flush = proto.flush
-
-    for i in range(byteCount):
-        write('x')
-    flush()
-
-
-
-def _benchmark(byteCount, clientProtocol):
-    result = {}
-    finished = Deferred()
-    def cbFinished(ignored):
-        result[u'disconnected'] = time()
-        result[u'duration'] = result[u'disconnected'] - result[u'connected']
-        return result
-    finished.addCallback(cbFinished)
-
-    f = ServerFactory()
-    f.protocol = lambda: ServerProtocol(byteCount, finished)
-    server = reactor.listenTCP(0, f)
-
-    f2 = ClientCreator(reactor, clientProtocol)
-    proto = f2.connectTCP('127.0.0.1', server.getHost().port)
-    def connected(proto):
-        result[u'connected'] = time()
-        return proto
-    proto.addCallback(connected)
-    proto.addCallback(_write, byteCount)
-    return finished
-
-
-
-def _benchmarkBuffered(byteCount):
-    return _benchmark(byteCount, BufferingProtocol)
-
-
-
-def _benchmarkUnbuffered(byteCount):
-    return _benchmark(byteCount, UnbufferingProtocol)
-
-
-
-def benchmark(scale=1):
-    """
-    Benchmark and return information regarding the relative performance of a
-    protocol which does not use the buffering mixin and a protocol which
-    does.
-
-    @type scale: C{int}
-    @param scale: A multipler to the amount of work to perform
-
-    @return: A Deferred which will fire with a dictionary mapping each of
-    the two unicode strings C{u'buffered'} and C{u'unbuffered'} to
-    dictionaries describing the performance of a protocol of each type. 
-    These value dictionaries will map the unicode strings C{u'connected'}
-    and C{u'disconnected'} to the times at which each of those events
-    occurred and C{u'duration'} two the difference between these two values.
-    """
-    overallResult = {}
-
-    byteCount = 1024
-
-    bufferedDeferred = _benchmarkBuffered(byteCount * scale)
-    def didBuffered(bufferedResult):
-        overallResult[u'buffered'] = bufferedResult
-        unbufferedDeferred =  _benchmarkUnbuffered(byteCount * scale)
-        def didUnbuffered(unbufferedResult):
-            overallResult[u'unbuffered'] = unbufferedResult
-            return overallResult
-        unbufferedDeferred.addCallback(didUnbuffered)
-        return unbufferedDeferred
-    bufferedDeferred.addCallback(didBuffered)
-    return bufferedDeferred
-
-
-
-def main(args=None):
-    """
-    Perform a single benchmark run, starting and stopping the reactor and
-    logging system as necessary.
-    """
-    startLogging(stdout)
-
-    options = BufferingBenchmark()
-    options.parseOptions(args)
-
-    d = benchmark(options['scale'])
-    def cbBenchmark(result):
-        pprint(result)
-    def ebBenchmark(err):
-        print err.getTraceback()
-    d.addCallbacks(cbBenchmark, ebBenchmark)
-    def stopReactor(ign):
-        reactor.stop()
-    d.addBoth(stopReactor)
-    reactor.run()
-
-
-if __name__ == '__main__':
-    main()

+ 0 - 25
desktop/core/ext-py/Twisted/doc/conch/examples/demo.tac

@@ -1,25 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-# You can run this .tac file directly with:
-#    twistd -ny demo.tac
-
-"""Nearly pointless demonstration of the manhole interactive interpreter.
-
-This does about the same thing as demo_manhole, but uses the tap
-module's makeService method instead.  The only interesting difference
-is that in this version, the telnet server also requires
-authentication.
-
-Note, you will have to create a file named \"passwd\" and populate it
-with credentials (in the format of passwd(5)) to use this demo.
-"""
-
-from twisted.application import service
-application = service.Application("TAC Demo")
-
-from twisted.conch import manhole_tap
-manhole_tap.makeService({"telnetPort": "tcp:6023",
-                         "sshPort": "tcp:6022",
-                         "namespace": {"foo": "bar"},
-                         "passwd": "passwd"}).setServiceParent(application)

+ 0 - 80
desktop/core/ext-py/Twisted/doc/conch/examples/demo_draw.tac

@@ -1,80 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-# You can run this .tac file directly with:
-#    twistd -ny demo_draw.tac
-
-"""A trivial drawing application.
-
-Clients are allowed to connect and spew various characters out over
-the terminal.  Spacebar changes the drawing character, while the arrow
-keys move the cursor.
-"""
-
-from twisted.conch.insults import insults
-from twisted.conch.telnet import TelnetTransport, TelnetBootstrapProtocol
-from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
-
-from twisted.internet import protocol
-from twisted.application import internet, service
-from twisted.cred import checkers, portal
-
-class Draw(insults.TerminalProtocol):
-    """Protocol which accepts arrow key and spacebar input and places
-    the requested characters onto the terminal.
-    """
-    cursors = list('!@#$%^&*()_+-=')
-
-    def connectionMade(self):
-        self.terminal.eraseDisplay()
-        self.terminal.resetModes([insults.IRM])
-        self.cursor = self.cursors[0]
-
-    def keystrokeReceived(self, keyID, modifier):
-        if keyID == self.terminal.UP_ARROW:
-            self.terminal.cursorUp()
-        elif keyID == self.terminal.DOWN_ARROW:
-            self.terminal.cursorDown()
-        elif keyID == self.terminal.LEFT_ARROW:
-            self.terminal.cursorBackward()
-        elif keyID == self.terminal.RIGHT_ARROW:
-            self.terminal.cursorForward()
-        elif keyID == ' ':
-            self.cursor = self.cursors[(self.cursors.index(self.cursor) + 1) % len(self.cursors)]
-        else:
-            return
-        self.terminal.write(self.cursor)
-        self.terminal.cursorBackward()
-
-def makeService(args):
-    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(username="password")
-
-    f = protocol.ServerFactory()
-    f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol,
-                                         insults.ServerProtocol,
-                                         args['protocolFactory'],
-                                         *args.get('protocolArgs', ()),
-                                         **args.get('protocolKwArgs', {}))
-    tsvc = internet.TCPServer(args['telnet'], f)
-
-    def chainProtocolFactory():
-        return insults.ServerProtocol(
-            args['protocolFactory'],
-            *args.get('protocolArgs', ()),
-            **args.get('protocolKwArgs', {}))
-
-    rlm = TerminalRealm()
-    rlm.chainedProtocolFactory = chainProtocolFactory
-    ptl = portal.Portal(rlm, [checker])
-    f = ConchFactory(ptl)
-    csvc = internet.TCPServer(args['ssh'], f)
-
-    m = service.MultiService()
-    tsvc.setServiceParent(m)
-    csvc.setServiceParent(m)
-    return m
-
-application = service.Application("Insults Demo App")
-makeService({'protocolFactory': Draw,
-             'telnet': 6023,
-             'ssh': 6022}).setServiceParent(application)

+ 0 - 252
desktop/core/ext-py/Twisted/doc/conch/examples/demo_insults.tac

@@ -1,252 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-# You can run this .tac file directly with:
-#    twistd -ny demo_insults.tac
-
-"""Various simple terminal manipulations using the insults module.
-
-This demo sets up two listening ports: one on 6022 which accepts ssh
-connections; one on 6023 which accepts telnet connections.  No login
-for the telnet server is required; for the ssh server, \"username\" is
-the username and \"password\" is the password.
-
-The TerminalProtocol subclass defined here ignores most user input
-(except to print it out to the server log) and spends the duration of
-the connection drawing (the author's humble approximation of)
-raindrops at random locations on the client's terminal.  +, -, *, and
-/ are respected and each adjusts an aspect of the timing of the
-animation process.
-"""
-
-import random, string
-
-from twisted.python import log
-from twisted.internet import protocol, task
-from twisted.application import internet, service
-from twisted.cred import checkers, portal
-
-from twisted.conch.insults import insults
-from twisted.conch.telnet import TelnetTransport, TelnetBootstrapProtocol
-from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
-
-class DrawingFinished(Exception):
-    """Sentinel exception, raised when no \"frames\" for a particular
-    \"animation\" remain to be drawn.
-    """
-
-class Drawable:
-    """Representation of an animation.
-
-    Constructed with a protocol instance and a coordinate on the
-    screen, waits for invocations of iterate() at which point it
-    erases the previous frame of the animation and draws the next one,
-    using its protocol instance and always placing the upper left hand
-    corner of the frame at the given coordinates.
-
-    Frames are defined with draw_ prefixed methods.  Erasure is
-    performed by erase_ prefixed methods.
-    """
-    n = 0
-
-    def __init__(self, proto, col, line):
-        self.proto = proto
-        self.col = col
-        self.line = line
-
-    def drawLines(self, s):
-        lines = s.splitlines()
-        c = self.col
-        line = self.line
-        for l in lines:
-            self.proto.cursorPosition(c - len(lines) / 2, line)
-            self.proto.write(l)
-            line += 1
-
-    def iterate(self):
-        getattr(self, 'erase_' + str(self.n))()
-        self.n += 1
-        f = getattr(self, 'draw_' + str(self.n), None)
-        if f is None:
-            raise DrawingFinished()
-        f()
-
-    def erase_0(self):
-        pass
-
-
-class Splat(Drawable):
-    HEIGHT = 5
-    WIDTH = 11
-
-    def draw_1(self):
-        # . .
-        #. . .
-        # . .
-        self.drawLines(' . .\n. . .\n . .')
-
-    def erase_1(self):
-        self.drawLines('    \n     \n    ')
-
-    def draw_2(self):
-        #  . . . .
-        # . o o o .
-        #. o o o o .
-        # . o o o .
-        #  . . . .
-        self.drawLines('  . . . .\n . o o o .\n. o o o o .\n . o o o .\n  . . . .')
-
-    def erase_2(self):
-        self.drawLines('         \n          \n           \n          \n         ')
-
-    def draw_3(self):
-        #  o o o o
-        # o O O O o
-        #o O O O O o
-        # o O O O o
-        #  o o o o
-        self.drawLines('  o o o o\n o O O O o\no O O O O o\n o O O O o\n  o o o o')
-
-    erase_3 = erase_2
-
-    def draw_4(self):
-        #  O O O O
-        # O . . . O
-        #O . . . . O
-        # O . . . O
-        #  O O O O
-        self.drawLines('  O O O O\n O . . . O\nO . . . . O\n O . . . O\n  O O O O')
-
-    erase_4 = erase_3
-
-    def draw_5(self):
-        #  . . . .
-        # .       .
-        #.         .
-        # .       .
-        #  . . . .
-        self.drawLines('  . . . .\n .       .\n.         .\n .       .\n  . . . .')
-
-    erase_5 = erase_4
-
-class Drop(Drawable):
-    WIDTH = 3
-    HEIGHT = 4
-
-    def draw_1(self):
-        # o
-        self.drawLines(' o')
-
-    def erase_1(self):
-        self.drawLines('  ')
-
-    def draw_2(self):
-        # _
-        #/ \
-        #\./
-        self.drawLines(' _ \n/ \\\n\\./')
-
-    def erase_2(self):
-        self.drawLines('  \n   \n   ')
-
-    def draw_3(self):
-        # O
-        self.drawLines(' O')
-
-    def erase_3(self):
-        self.drawLines('  ')
-
-class DemoProtocol(insults.TerminalProtocol):
-    """Draws random things at random places on the screen.
-    """
-    width = 80
-    height = 24
-
-    interval = 0.1
-    rate = 0.05
-
-    def connectionMade(self):
-        self.run()
-
-    def connectionLost(self, reason):
-        self._call.stop()
-        del self._call
-
-    def run(self):
-        # Clear the screen, matey
-        self.terminal.eraseDisplay()
-
-        self._call = task.LoopingCall(self._iterate)
-        self._call.start(self.interval)
-
-    def _iterate(self):
-        cls = random.choice((Splat, Drop))
-
-        # Move to a random location on the screen
-        col = random.randrange(self.width - cls.WIDTH) + cls.WIDTH
-        line = random.randrange(self.height - cls.HEIGHT) + cls.HEIGHT
-
-        s = cls(self.terminal, col, line)
-
-        c = task.LoopingCall(s.iterate)
-        c.start(self.rate).addErrback(lambda f: f.trap(DrawingFinished)).addErrback(log.err)
-
-    # ITerminalListener
-    def terminalSize(self, width, height):
-        self.width = width
-        self.height = height
-
-    def unhandledControlSequence(self, seq):
-        log.msg("Client sent something weird: %r" % (seq,))
-
-    def keystrokeReceived(self, keyID, modifier):
-        if keyID == '+':
-            self.interval /= 1.1
-        elif keyID == '-':
-            self.interval *= 1.1
-        elif keyID == '*':
-            self.rate /= 1.1
-        elif keyID == '/':
-            self.rate *= 1.1
-        else:
-            log.msg("Client sent: %r" % (keyID,))
-            return
-
-        self._call.stop()
-        self._call = task.LoopingCall(self._iterate)
-        self._call.start(self.interval)
-
-
-def makeService(args):
-    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(username="password")
-
-    f = protocol.ServerFactory()
-    f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol,
-                                         insults.ServerProtocol,
-                                         args['protocolFactory'],
-                                         *args.get('protocolArgs', ()),
-                                         **args.get('protocolKwArgs', {}))
-    tsvc = internet.TCPServer(args['telnet'], f)
-
-    def chainProtocolFactory():
-        return insults.ServerProtocol(
-            args['protocolFactory'],
-            *args.get('protocolArgs', ()),
-            **args.get('protocolKwArgs', {}))
-
-    rlm = TerminalRealm()
-    rlm.chainedProtocolFactory = chainProtocolFactory
-    ptl = portal.Portal(rlm, [checker])
-    f = ConchFactory(ptl)
-    csvc = internet.TCPServer(args['ssh'], f)
-
-    m = service.MultiService()
-    tsvc.setServiceParent(m)
-    csvc.setServiceParent(m)
-    return m
-
-application = service.Application("Insults Demo App")
-
-makeService({'protocolFactory': DemoProtocol,
-             'telnet': 6023,
-             'ssh': 6022}).setServiceParent(application)

+ 0 - 56
desktop/core/ext-py/Twisted/doc/conch/examples/demo_manhole.tac

@@ -1,56 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-# You can run this .tac file directly with:
-#    twistd -ny demo_manhole.tac
-
-"""An interactive Python interpreter with syntax coloring.
-
-Nothing interesting is actually defined here.  Two listening ports are
-set up and attached to protocols which know how to properly set up a
-ColoredManhole instance.
-"""
-
-from twisted.conch.manhole import ColoredManhole
-from twisted.conch.insults import insults
-from twisted.conch.telnet import TelnetTransport, TelnetBootstrapProtocol
-from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
-
-from twisted.internet import protocol
-from twisted.application import internet, service
-from twisted.cred import checkers, portal
-
-def makeService(args):
-    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(username="password")
-
-    f = protocol.ServerFactory()
-    f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol,
-                                         insults.ServerProtocol,
-                                         args['protocolFactory'],
-                                         *args.get('protocolArgs', ()),
-                                         **args.get('protocolKwArgs', {}))
-    tsvc = internet.TCPServer(args['telnet'], f)
-
-    def chainProtocolFactory():
-        return insults.ServerProtocol(
-            args['protocolFactory'],
-            *args.get('protocolArgs', ()),
-            **args.get('protocolKwArgs', {}))
-
-    rlm = TerminalRealm()
-    rlm.chainedProtocolFactory = chainProtocolFactory
-    ptl = portal.Portal(rlm, [checker])
-    f = ConchFactory(ptl)
-    csvc = internet.TCPServer(args['ssh'], f)
-
-    m = service.MultiService()
-    tsvc.setServiceParent(m)
-    csvc.setServiceParent(m)
-    return m
-
-application = service.Application("Interactive Python Interpreter")
-
-makeService({'protocolFactory': ColoredManhole,
-             'protocolArgs': (None,),
-             'telnet': 6023,
-             'ssh': 6022}).setServiceParent(application)

+ 0 - 77
desktop/core/ext-py/Twisted/doc/conch/examples/demo_recvline.tac

@@ -1,77 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-# You can run this .tac file directly with:
-#    twistd -ny demo_recvline.tac
-
-"""Demonstrates line-at-a-time handling with basic line-editing support.
-
-This is a variation on the echo server.  It sets up two listening
-ports: one on 6022 which accepts ssh connections; one on 6023 which
-accepts telnet connections.  No login for the telnet server is
-required; for the ssh server, \"username\" is the username and
-\"password\" is the password.
-
-The demo protocol defined in this module is handed a line of input at
-a time, which it simply writes back to the connection.
-HistoricRecvline, which the demo protocol subclasses, provides basic
-line editing and input history features.
-"""
-
-from twisted.conch import recvline
-from twisted.conch.insults import insults
-from twisted.conch.telnet import TelnetTransport, TelnetBootstrapProtocol
-from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
-
-from twisted.internet import protocol
-from twisted.application import internet, service
-from twisted.cred import checkers, portal
-
-class DemoRecvLine(recvline.HistoricRecvLine):
-    """Simple echo protocol.
-
-    Accepts lines of input and writes them back to its connection.  If
-    a line consisting solely of \"quit\" is received, the connection
-    is dropped.
-    """
-
-    def lineReceived(self, line):
-        if line == "quit":
-            self.terminal.loseConnection()
-        self.terminal.write(line)
-        self.terminal.nextLine()
-        self.terminal.write(self.ps[self.pn])
-
-def makeService(args):
-    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(username="password")
-
-    f = protocol.ServerFactory()
-    f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol,
-                                         insults.ServerProtocol,
-                                         args['protocolFactory'],
-                                         *args.get('protocolArgs', ()),
-                                         **args.get('protocolKwArgs', {}))
-    tsvc = internet.TCPServer(args['telnet'], f)
-
-    def chainProtocolFactory():
-        return insults.ServerProtocol(
-            args['protocolFactory'],
-            *args.get('protocolArgs', ()),
-            **args.get('protocolKwArgs', {}))
-
-    rlm = TerminalRealm()
-    rlm.chainedProtocolFactory = chainProtocolFactory
-    ptl = portal.Portal(rlm, [checker])
-    f = ConchFactory(ptl)
-    csvc = internet.TCPServer(args['ssh'], f)
-
-    m = service.MultiService()
-    tsvc.setServiceParent(m)
-    csvc.setServiceParent(m)
-    return m
-
-application = service.Application("Insults RecvLine Demo")
-
-makeService({'protocolFactory': DemoRecvLine,
-             'telnet': 6023,
-             'ssh': 6022}).setServiceParent(application)

+ 0 - 100
desktop/core/ext-py/Twisted/doc/conch/examples/demo_scroll.tac

@@ -1,100 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-# You can run this .tac file directly with:
-#    twistd -ny demo_scroll.tac
-
-"""Simple echo-ish server that uses the scroll-region.
-
-This demo sets up two listening ports: one on 6022 which accepts ssh
-connections; one on 6023 which accepts telnet connections.  No login
-for the telnet server is required; for the ssh server, \"username\" is
-the username and \"password\" is the password.
-
-The TerminalProtocol subclass defined here sets up a scroll-region occupying
-most of the screen.  It positions the cursor at the bottom of the screen and
-then echos back printable input.  When return is received, the line is
-copied to the upper area of the screen (scrolling anything older up) and
-clears the input line.
-"""
-
-import string
-
-from twisted.python import log
-from twisted.internet import protocol
-from twisted.application import internet, service
-from twisted.cred import checkers, portal
-
-from twisted.conch.insults import insults
-from twisted.conch.telnet import TelnetTransport, TelnetBootstrapProtocol
-from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
-
-class DemoProtocol(insults.TerminalProtocol):
-    """Copies input to an upwards scrolling region.
-    """
-    width = 80
-    height = 24
-
-    def connectionMade(self):
-        self.buffer = []
-        self.terminalSize(self.width, self.height)
-
-    # ITerminalListener
-    def terminalSize(self, width, height):
-        self.width = width
-        self.height = height
-
-        self.terminal.setScrollRegion(0, height - 1)
-        self.terminal.cursorPosition(0, height)
-        self.terminal.write('> ')
-
-    def unhandledControlSequence(self, seq):
-        log.msg("Client sent something weird: %r" % (seq,))
-
-    def keystrokeReceived(self, keyID, modifier):
-        if keyID == '\r':
-            self.terminal.cursorPosition(0, self.height - 2)
-            self.terminal.nextLine()
-            self.terminal.write(''.join(self.buffer))
-            self.terminal.cursorPosition(0, self.height - 1)
-            self.terminal.eraseToLineEnd()
-            self.terminal.write('> ')
-            self.buffer = []
-        elif keyID in list(string.printable):
-            self.terminal.write(keyID)
-            self.buffer.append(keyID)
-
-
-def makeService(args):
-    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(username="password")
-
-    f = protocol.ServerFactory()
-    f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol,
-                                         insults.ServerProtocol,
-                                         args['protocolFactory'],
-                                         *args.get('protocolArgs', ()),
-                                         **args.get('protocolKwArgs', {}))
-    tsvc = internet.TCPServer(args['telnet'], f)
-
-    def chainProtocolFactory():
-        return insults.ServerProtocol(
-            args['protocolFactory'],
-            *args.get('protocolArgs', ()),
-            **args.get('protocolKwArgs', {}))
-
-    rlm = TerminalRealm()
-    rlm.chainedProtocolFactory = chainProtocolFactory
-    ptl = portal.Portal(rlm, [checker])
-    f = ConchFactory(ptl)
-    csvc = internet.TCPServer(args['ssh'], f)
-
-    m = service.MultiService()
-    tsvc.setServiceParent(m)
-    csvc.setServiceParent(m)
-    return m
-
-application = service.Application("Scroll Region Demo App")
-
-makeService({'protocolFactory': DemoProtocol,
-             'telnet': 6023,
-             'ssh': 6022}).setServiceParent(application)

+ 0 - 2
desktop/core/ext-py/Twisted/doc/conch/examples/index.html

@@ -1,2 +0,0 @@
-<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><title>Twisted Documentation: Twisted.Conch code examples</title><link href="../howto/stylesheet.css" type="text/css" rel="stylesheet" /></head><body bgcolor="white"><h1 class="title">Twisted.Conch code examples</h1><div class="toc"><ol><li><a href="#auto0">Simple server and client</a></li><li><a href="#auto1">twisted.conch.insults examples</a></li></ol></div><div class="content"><span></span><h2>Simple server and client<a name="auto0"></a></h2><ul><li><a href="sshsimpleclient.py">sshsimpleclient.py</a></li><li><a href="sshsimpleserver.py">sshsimpleserver.py</a></li></ul><h2>twisted.conch.insults examples<a name="auto1"></a></h2><ul><li><a href="demo.tac">demo.tac</a> Nearly pointless demonstration of the manhole interactive interpreter</li><li><a href="demo_draw.tac">demo_draw.tac</a> A trivial drawing application</li><li><a href="demo_insults.tac">demo_insults.tac</a> Various simple terminal manipulations using the insults module</li><li><a href="demo_recvline.tac">demo_recvline.tac</a> Demonstrates line-at-a-time handling with basic line-editing support</li><li><a href="demo_scroll.tac">demo_scroll.tac</a> Simple echo-ish server that uses the scroll-region</li><li><a href="demo_manhole.tac">demo_manhole.tac</a> An interactive Python interpreter with syntax coloring</li><li><a href="window.tac">window.tac</a> An example of various widgets</li></ul></div><p><a href="../howto/index.html">Index</a></p><span class="version">Version: 8.2.0</span></body></html>

+ 0 - 107
desktop/core/ext-py/Twisted/doc/conch/examples/sshsimpleclient.py

@@ -1,107 +0,0 @@
-#!/usr/bin/python
-from twisted.conch.ssh import transport, userauth, connection, common, keys, channel
-from twisted.internet import defer, protocol, reactor
-from twisted.python import log
-import struct, sys, getpass, os
-
-USER = 'z3p'  # replace this with a valid username
-HOST = 'localhost' # and a valid host
-
-class SimpleTransport(transport.SSHClientTransport):
-    def verifyHostKey(self, hostKey, fingerprint):
-        print 'host key fingerprint: %s' % fingerprint
-        return defer.succeed(1) 
-
-    def connectionSecure(self):
-        self.requestService(
-            SimpleUserAuth(USER,
-                SimpleConnection()))
-
-class SimpleUserAuth(userauth.SSHUserAuthClient):
-    def getPassword(self):
-        return defer.succeed(getpass.getpass("%s@%s's password: " % (USER, HOST)))
-
-    def getGenericAnswers(self, name, instruction, questions):
-        print name
-        print instruction
-        answers = []
-        for prompt, echo in questions:
-            if echo:
-                answer = raw_input(prompt)
-            else:
-                answer = getpass.getpass(prompt)
-            answers.append(answer)
-        return defer.succeed(answers)
-            
-    def getPublicKey(self):
-        path = os.path.expanduser('~/.ssh/id_dsa') 
-        # this works with rsa too
-        # just change the name here and in getPrivateKey
-        if not os.path.exists(path) or self.lastPublicKey:
-            # the file doesn't exist, or we've tried a public key
-            return
-        return keys.getPublicKeyString(path+'.pub')
-
-    def getPrivateKey(self):
-        path = os.path.expanduser('~/.ssh/id_dsa')
-        return defer.succeed(keys.getPrivateKeyObject(path))
-
-class SimpleConnection(connection.SSHConnection):
-    def serviceStarted(self):
-        self.openChannel(TrueChannel(2**16, 2**15, self))
-        self.openChannel(FalseChannel(2**16, 2**15, self))
-        self.openChannel(CatChannel(2**16, 2**15, self))
-
-class TrueChannel(channel.SSHChannel):
-    name = 'session' # needed for commands
-
-    def openFailed(self, reason):
-        print 'true failed', reason
-    
-    def channelOpen(self, ignoredData):
-        self.conn.sendRequest(self, 'exec', common.NS('true'))
-
-    def request_exit_status(self, data):
-        status = struct.unpack('>L', data)[0]
-        print 'true status was: %s' % status
-        self.loseConnection()
-
-class FalseChannel(channel.SSHChannel):
-    name = 'session'
-
-    def openFailed(self, reason):
-        print 'false failed', reason
-
-    def channelOpen(self, ignoredData):
-        self.conn.sendRequest(self, 'exec', common.NS('false'))
-
-    def request_exit_status(self, data):
-        status = struct.unpack('>L', data)[0]
-        print 'false status was: %s' % status
-        self.loseConnection()
-
-class CatChannel(channel.SSHChannel):
-    name = 'session'
-
-    def openFailed(self, reason):
-        print 'echo failed', reason
-
-    def channelOpen(self, ignoredData):
-        self.data = ''
-        d = self.conn.sendRequest(self, 'exec', common.NS('cat'), wantReply = 1)
-        d.addCallback(self._cbRequest)
-
-    def _cbRequest(self, ignored):
-        self.write('hello conch\n')
-        self.conn.sendEOF(self)
-
-    def dataReceived(self, data):
-        self.data += data
-
-    def closed(self):
-        print 'got data from cat: %s' % repr(self.data)
-        self.loseConnection()
-        reactor.stop()
-
-protocol.ClientCreator(reactor, SimpleTransport).connectTCP(HOST, 22)
-reactor.run()

+ 0 - 112
desktop/core/ext-py/Twisted/doc/conch/examples/sshsimpleserver.py

@@ -1,112 +0,0 @@
-#!/usr/bin/python
-from twisted.cred import portal, checkers
-from twisted.conch import error, avatar
-from twisted.conch.checkers import SSHPublicKeyDatabase
-from twisted.conch.ssh import factory, userauth, connection, keys, session
-from twisted.internet import reactor, protocol, defer
-from twisted.python import log
-from zope.interface import implements
-import sys
-log.startLogging(sys.stderr)
-
-"""Example of running another protocol over an SSH channel.
-log in with username "user" and password "password".
-"""
-
-class ExampleAvatar(avatar.ConchUser):
-
-    def __init__(self, username):
-        avatar.ConchUser.__init__(self)
-        self.username = username
-        self.channelLookup.update({'session':session.SSHSession})
-
-class ExampleRealm:
-    implements(portal.IRealm)
-
-    def requestAvatar(self, avatarId, mind, *interfaces):
-        return interfaces[0], ExampleAvatar(avatarId), lambda: None
-
-class EchoProtocol(protocol.Protocol):
-    """this is our example protocol that we will run over SSH
-    """
-    def dataReceived(self, data):
-        if data == '\r':
-            data = '\r\n'
-        elif data == '\x03': #^C
-            self.transport.loseConnection()
-            return
-        self.transport.write(data)
-
-publicKey = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEArzJx8OYOnJmzf4tfBEvLi8DVPrJ3/c9k2I/Az64fxjHf9imyRJbixtQhlH9lfNjUIx+4LmrJH5QNRsFporcHDKOTwTTYLh5KmRpslkYHRivcJSkbh/C+BR3utDS555mV'
-
-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-----"""
-
-
-class InMemoryPublicKeyChecker(SSHPublicKeyDatabase):
-
-    def checkKey(self, credentials):
-        return credentials.username == 'user' and \
-            keys.getPublicKeyString(data=publicKey) == credentials.blob
-
-class ExampleSession:
-    
-    def __init__(self, avatar):
-        """
-        We don't use it, but the adapter is passed the avatar as its first
-        argument.
-        """
-
-    def getPty(self, term, windowSize, attrs):
-        pass
-    
-    def execCommand(self, proto, cmd):
-        raise Exception("no executing commands")
-
-    def openShell(self, trans):
-        ep = EchoProtocol()
-        ep.makeConnection(trans)
-        trans.makeConnection(session.wrapProtocol(ep))
-
-    def eofReceived(self):
-        pass
-
-    def closed(self):
-        pass
-
-from twisted.python import components
-components.registerAdapter(ExampleSession, ExampleAvatar, session.ISession)
-
-class ExampleFactory(factory.SSHFactory):
-    publicKeys = {
-        'ssh-rsa': keys.Key.fromString(data=publicKey)
-    }
-    privateKeys = {
-        'ssh-rsa': keys.Key.fromString(data=privateKey)
-    }
-    services = {
-        'ssh-userauth': userauth.SSHUserAuthServer,
-        'ssh-connection': connection.SSHConnection
-    }
-    
-
-portal = portal.Portal(ExampleRealm())
-passwdDB = checkers.InMemoryUsernamePasswordDatabaseDontUse()
-passwdDB.addUser('user', 'password')
-portal.registerChecker(passwdDB)
-portal.registerChecker(InMemoryPublicKeyChecker())
-ExampleFactory.portal = portal
-
-if __name__ == '__main__':
-    reactor.listenTCP(5022, ExampleFactory())
-    reactor.run()

+ 0 - 190
desktop/core/ext-py/Twisted/doc/conch/examples/window.tac

@@ -1,190 +0,0 @@
-# Copyright (c) 2001-2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-# You can run this .tac file directly with:
-#    twistd -ny window.tac
-
-from __future__ import division
-
-import string, random
-
-from twisted.python import log
-from twisted.internet import protocol, task
-from twisted.application import internet, service
-from twisted.cred import checkers, portal
-
-from twisted.conch.insults import insults, window
-from twisted.conch.telnet import TelnetTransport, TelnetBootstrapProtocol
-from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
-
-from twisted.internet import reactor
-
-class DrawableCanvas(window.Canvas):
-    x = 0
-    y = 0
-
-    def func_LEFT_ARROW(self, modifier):
-        self.x -= 1
-        self.repaint()
-
-    def func_RIGHT_ARROW(self, modifier):
-        self.x += 1
-        self.repaint()
-
-    def func_UP_ARROW(self, modifier):
-        self.y -= 1
-        self.repaint()
-
-    def func_DOWN_ARROW(self, modifier):
-        self.y += 1
-        self.repaint()
-
-    def characterReceived(self, keyID, modifier):
-        self[self.x, self.y] = keyID
-        self.x += 1
-        self.repaint()
-
-    def keystrokeReceived(self, keyID, modifier):
-        if keyID == '\r' or keyID == '\v':
-            return
-        window.Canvas.keystrokeReceived(self, keyID, modifier)
-        if self.x >= self.width:
-            self.x = 0
-        elif self.x < 0:
-            self.x = self.width - 1
-
-        if self.y >= self.height:
-            self.y = 0
-        elif self.y < 0:
-            self.y = self.height - 1
-        self.repaint()
-
-    def render(self, width, height, terminal):
-        window.Canvas.render(self, width, height, terminal)
-        if self.focused:
-            terminal.cursorPosition(self.x, self.y)
-            window.cursor(terminal, self[self.x, self.y])
-
-
-class ButtonDemo(insults.TerminalProtocol):
-    width = 80
-    height = 24
-
-    def _draw(self):
-        self.window.draw(self.width, self.height, self.terminal)
-
-    def _redraw(self):
-        self.window.filthy()
-        self._draw()
-
-    def _schedule(self, f):
-        reactor.callLater(0, f)
-
-    def connectionMade(self):
-        self.terminal.eraseDisplay()
-        self.terminal.resetPrivateModes([insults.privateModes.CURSOR_MODE])
-
-        self.window = window.TopWindow(self._draw, self._schedule)
-        self.output = window.TextOutput((15, 1))
-        self.input = window.TextInput(15, self._setText)
-        self.select1 = window.Selection(map(str, range(100)), self._setText, 10)
-        self.select2 = window.Selection(map(str, range(200, 300)), self._setText, 10)
-        self.button = window.Button("Clear", self._clear)
-        self.canvas = DrawableCanvas()
-
-        hbox = window.HBox()
-        hbox.addChild(self.input)
-        hbox.addChild(self.output)
-        hbox.addChild(window.Border(self.button))
-        hbox.addChild(window.Border(self.select1))
-        hbox.addChild(window.Border(self.select2))
-
-        t1 = window.TextOutputArea(longLines=window.TextOutputArea.WRAP)
-        t2 = window.TextOutputArea(longLines=window.TextOutputArea.TRUNCATE)
-        t3 = window.TextOutputArea(longLines=window.TextOutputArea.TRUNCATE)
-        t4 = window.TextOutputArea(longLines=window.TextOutputArea.TRUNCATE)
-        for _t in t1, t2, t3, t4:
-            _t.setText((('This is a very long string.  ' * 3) + '\n') * 3)
-
-        vp = window.Viewport(t3)
-        d = [1]
-        def spin():
-            vp.xOffset += d[0]
-            if vp.xOffset == 0 or vp.xOffset == 25:
-                d[0] *= -1
-        self.call = task.LoopingCall(spin)
-        self.call.start(0.25, now=False)
-        hbox.addChild(window.Border(vp))
-
-        vp2 = window.ScrolledArea(t4)
-        hbox.addChild(vp2)
-
-        texts = window.VBox()
-        texts.addChild(window.Border(t1))
-        texts.addChild(window.Border(t2))
-
-        areas = window.HBox()
-        areas.addChild(window.Border(self.canvas))
-        areas.addChild(texts)
-
-        vbox = window.VBox()
-        vbox.addChild(hbox)
-        vbox.addChild(areas)
-        self.window.addChild(vbox)
-        self.terminalSize(self.width, self.height)
-
-    def connectionLost(self, reason):
-        self.call.stop()
-        insults.TerminalProtocol.connectionLost(self, reason)
-
-    def terminalSize(self, width, height):
-        self.width = width
-        self.height = height
-        self.terminal.eraseDisplay()
-        self._redraw()
-
-
-    def keystrokeReceived(self, keyID, modifier):
-        self.window.keystrokeReceived(keyID, modifier)
-
-    def _clear(self):
-        self.canvas.clear()
-
-    def _setText(self, text):
-        self.input.setText('')
-        self.output.setText(text)
-
-
-def makeService(args):
-    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(username="password")
-
-    f = protocol.ServerFactory()
-    f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol,
-                                         insults.ServerProtocol,
-                                         args['protocolFactory'],
-                                         *args.get('protocolArgs', ()),
-                                         **args.get('protocolKwArgs', {}))
-    tsvc = internet.TCPServer(args['telnet'], f)
-
-    def chainProtocolFactory():
-        return insults.ServerProtocol(
-            args['protocolFactory'],
-            *args.get('protocolArgs', ()),
-            **args.get('protocolKwArgs', {}))
-
-    rlm = TerminalRealm()
-    rlm.chainedProtocolFactory = chainProtocolFactory
-    ptl = portal.Portal(rlm, [checker])
-    f = ConchFactory(ptl)
-    csvc = internet.TCPServer(args['ssh'], f)
-
-    m = service.MultiService()
-    tsvc.setServiceParent(m)
-    csvc.setServiceParent(m)
-    return m
-
-application = service.Application("Window Demo")
-
-makeService({'protocolFactory': ButtonDemo,
-             'telnet': 6023,
-             'ssh': 6022}).setServiceParent(application)

+ 0 - 172
desktop/core/ext-py/Twisted/doc/conch/howto/conch_client.html

@@ -1,172 +0,0 @@
-<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><title>Twisted Documentation: Writing a client with Twisted.Conch</title><link href="stylesheet.css" type="text/css" rel="stylesheet" /></head><body bgcolor="white"><h1 class="title">Writing a client with Twisted.Conch</h1><div class="toc"><ol><li><a href="#auto0">Introduction</a></li><li><a href="#auto1">Writing a client</a></li><li><a href="#auto2">The Transport</a></li><li><a href="#auto3">The Authorization Client</a></li><li><a href="#auto4">The Connection</a></li><li><a href="#auto5">The Channel</a></li><li><a href="#auto6">The main() function</a></li></ol></div><div class="content"><span></span><h2>Introduction<a name="auto0"></a></h2><p>In the original days of computing, rsh/rlogin were used to connect to
-remote computers and execute commands. These commands had the problem
-that the passwords and commands were sent in the clear. To solve this
-problem, the SSH protocol was created. Twisted.Conch implements the
-second version of this protocol.</p><h2>Writing a client<a name="auto1"></a></h2><p>Writing a client with Conch involves sub-classing 4 classes: <code class="API"><a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.conch.ssh.transport.SSHClientTransport.html" title="twisted.conch.ssh.transport.SSHClientTransport">twisted.conch.ssh.transport.SSHClientTransport</a></code>, <code class="API"><a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.conch.ssh.userauth.SSHUserAuthClient.html" title="twisted.conch.ssh.userauth.SSHUserAuthClient">twisted.conch.ssh.userauth.SSHUserAuthClient</a></code>, <code class="API"><a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.conch.ssh.connection.SSHConnection.html" title="twisted.conch.ssh.connection.SSHConnection">twisted.conch.ssh.connection.SSHConnection</a></code>, and <code class="API"><a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.conch.ssh.channel.SSHChannel.html" title="twisted.conch.ssh.channel.SSHChannel">twisted.conch.ssh.channel.SSHChannel</a></code>. We'll start out
-with <code class="python">SSHClientTransport</code> because it's the base 
-of the client.</p><h2>The Transport<a name="auto2"></a></h2><pre class="python">
-<span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">conch</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">error</span>
-<span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">conch</span>.<span class="py-src-variable">ssh</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">transport</span>
-<span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">defer</span>
-
-<span class="py-src-keyword">class</span> <span class="py-src-identifier">ClientTransport</span>(<span class="py-src-parameter">transport</span>.<span class="py-src-parameter">SSHClientTransport</span>):
-
-    <span class="py-src-keyword">def</span> <span class="py-src-identifier">verifyHostKey</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">pubKey</span>, <span class="py-src-parameter">fingerprint</span>):
-        <span class="py-src-keyword">if</span> <span class="py-src-variable">fingerprint</span> != <span class="py-src-string">'b1:94:6a:c9:24:92:d2:34:7c:62:35:b4:d2:61:11:84'</span>:
-            <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">fail</span>(<span class="py-src-variable">error</span>.<span class="py-src-variable">ConchError</span>(<span class="py-src-string">'bad key'</span>))
-        <span class="py-src-keyword">else</span>:
-            <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-number">1</span>)
-
-    <span class="py-src-keyword">def</span> <span class="py-src-identifier">connectionSecure</span>(<span class="py-src-parameter">self</span>):
-        <span class="py-src-variable">self</span>.<span class="py-src-variable">requestService</span>(<span class="py-src-variable">ClientUserAuth</span>(<span class="py-src-string">'user'</span>, <span class="py-src-variable">ClientConnection</span>()))
-</pre><p>See how easy it is? <code class="python">SSHClientTransport</code>
-handles the negotiation of encryption and the verification of keys
-for you. The one security element that you as a client writer need to
-implement is <code class="python">verifyHostKey()</code>. This method
-is called with two strings: the public key sent by the server and its
-fingerprint. You should verify the host key the server sends, either
-by checking against a hard-coded value as in the example, or by asking
-the user. <code class="python">verifyHostKey</code> returns a <code class="API"><a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.defer.Deferred.html" title="twisted.internet.defer.Deferred">twisted.internet.defer.Deferred</a></code> which gets a callback
-if the host key is valid, or an errback if it is not. Note that in the
-above, replace 'user' with the username you're attempting to ssh with,
-for instance a call to <code class="python">os.getlogin()</code> for the
-current user.</p><p>The second method you need to implement is <code class="python">connectionSecure()</code>. It is called when the
-encryption is set up and other services can be run. The example requests
-that the <code class="python">ClientUserAuth</code> service be started.
-This service will be discussed next.</p><h2>The Authorization Client<a name="auto3"></a></h2><pre class="python">
-<span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">conch</span>.<span class="py-src-variable">ssh</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">keys</span>, <span class="py-src-variable">userauth</span>
-
-<span class="py-src-comment"># these are the public/private keys from test_conch
-</span>
-<span class="py-src-variable">publicKey</span> = <span class="py-src-string">'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAGEArzJx8OYOnJmzf4tfBEvLi8DVPrJ3\
-/c9k2I/Az64fxjHf9imyRJbixtQhlH9lfNjUIx+4LmrJH5QNRsFporcHDKOTwTTYLh5KmRpslkYHR\
-ivcJSkbh/C+BR3utDS555mV'</span>
-
-<span class="py-src-variable">privateKey</span> = <span class="py-src-string">&quot;&quot;&quot;-----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-----&quot;&quot;&quot;</span>
-
-<span class="py-src-keyword">class</span> <span class="py-src-identifier">ClientUserAuth</span>(<span class="py-src-parameter">userauth</span>.<span class="py-src-parameter">SSHUserAuthClient</span>):
-
-    <span class="py-src-keyword">def</span> <span class="py-src-identifier">getPassword</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">prompt</span> = <span class="py-src-parameter">None</span>):
-        <span class="py-src-keyword">return</span> 
-        <span class="py-src-comment"># this says we won't do password authentication
-</span>
-    <span class="py-src-keyword">def</span> <span class="py-src-identifier">getPublicKey</span>(<span class="py-src-parameter">self</span>):
-        <span class="py-src-keyword">return</span> <span class="py-src-variable">keys</span>.<span class="py-src-variable">getPublicKeyString</span>(<span class="py-src-variable">data</span> = <span class="py-src-variable">publicKey</span>)
-
-    <span class="py-src-keyword">def</span> <span class="py-src-identifier">getPrivateKey</span>(<span class="py-src-parameter">self</span>):
-        <span class="py-src-keyword">return</span> <span class="py-src-variable">defer</span>.<span class="py-src-variable">succeed</span>(<span class="py-src-variable">keys</span>.<span class="py-src-variable">getPrivateKeyObject</span>(<span class="py-src-variable">data</span> = <span class="py-src-variable">privateKey</span>))
-</pre><p>Again, fairly simple. The <code class="python">SSHUserAuthClient</code> takes care of most
-of the work, but the actual authentication data needs to be
-supplied. <code class="python">getPassword()</code> asks for a
-password, <code class="python">getPublicKey()</code> and <code class="python">getPrivateKey()</code> get public and private keys,
-respectively. <code class="python">getPassword()</code> returns
-a <code class="python">Deferred</code> that is called back with
-the password to use. <code class="python">getPublicKey()</code>
-returns the SSH key data for the public key to use. <code class="python">keys.getPublicKeyString()</code> will take
-keys in OpenSSH and LSH format, and convert them to the
-required format. <code class="python">getPrivateKey()</code>
-returns a <code class="python">Deferred</code> which is
-called back with the key object (as used in PyCrypto) for
-the private key. <code class="python">getPassword()</code>
-and <code class="python">getPrivateKey()</code> return <code class="python">Deferreds</code> because they may need to ask the user
-for input.</p><p>Once the authentication is complete, <code class="python">SSHUserAuthClient</code> takes care of starting the code
-<code class="python">SSHConnection</code> object given to it. Next, we'll
-look at how to use the <code class="python">SSHConnection</code></p><h2>The Connection<a name="auto4"></a></h2><pre class="python">
-<span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">conch</span>.<span class="py-src-variable">ssh</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">connection</span>
-
-<span class="py-src-keyword">class</span> <span class="py-src-identifier">ClientConnection</span>(<span class="py-src-parameter">connection</span>.<span class="py-src-parameter">SSHConnection</span>):
-
-    <span class="py-src-keyword">def</span> <span class="py-src-identifier">serviceStarted</span>(<span class="py-src-parameter">self</span>):
-        <span class="py-src-variable">self</span>.<span class="py-src-variable">openChannel</span>(<span class="py-src-variable">CatChannel</span>(<span class="py-src-variable">conn</span> = <span class="py-src-variable">self</span>))
-</pre><p><code class="python">SSHConnection</code> is the easiest,
-as it's only responsible for starting the channels. It has
-other methods, those will be examined when we look at <code class="python">SSHChannel</code>.</p><h2>The Channel<a name="auto5"></a></h2><pre class="python">
-<span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">conch</span>.<span class="py-src-variable">ssh</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">channel</span>, <span class="py-src-variable">common</span>
-
-<span class="py-src-keyword">class</span> <span class="py-src-identifier">CatChannel</span>(<span class="py-src-parameter">channel</span>.<span class="py-src-parameter">SSHChannel</span>):
-
-    <span class="py-src-variable">name</span> = <span class="py-src-string">'session'</span>
-
-    <span class="py-src-keyword">def</span> <span class="py-src-identifier">channelOpen</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">data</span>):
-        <span class="py-src-variable">d</span> = <span class="py-src-variable">self</span>.<span class="py-src-variable">conn</span>.<span class="py-src-variable">sendRequest</span>(<span class="py-src-variable">self</span>, <span class="py-src-string">'exec'</span>, <span class="py-src-variable">common</span>.<span class="py-src-variable">NS</span>(<span class="py-src-string">'cat'</span>),
-                                  <span class="py-src-variable">wantReply</span> = <span class="py-src-number">1</span>)
-        <span class="py-src-variable">d</span>.<span class="py-src-variable">addCallback</span>(<span class="py-src-variable">self</span>.<span class="py-src-variable">_cbSendRequest</span>)
-        <span class="py-src-variable">self</span>.<span class="py-src-variable">catData</span> = <span class="py-src-string">''</span>
-
-    <span class="py-src-keyword">def</span> <span class="py-src-identifier">_cbSendRequest</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">ignored</span>):
-        <span class="py-src-variable">self</span>.<span class="py-src-variable">write</span>(<span class="py-src-string">'This data will be echoed back to us by &quot;cat.&quot;\r\n'</span>)
-        <span class="py-src-variable">self</span>.<span class="py-src-variable">conn</span>.<span class="py-src-variable">sendEOF</span>(<span class="py-src-variable">self</span>)
-        <span class="py-src-variable">self</span>.<span class="py-src-variable">loseConnection</span>()
-
-    <span class="py-src-keyword">def</span> <span class="py-src-identifier">dataReceived</span>(<span class="py-src-parameter">self</span>, <span class="py-src-parameter">data</span>):
-        <span class="py-src-variable">self</span>.<span class="py-src-variable">catData</span> += <span class="py-src-variable">data</span>
-
-    <span class="py-src-keyword">def</span> <span class="py-src-identifier">closed</span>(<span class="py-src-parameter">self</span>):
-        <span class="py-src-keyword">print</span> <span class="py-src-string">'We got this from &quot;cat&quot;:'</span>, <span class="py-src-variable">self</span>.<span class="py-src-variable">catData</span>
-</pre><p>Now that we've spent all this time getting the server and
-client connected, here is where that work pays off. <code class="python">SSHChannel</code> is the interface between you and the
-other side. This particular channel opens a session and plays with the
-'cat' program, but your channel can implement anything, so long as the
-server supports it.</p><p>The <code class="python">channelOpen()</code> method is
-where everything gets started. It gets passed a chunk of data;
-however, this chunk is usually nothing and can be ignored.
-Our <code class="python">channelOpen()</code> initializes our
-channel, and sends a request to the other side, using the
-<code class="python">sendRequest()</code> method of the <code class="python">SSHConnection</code> object. Requests are used to send
-events to the other side. We pass the method self so that it knows to
-send the request for this channel. The 2nd argument of 'exec' tells the
-server that we want to execute a command. The third argument is the data
-that accompanies the request. <code class="API"><a href="http://twistedmatrix.com/documents/8.2.0/api/common.NS.html" title="common.NS">common.NS</a></code> encodes
-the data as a length-prefixed string, which is how the server expects
-the data. We also say that we want a reply saying that the process has a
-been started. <code class="python">sendRequest()</code> then returns a
-<code class="python">Deferred</code> which we add a callback for.</p><p>Once the callback fires, we send the data. <code class="python">SSHChannel</code> supports the <code class="API"><a href="http://twistedmatrix.com/documents/8.2.0/api/
-twisted.internet.interface.Transport.html" title="
-twisted.internet.interface.Transport">
-twisted.internet.interface.Transport</a></code> interface, so
-it can be given to Protocols to run them over the secure
-connection. In our case, we just write the data directly. <code class="python">sendEOF()</code> does not follow the interface,
-but Conch uses it to tell the other side that we will write no
-more data. <code class="python">loseConnection()</code> shuts
-down our side of the connection, but we will still receive data
-through <code class="python">dataReceived()</code>. The <code class="python">closed()</code> method is called when both sides of the
-connection are closed, and we use it to display the data we received
-(which should be the same as the data we sent.)</p><p>Finally, let's actually invoke the code we've set up.</p><h2>The main() function<a name="auto6"></a></h2><pre class="python">
-<span class="py-src-keyword">from</span> <span class="py-src-variable">twisted</span>.<span class="py-src-variable">internet</span> <span class="py-src-keyword">import</span> <span class="py-src-variable">protocol</span>, <span class="py-src-variable">reactor</span>
-
-<span class="py-src-keyword">def</span> <span class="py-src-identifier">main</span>():
-    <span class="py-src-variable">factory</span> = <span class="py-src-variable">protocol</span>.<span class="py-src-variable">ClientFactory</span>()
-    <span class="py-src-variable">factory</span>.<span class="py-src-variable">protocol</span> = <span class="py-src-variable">ClientTransport</span>
-    <span class="py-src-variable">reactor</span>.<span class="py-src-variable">connectTCP</span>(<span class="py-src-string">'localhost'</span>, <span class="py-src-number">22</span>, <span class="py-src-variable">factory</span>)
-    <span class="py-src-variable">reactor</span>.<span class="py-src-variable">run</span>()
-
-<span class="py-src-keyword">if</span> <span class="py-src-variable">__name__</span> == <span class="py-src-string">&quot;__main__&quot;</span>:
-    <span class="py-src-variable">main</span>()
-</pre><p>We call <code class="python">connectTCP()</code> to connect to
-localhost, port 22 (the standard port for ssh), and pass it an instance
-of <code class="API"><a href="http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.protocol.ClientFactory.html" title="twisted.internet.protocol.ClientFactory">twisted.internet.protocol.ClientFactory</a></code>.
-This instance has the attribute <code class="python">protocol</code>
-set to our earlier <code class="python">ClientTransport</code>
-class. Note that the protocol attribute is set to the class <code class="python">ClientTransport</code>, not an instance of
-<code class="python">ClientTransport</code>! When the <code class="python">connectTCP</code> call completes, the protocol will be
-called to create a <code class="python">ClientTransport()</code> object
-- this then invokes all our previous work.</p><p>It's worth noting that in the example <code class="python">main()</code> 
-routine, the <code class="python">reactor.run()</code> call never returns. 
-If you want to make the program exit, call 
-<code class="python">reactor.stop()</code> in the earlier 
-<code class="python">closed()</code> method.</p><p>If you wish to observe the interactions in more detail, adding a call
-to <code class="python">log.startLogging(sys.stdout, setStdout=0)</code>
-before the <code class="python">reactor.run()</code> call will send all
-logging to stdout.</p></div><p><a href="index.html">Index</a></p><span class="version">Version: 8.2.0</span></body></html>

+ 0 - 3
desktop/core/ext-py/Twisted/doc/conch/howto/index.html

@@ -1,3 +0,0 @@
-<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><title>Twisted Documentation: Twisted Documentation</title><link href="stylesheet.css" type="text/css" rel="stylesheet" /></head><body bgcolor="white"><h1 class="title">Twisted Documentation</h1><div class="toc"><ol></ol></div><div class="content"><span></span><ul class="toc"><li>Tutorial
-  <ul><li><a href="conch_client.html">Writing an SSH client with Conch</a></li></ul></li></ul></div><p><a href="index.html">Index</a></p><span class="version">Version: 8.2.0</span></body></html>

+ 0 - 4
desktop/core/ext-py/Twisted/doc/conch/index.html

@@ -1,4 +0,0 @@
-<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><title>Twisted Documentation: Twisted Conch Documentation</title><link href="howto/stylesheet.css" type="text/css" rel="stylesheet" /></head><body bgcolor="white"><h1 class="title">Twisted Conch Documentation</h1><div class="toc"><ol></ol></div><div class="content"><span></span><ul><li><a href="howto/index.html">Developer guides</a>: documentation on using
-Twisted Conch to develop your own applications</li><li><a href="examples/index.html">Examples</a>: short code examples using
-Twisted Conch</li></ul></div><p><a href="howto/index.html">Index</a></p><span class="version">Version: 8.2.0</span></body></html>

+ 0 - 37
desktop/core/ext-py/Twisted/doc/conch/man/cftp-man.html

@@ -1,37 +0,0 @@
-<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><title>Twisted Documentation: CFTP.1</title><link href="../howto/stylesheet.css" type="text/css" rel="stylesheet" /></head><body bgcolor="white"><h1 class="title">CFTP.1</h1><div class="toc"><ol><li><a href="#auto0">NAME</a></li><li><a href="#auto1">SYNOPSIS</a></li><li><a href="#auto2">DESCRIPTION</a></li><li><a href="#auto3">AUTHOR</a></li><li><a href="#auto4">REPORTING BUGS</a></li><li><a href="#auto5">COPYRIGHT</a></li></ol></div><div class="content"><span></span><h2>NAME<a name="auto0"></a></h2><p>cftp </p><h2>SYNOPSIS<a name="auto1"></a></h2><p>cftp [<strong>-B</strong><em> buffer_size</em>][<strong>-b</strong><em> command_file</em>][<strong>-R</strong><em> num_requests</em>][<strong>-s</strong><em> subsystem</em>]</p><h2>DESCRIPTION<a name="auto2"></a></h2><p>cftp is a client for logging into a remote machine and executing commands to send and receive file information. It can wrap a number of file transfer subsystems
-</p><p>The options are as follows:
-<dl><dt><strong>-B</strong></dt><dd>Specifies the default size of the buffer to use for sending and receiving. (Default value: 32768 bytes.)
-</dd><dt><strong>-b</strong></dt><dd>File to read commands from, '-' for stdin. (Default value: interactive/stdin.)
-</dd><dt><strong>-R</strong></dt><dd>Number of requests to make before waiting for a reply.
-</dd><dt><strong>-s</strong></dt><dd>Subsystem/server program to connect to.
-</dd></dl></p><p>The following commands are recognised by
-cftp :
-<dl><dt>cd <u>path</u></dt><dd>Change the remote directory to 'path'.
-</dd><dt>chgrp <u>gid</u><u>path</u></dt><dd>Change the gid of 'path' to 'gid'.
-</dd><dt>chmod <u>mode</u><u>path</u></dt><dd>Change mode of 'path' to 'mode'.
-</dd><dt>chown <u>uid</u><u>path</u></dt><dd>Change uid of 'path' to 'uid'.
-</dd><dt>exit</dt><dd>Disconnect from the server.
-</dd><dt>get <u>remote-path</u> [<u>local-path</u>]</dt><dd>Get remote file and optionally store it at specified local path.
-</dd><dt>help</dt><dd>Get a list of available commands.
-</dd><dt>lcd <u>path</u></dt><dd>Change local directory to 'path'.
-</dd><dt>lls [<u>ls-options</u>] [<u>path</u>]</dt><dd>Display local directory listing.
-</dd><dt>lmkdir <u>path</u></dt><dd>Create local directory.
-</dd><dt>ln <u>linkpath</u><u>targetpath</u></dt><dd>Symlink remote file.
-</dd><dt>lpwd</dt><dd>Print the local working directory.
-</dd><dt>ls [<u>-l</u>] [<u>path</u>]</dt><dd>Display remote directory listing.
-</dd><dt>mkdir <u>path</u></dt><dd>Create remote directory.
-</dd><dt>progress</dt><dd>Toggle progress bar.
-</dd><dt>put <u>local-path</u> [<u>remote-path</u>]</dt><dd>Transfer local file to remote location
-</dd><dt>pwd</dt><dd>Print the remote working directory.
-</dd><dt>quit</dt><dd>Disconnect from the server.
-</dd><dt>rename <u>oldpath</u><u>newpath</u></dt><dd>Rename remote file.
-</dd><dt>rmdir <u>path</u></dt><dd>Remove remote directory.
-</dd><dt>rm <u>path</u></dt><dd>Remove remote file.
-</dd><dt>version</dt><dd>Print the SFTP version.
-</dd><dt>?</dt><dd>Synonym for 'help'.
-</dd></dl></p><h2>AUTHOR<a name="auto3"></a></h2><p>cftp by Paul Swartz &lt;z3p@twistedmatrix.com&gt;. Man page by Mary Gardiner &lt;mary@twistedmatrix.com&gt;.
-</p><h2>REPORTING BUGS<a name="auto4"></a></h2><p>Report bugs to <em>http://twistedmatrix.com/bugs/</em></p><h2>COPYRIGHT<a name="auto5"></a></h2><p>Copyright &copy; 2005-2008 Twisted Matrix Laboratories
-This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-</p></div><p><a href="../howto/index.html">Index</a></p><span class="version">Version: 8.2.0</span></body></html>

+ 0 - 89
desktop/core/ext-py/Twisted/doc/conch/man/cftp.1

@@ -1,89 +0,0 @@
-.Dd October 8, 2005
-.Dt CFTP 1
-.Os
-.Sh NAME
-.Nm cftp
-.Nd Conch command-line SFTP client
-.Sh SYNOPSIS
-.Nm cftp
-.Op Fl B Ar buffer_size
-.Op Fl b Ar command_file
-.Op Fl R Ar num_requests
-.Op Fl s Ar subsystem
-.Os
-.Sh DESCRIPTION
-.Nm
-is a client for logging into a remote machine and executing commands to send and receive file information. It can wrap a number of file transfer subsystems
-.Pp
-The options are as follows:
-.Bl -tag -width Ds
-.It Fl B
-Specifies the default size of the buffer to use for sending and receiving. (Default value: 32768 bytes.)
-.It Fl b
-File to read commands from, '-' for stdin. (Default value: interactive/stdin.)
-.It Fl R
-Number of requests to make before waiting for a reply.
-.It Fl s
-Subsystem/server program to connect to.
-.El
-.Pp
-The following commands are recognised by
-.Nm
-:
-.Bl -tag -width Ds
-.It Ic cd Ar path
-Change the remote directory to 'path'.
-.It Ic chgrp Ar gid Ar path
-Change the gid of 'path' to 'gid'.
-.It Ic chmod Ar mode Ar path
-Change mode of 'path' to 'mode'.
-.It Ic chown Ar uid Ar path
-Change uid of 'path' to 'uid'.
-.It Ic exit
-Disconnect from the server.
-.It Ic get Ar remote-path Op Ar local-path
-Get remote file and optionally store it at specified local path.
-.It Ic help
-Get a list of available commands.
-.It Ic lcd Ar path
-Change local directory to 'path'.
-.It Ic lls Op Ar ls-options Op Ar path
-Display local directory listing.
-.It Ic lmkdir Ar path
-Create local directory.
-.It Ic ln Ar linkpath Ar targetpath
-Symlink remote file.
-.It Ic lpwd
-Print the local working directory.
-.It Ic ls Op Ar -l Op Ar path
-Display remote directory listing.
-.It Ic mkdir Ar path
-Create remote directory.
-.It Ic progress
-Toggle progress bar.
-.It Ic put Ar local-path Op Ar remote-path
-Transfer local file to remote location
-.It Ic pwd
-Print the remote working directory.
-.It Ic quit
-Disconnect from the server.
-.It Ic rename Ar oldpath Ar newpath
-Rename remote file.
-.It Ic rmdir Ar path
-Remove remote directory.
-.It Ic rm Ar path
-Remove remote file.
-.It Ic version
-Print the SFTP version.
-.It Ic ?
-Synonym for 'help'.
-.El
-.Sh AUTHOR
-cftp by Paul Swartz <z3p@twistedmatrix.com>. Man page by Mary Gardiner <mary@twistedmatrix.com>.
-.Sh "REPORTING BUGS"
-Report bugs to \fIhttp://twistedmatrix.com/bugs/\fR
-.Sh COPYRIGHT
-Copyright \(co 2005-2008 Twisted Matrix Laboratories
-.br 
-This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

+ 0 - 22
desktop/core/ext-py/Twisted/doc/conch/man/ckeygen-man.html

@@ -1,22 +0,0 @@
-<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><title>Twisted Documentation: CKEYGEN.1</title><link href="../howto/stylesheet.css" type="text/css" rel="stylesheet" /></head><body bgcolor="white"><h1 class="title">CKEYGEN.1</h1><div class="toc"><ol><li><a href="#auto0">NAME</a></li><li><a href="#auto1">SYNOPSIS</a></li><li><a href="#auto2">DESCRIPTION</a></li><li><a href="#auto3">DESCRIPTION</a></li><li><a href="#auto4">AUTHOR</a></li><li><a href="#auto5">REPORTING BUGS</a></li><li><a href="#auto6">COPYRIGHT</a></li><li><a href="#auto7">SEE ALSO</a></li></ol></div><div class="content"><span></span><h2>NAME<a name="auto0"></a></h2><p>ckeygen - connect to SSH servers
-</p><h2>SYNOPSIS<a name="auto1"></a></h2><p><strong>ckeygen</strong>  [-b <em>bits</em>] [-f <em>filename</em>] [-t <em>type</em>]<strong>[-C</strong><em>comment</em>] [-N <em>new passphrase</em>] [-P <em>old passphrase</em>]<strong>[-l]</strong>  [-p] [-q] [-y]<strong>ckeygen</strong>  --help</p><h2>DESCRIPTION<a name="auto2"></a></h2><p>The <strong>--help</strong> prints out a usage message to standard output.
-<dl><dt><strong>-b</strong>, <strong>--bits</strong>&lt;bits&gt;</dt><dd>Number of bits in the key to create (default: 1024)
-</dd><dt><strong>-f</strong>, <strong>--filename</strong>&lt;file name&gt;</dt><dd>Filename of the key file.
-</dd><dt><strong>-t</strong>, <strong>--type</strong>&lt;type&gt;</dt><dd>Type of key (rsa or dsa).
-</dd><dt><strong>-C</strong>, <strong>--comment</strong>&lt;comment&gt;</dt><dd>Provide a new comment.
-</dd><dt><strong>-N</strong>, <strong>--newpass</strong>&lt;pass phrase&gt;</dt><dd>Provide new passphrase.
-</dd><dt><strong>-P</strong>, <strong>--pass</strong>&lt;pass phrase&gt;</dt><dd>Provide old passphrase.
-</dd><dt><strong>-l</strong>, <strong>--fingerprint</strong></dt><dd>Show fingerprint of key file.
-</dd><dt><strong>-p</strong>, <strong>--changepass</strong></dt><dd>Change passphrase of private key file.
-</dd><dt><strong>-q</strong>, <strong>--quiet</strong></dt><dd>Be quiet.
-</dd><dt><strong>-y</strong>, <strong>--showpub</strong></dt><dd>Read private key file and print public key.
-</dd><dt><strong>--version</strong></dt><dd>Display version number only.
-</dd></dl></p><h2>DESCRIPTION<a name="auto3"></a></h2><p>Manipulate public/private keys in various ways.
-If no filename is given, a file name will be requested interactively.
-</p><h2>AUTHOR<a name="auto4"></a></h2><p>Written by Moshe Zadka, based on ckeygen's help messages
-</p><h2>REPORTING BUGS<a name="auto5"></a></h2><p>To report a bug, visit <em>http://twistedmatrix.com/bugs/</em></p><h2>COPYRIGHT<a name="auto6"></a></h2><p>Copyright &copy; 2002-2008 Twisted Matrix Laboratories.
-This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-</p><h2>SEE ALSO<a name="auto7"></a></h2><p>ssh(1), conch(1)
-</p></div><p><a href="../howto/index.html">Index</a></p><span class="version">Version: 8.2.0</span></body></html>

+ 0 - 58
desktop/core/ext-py/Twisted/doc/conch/man/ckeygen.1

@@ -1,58 +0,0 @@
-.TH CKEYGEN "1" "October 2002" "" ""
-.SH NAME
-ckeygen \- connect to SSH servers
-.SH SYNOPSIS
-.B ckeygen [-b \fIbits\fR] [-f \fIfilename\fR] [-t \fItype\fR]
-.B [-C \fIcomment\fR] [-N \fInew passphrase\fR] [-P \fIold passphrase\fR]
-.B [-l] [-p] [-q] [-y]
-.B ckeygen --help
-.SH DESCRIPTION
-.PP
-The \fB\--help\fR prints out a usage message to standard output.
-.TP
-\fB-b\fR, \fB--bits\fR <bits>
-Number of bits in the key to create (default: 1024)
-.TP
-\fB-f\fR, \fB--filename\fR <file name>
-Filename of the key file.
-.TP
-\fB-t\fR, \fB--type\fR <type>
-Type of key (rsa or dsa).
-.TP
-\fB-C\fR, \fB--comment\fR <comment>
-Provide a new comment.
-.TP
-\fB-N\fR, \fB--newpass\fR <pass phrase>
-Provide new passphrase.
-.TP
-\fB-P\fR, \fB--pass\fR <pass phrase>
-Provide old passphrase.
-.TP
-\fB-l\fR, \fB--fingerprint\fR
-Show fingerprint of key file.
-.TP
-\fB-p\fR, \fB--changepass\fR
-Change passphrase of private key file.
-.TP
-\fB-q\fR, \fB--quiet\fR
-Be quiet.
-.TP
-\fB-y\fR, \fB--showpub\fR
-Read private key file and print public key.
-.TP
-\fB--version\fR
-Display version number only.
-.SH DESCRIPTION
-Manipulate public/private keys in various ways.
-If no filename is given, a file name will be requested interactively.
-.SH AUTHOR
-Written by Moshe Zadka, based on ckeygen's help messages
-.SH "REPORTING BUGS"
-To report a bug, visit \fIhttp://twistedmatrix.com/bugs/\fR
-.SH COPYRIGHT
-Copyright \(co 2002-2008 Twisted Matrix Laboratories.
-.br
-This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-.SH "SEE ALSO"
-ssh(1), conch(1)

+ 0 - 81
desktop/core/ext-py/Twisted/doc/conch/man/conch-man.html

@@ -1,81 +0,0 @@
-<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><title>Twisted Documentation: CONCH.1</title><link href="../howto/stylesheet.css" type="text/css" rel="stylesheet" /></head><body bgcolor="white"><h1 class="title">CONCH.1</h1><div class="toc"><ol><li><a href="#auto0">NAME</a></li><li><a href="#auto1">SYNOPSIS</a></li><li><a href="#auto2">DESCRIPTION</a></li><li><a href="#auto3">AUTHOR</a></li><li><a href="#auto4">REPORTING BUGS</a></li><li><a href="#auto5">COPYRIGHT</a></li><li><a href="#auto6">SEE ALSO</a></li></ol></div><div class="content"><span></span><h2>NAME<a name="auto0"></a></h2><p>conch </p><h2>SYNOPSIS<a name="auto1"></a></h2><p>conch [<strong>-AaCfINnrsTtVvx</strong>][<strong>-c</strong><em> cipher_spec</em>][<strong>-e</strong><em> escape_char</em>][<strong>-i</strong><em> identity_file</em>][<strong>-K</strong><em> connection_spec</em>][<strong>-L</strong><em> port</em>:<em> host</em>:<em> hostport</em>][<strong>-l</strong><em> user</em>][<strong>-m</strong><em> mac_spec</em>][<strong>-o</strong><em> openssh_option</em>][<strong>-p</strong><em> port</em>][<strong>-R</strong><em> port</em>:<em> host</em>:<em> hostport</em>][<em> user</em>@]<em> hostname</em>[<em> command</em>]</p><h2>DESCRIPTION<a name="auto2"></a></h2><p>conch is a SSHv2 client for logging into a remote machine and executing commands.  It provides encrypted and secure communications across a possibly insecure network.  Arbitrary TCP/IP ports can also be forwarded over the secure connection.
-</p><p>conch connects and logs into 
-<em> hostname</em>(as 
-<em> user</em>or the current username).  The user must prove her/his identity through a public-key or a password.  Alternatively, if a connection is already open to a server, a new shell can be opened over the connection without having to reauthenticate.
-</p><p>If 
-<em> command</em>is specified, 
-<em> command</em>is executed instead of a shell.  If the 
-<strong>-s</strong>option is given, 
-<em> command</em>is treated as an SSHv2 subsystem name. 
-Conch supports the public-key, keyboard-interactive, and password authentications.
-</p><p>The public-key method allows the RSA or DSA algorithm to be used.  The client uses his/her private key,
-or
-to sign the session identifier, known only by the client and server.  The server checks that the matching public key is valid for the user, and that the signature is correct.
-</p><p>If public-key authentication fails,
-conch can authenticate by sending an encrypted password over the connection.
-conch has the ability to multiplex multiple shells, commands and TCP/IP ports over the same secure connection.  To disable multiplexing for a connection, use the
-<strong>-I</strong>flag.
-</p><p>The
-<strong>-K</strong>option determines how the client connects to the remote host.  It is a comma-separated list of the methods to use, in order of preference.  The two connection methods are 
-(for connecting over a multiplexed connection) and 
-(to connect directly).
-To disable connecting over a multiplexed connection, do not include
-in the preference list.
-</p><p>As an example of how connection sharing works, to speed up CVS over SSH:
-</p><p>conch --noshell --fork -l cvs_user cvs_host
-set CVS_RSH=<strong>conch</strong></p><p>Now, when CVS connects to cvs_host as cvs_user, instead of making a new connection to the server,
-conch will add a new channel to the existing connection.  This saves the cost of repeatedly negotiating the cryptography and authentication.
-</p><p>The options are as follows:
-<dl><dt><strong>-A</strong></dt><dd>Enables authentication agent forwarding.
-</dd><dt><strong>-a</strong></dt><dd>Disables authentication agent forwarding (default).
-</dd><dt><strong>-C</strong></dt><dd>Enable compression.
-</dd><dt><strong>-c</strong></dt><dd><em> cipher_spec</em>Selects encryption algorithms to be used for this connection, as a comma-separated list of ciphers in order of preference.  The list that
-conch supports is (in order of default preference): aes256-ctr, aes256-cbc, aes192-ctr, aes192-cbc, aes128-ctr, aes128-cbc, cast128-ctr, cast128-cbc, blowfish-ctr, blowfish, idea-ctr, idea-cbc, 3des-ctr, 3des-cbc.
-</dd><dt><strong>-e</strong></dt><dd><em> ch</em>| ^ch | noneSets the escape character for sessions with a PTY (default:
-The escape character is only recognized at the beginning of a line (after a newline).
-The escape character followed by a dot
-closes the connection;
-followed by ^Z suspends the connection;
-and followed by the escape character sends the escape character once.
-Setting the character to
-disables any escapes.
-</dd><dt><strong>-f</strong></dt><dd>Fork to background after authentication.
-</dd><dt><strong>-I</strong></dt><dd>Do not allow connection sharing over this connection.
-</dd><dt><strong>-i</strong></dt><dd><em> identity_spec</em>The file from which the identity (private key) for RSA or DSA authentication is read.
-The defaults are
-and
-It is possible to use this option more than once to use more than one private key.
-</dd><dt><strong>-K</strong></dt><dd><em> connection_spec</em>Selects methods for connection to the server, as a comma-separated list of methods in order of preference.  See
-for more information.
-</dd><dt><strong>-L</strong></dt><dd><em> port</em>: host : hostportSpecifies that the given port on the client host is to be forwarded to the given host and port on the remote side.  This allocates a socket to listen to
-<em> port</em>on the local side, and when connections are made to that socket, they are forwarded over the secure channel and a connection is made to
-<em> host</em>port
-<em> hostport</em>from the remote machine.
-Only root can forward privieged ports.
-</dd><dt><strong>-l</strong></dt><dd><em> user</em>Log in using this username.
-</dd><dt><strong>-m</strong></dt><dd><em> mac_spec</em>Selects MAC (message authentication code) algorithms, as a comma-separated list in order of preference.  The list that
-conch supports is (in order of preference): hmac-sha1, hmac-md5.
-</dd><dt><strong>-N</strong></dt><dd>Do not execute a shell or command.
-</dd><dt><strong>-n</strong></dt><dd>Redirect input from /dev/null.
-</dd><dt><strong>-o</strong></dt><dd><em> openssh_option</em>Ignored OpenSSH options.
-</dd><dt><strong>-p</strong></dt><dd><em> port</em>The port to connect to on the server.
-</dd><dt><strong>-R</strong></dt><dd><em> port</em>: host : hostportSpecifies that the given port on the remote host is to be forwarded to the given host and port on the local side.  This allocates a socket to listen to
-<em> port</em>on the remote side, and when connections are made to that socket, they are forwarded over the secure channel and a connection is made to
-<em> host</em>port
-<em> hostport</em>from the client host.
-Only root can forward privieged ports.
-</dd><dt><strong>-s</strong></dt><dd>Reconnect to the server if the connection is lost.
-</dd><dt><strong>-s</strong></dt><dd>Invoke
-<em> command</em>(mandatory) as a SSHv2 subsystem.
-</dd><dt><strong>-T</strong></dt><dd>Do not allocate a TTY.
-</dd><dt><strong>-t</strong></dt><dd>Allocate a TTY even if command is given.
-</dd><dt><strong>-V</strong></dt><dd>Display version number only.
-</dd><dt><strong>-v</strong></dt><dd>Log to stderr.
-</dd><dt><strong>-x</strong></dt><dd>Disable X11 connection forwarding (default).
-</dd></dl></p><h2>AUTHOR<a name="auto3"></a></h2><p>Written by Paul Swartz &lt;z3p@twistedmatrix.com&gt;.
-</p><h2>REPORTING BUGS<a name="auto4"></a></h2><p>To report a bug, visit <em>http://twistedmatrix.com/bugs/</em></p><h2>COPYRIGHT<a name="auto5"></a></h2><p>Copyright &copy; 2002-2008 Twisted Matrix Laboratories.
-This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-</p><h2>SEE ALSO<a name="auto6"></a></h2><p>ssh(1)
-</p></div><p><a href="../howto/index.html">Index</a></p><span class="version">Version: 8.2.0</span></body></html>

+ 0 - 206
desktop/core/ext-py/Twisted/doc/conch/man/conch.1

@@ -1,206 +0,0 @@
-.Dd May 22, 2004
-.Dt CONCH 1
-.Os
-.Sh NAME
-.Nm conch
-.Nd Conch SSH client
-.Sh SYNOPSIS
-.Nm conch
-.Op Fl AaCfINnrsTtVvx
-.Op Fl c Ar cipher_spec
-.Op Fl e Ar escape_char
-.Op Fl i Ar identity_file
-.Op Fl K Ar connection_spec
-.Bk -words
-.Oo Fl L Xo
-.Sm off
-.Ar port :
-.Ar host :
-.Ar hostport
-.Sm on
-.Xc
-.Oc
-.Ek
-.Op Fl l Ar user
-.Op Fl m Ar mac_spec
-.Op Fl o Ar openssh_option
-.Op Fl p Ar port
-.Bk -words
-.Oo Fl R Xo
-.Sm off
-.Ar port :
-.Ar host :
-.Ar hostport
-.Sm on
-.Xc
-.Oc
-.Ek
-.Oo Ar user Ns @ Ns Oc Ar hostname
-.Op Ar command
-.Sh DESCRIPTION
-.Nm
-is a SSHv2 client for logging into a remote machine and executing commands.  It provides encrypted and secure communications across a possibly insecure network.  Arbitrary TCP/IP ports can also be forwarded over the secure connection.
-.Pp 
-.Nm
-connects and logs into 
-.Ar hostname
-(as 
-.Ar user
-or the current username).  The user must prove her/his identity through a public\-key or a password.  Alternatively, if a connection is already open to a server, a new shell can be opened over the connection without having to reauthenticate.
-.Pp 
-If 
-.Ar command
-is specified, 
-.Ar command
-is executed instead of a shell.  If the 
-.Fl s
-option is given, 
-.Ar command
-is treated as an SSHv2 subsystem name. 
-.Ss Authentication
-Conch supports the public-key, keyboard-interactive, and password authentications.
-.Pp
-The public-key method allows the RSA or DSA algorithm to be used.  The client uses his/her private key,
-.Pa $HOME/.ssh/id_rsa
-or
-.Pa $HOME/.ssh/id_dsa
-to sign the session identifier, known only by the client and server.  The server checks that the matching public key is valid for the user, and that the signature is correct.
-.Pp
-If public-key authentication fails,
-.Nm
-can authenticate by sending an encrypted password over the connection.
-.Ss Connection sharing
-.Nm
-has the ability to multiplex multiple shells, commands and TCP/IP ports over the same secure connection.  To disable multiplexing for a connection, use the
-.Fl I
-flag.
-.Pp
-The
-.Fl K
-option determines how the client connects to the remote host.  It is a comma-separated list of the methods to use, in order of preference.  The two connection methods are 
-.Ql unix
-(for connecting over a multiplexed connection) and 
-.Ql direct 
-(to connect directly).
-To disable connecting over a multiplexed connection, do not include
-.Ql unix
-in the preference list.
-.Pp
-As an example of how connection sharing works, to speed up CVS over SSH:
-.Pp
-.Nm
---noshell --fork -l cvs_user cvs_host
-.br
-set CVS_RSH=\fBconch\fR
-.Pp
-Now, when CVS connects to cvs_host as cvs_user, instead of making a new connection to the server,
-.Nm
-will add a new channel to the existing connection.  This saves the cost of repeatedly negotiating the cryptography and authentication.
-.Pp
-The options are as follows:
-.Bl -tag -width Ds
-.It Fl A
-Enables authentication agent forwarding.
-.It Fl a
-Disables authentication agent forwarding (default).
-.It Fl C
-Enable compression.
-.It Fl c Ar cipher_spec
-Selects encryption algorithms to be used for this connection, as a comma-separated list of ciphers in order of preference.  The list that
-.Nm
-supports is (in order of default preference): aes256-ctr, aes256-cbc, aes192-ctr, aes192-cbc, aes128-ctr, aes128-cbc, cast128-ctr, cast128-cbc, blowfish-ctr, blowfish, idea-ctr, idea-cbc, 3des-ctr, 3des-cbc.
-.It Fl e Ar ch | ^ch | none
-Sets the escape character for sessions with a PTY (default:
-.Ql ~ ) .
-The escape character is only recognized at the beginning of a line (after a newline).
-The escape character followed by a dot
-.Pq Ql \&.
-closes the connection;
-followed by ^Z suspends the connection;
-and followed by the escape character sends the escape character once.
-Setting the character to
-.Dq none
-disables any escapes.
-.It Fl f
-Fork to background after authentication.
-.It Fl I
-Do not allow connection sharing over this connection.
-.It Fl i Ar identity_spec
-The file from which the identity (private key) for RSA or DSA authentication is read.
-The defaults are
-.Pa $HOME/.ssh/id_rsa
-and
-.Pa $HOME/.ssh/id_dsa . 
-It is possible to use this option more than once to use more than one private key.
-.It Fl K Ar connection_spec
-Selects methods for connection to the server, as a comma-separated list of methods in order of preference.  See
-.Cm Connection sharing
-for more information.
-.It Fl L Xo
-.Sm off
-.Ar port : host : hostport
-.Sm on
-.Xc
-Specifies that the given port on the client host is to be forwarded to the given host and port on the remote side.  This allocates a socket to listen to
-.Ar port 
-on the local side, and when connections are made to that socket, they are forwarded over the secure channel and a connection is made to
-.Ar host
-port
-.Ar hostport
-from the remote machine.
-Only root can forward privieged ports.
-.It Fl l Ar user
-Log in using this username.
-.It Fl m Ar mac_spec
-Selects MAC (message authentication code) algorithms, as a comma-separated list in order of preference.  The list that
-.Nm
-supports is (in order of preference): hmac-sha1, hmac-md5.
-.It Fl N
-Do not execute a shell or command.
-.It Fl n
-Redirect input from /dev/null.
-.It Fl o Ar openssh_option
-Ignored OpenSSH options.
-.It Fl p Ar port
-The port to connect to on the server.
-.It Fl R Xo
-.Sm off
-.Ar port : host : hostport
-.Sm on
-.Xc
-Specifies that the given port on the remote host is to be forwarded to the given host and port on the local side.  This allocates a socket to listen to
-.Ar port 
-on the remote side, and when connections are made to that socket, they are forwarded over the secure channel and a connection is made to
-.Ar host
-port
-.Ar hostport
-from the client host.
-Only root can forward privieged ports.
-.It Fl s
-Reconnect to the server if the connection is lost.
-.It Fl s
-Invoke
-.Ar command
-(mandatory) as a SSHv2 subsystem.
-.It Fl T
-Do not allocate a TTY.
-.It Fl t
-Allocate a TTY even if command is given.
-.It Fl V
-Display version number only.
-.It Fl v
-Log to stderr.
-.It Fl x
-Disable X11 connection forwarding (default).
-.El
-.Sh AUTHOR
-Written by Paul Swartz <z3p@twistedmatrix.com>.
-.Sh "REPORTING BUGS"
-To report a bug, visit \fIhttp://twistedmatrix.com/bugs/\fR
-.Sh COPYRIGHT
-Copyright \(co 2002-2008 Twisted Matrix Laboratories.
-.br 
-This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-.Sh SEE ALSO
-ssh(1)

+ 0 - 27
desktop/core/ext-py/Twisted/doc/conch/man/tkconch-man.html

@@ -1,27 +0,0 @@
-<?xml version="1.0"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><title>Twisted Documentation: CONCH.1</title><link href="../howto/stylesheet.css" type="text/css" rel="stylesheet" /></head><body bgcolor="white"><h1 class="title">CONCH.1</h1><div class="toc"><ol><li><a href="#auto0">NAME</a></li><li><a href="#auto1">SYNOPSIS</a></li><li><a href="#auto2">DESCRIPTION</a></li><li><a href="#auto3">DESCRIPTION</a></li><li><a href="#auto4">AUTHOR</a></li><li><a href="#auto5">REPORTING BUGS</a></li><li><a href="#auto6">COPYRIGHT</a></li><li><a href="#auto7">SEE ALSO</a></li></ol></div><div class="content"><span></span><h2>NAME<a name="auto0"></a></h2><p>tkconch - connect to SSH servers graphically
-</p><h2>SYNOPSIS<a name="auto1"></a></h2><p><strong>conch</strong>  [-l <em>user</em>] [-i <em>identity</em> [ -i <em>identity</em> ... ]] [-c <em>cipher</em>] [-m <em>MAC</em>] [-p <em>port</em>] [-n] [-t] [-T] [-V] [-C] [-N] [-s] [arg [...]]</p><p><strong>conch</strong>  --help</p><h2>DESCRIPTION<a name="auto2"></a></h2><p>The <strong>--help</strong> prints out a usage message to standard output.
-<dl><dt><strong>-l</strong>, <strong>--user</strong>&lt;user&gt;</dt><dd>Log in using this user name.
-</dd><dt><strong>-e</strong>, <strong>--escape</strong>&lt;escape character&gt;</dt><dd>Set escape character; 'none' = disable (default: ~)
-</dd><dt><strong>-i</strong>, <strong>--identity</strong>&lt;identity&gt;</dt><dd>Add an identity file for public key authentication (default: ~/.ssh/identity)
-</dd><dt><strong>-c</strong>, <strong>--cipher</strong>&lt;cipher&gt;</dt><dd>Cipher algorithm to use.
-</dd><dt><strong>-m</strong>, <strong>--macs</strong>&lt;mac&gt;</dt><dd>Specify MAC algorithms for protocol version 2.
-</dd><dt><strong>-p</strong>, <strong>--port</strong>&lt;port&gt;</dt><dd>Port to connect to.
-</dd><dt><strong>-L</strong>, <strong>--localforward</strong>&lt;listen-port:host:port&gt;</dt><dd>Forward local port to remote address.
-</dd><dt><strong>-R</strong>, <strong>--remoteforward</strong>&lt;listen-port:host:port&gt;</dt><dd>Forward remote port to local address.
-</dd><dt><strong>-t</strong>, <strong>--tty</strong></dt><dd>Allocate a tty even if command is given.
-</dd><dt><strong>-n</strong>, <strong>--notty</strong></dt><dd>Do not allocate a tty.
-</dd><dt><strong>-V</strong>, <strong>--version</strong></dt><dd>Display version number only.
-</dd><dt><strong>-C</strong>, <strong>--compress</strong></dt><dd>Enable compression.
-</dd><dt><strong>-a</strong>, <strong>--ansilog</strong></dt><dd>Print the received data to stdout.
-</dd><dt><strong>-N</strong>, <strong>--noshell</strong></dt><dd>Do not execute a shell or command.
-</dd><dt><strong>-s</strong>, <strong>--subsystem</strong></dt><dd>Invoke command (mandatory) as SSH2 subsystem.
-</dd><dt><strong>--log</strong></dt><dd>Print the receieved data to stderr.
-</dd></dl></p><h2>DESCRIPTION<a name="auto3"></a></h2><p>Open an SSH connection to specified server, and either run the command
-given there or open a remote interactive shell.
-</p><h2>AUTHOR<a name="auto4"></a></h2><p>Written by Moshe Zadka, based on conch's help messages
-</p><h2>REPORTING BUGS<a name="auto5"></a></h2><p>To report a bug, visit <em>http://twistedmatrix.com/bugs/</em></p><h2>COPYRIGHT<a name="auto6"></a></h2><p>Copyright &copy; 2002-2008 Twisted Matrix Laboratories.
-This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-</p><h2>SEE ALSO<a name="auto7"></a></h2><p>ssh(1)
-</p></div><p><a href="../howto/index.html">Index</a></p><span class="version">Version: 8.2.0</span></body></html>

+ 0 - 72
desktop/core/ext-py/Twisted/doc/conch/man/tkconch.1

@@ -1,72 +0,0 @@
-.TH CONCH "1" "October 2002" "" ""
-.SH NAME
-tkconch \- connect to SSH servers graphically
-.SH SYNOPSIS
-.B conch [-l \fIuser\fR] [-i \fIidentity\fR [ -i \fIidentity\fR ... ]] [-c \fIcipher\fR] [-m \fIMAC\fR] [-p \fIport\fR] [-n] [-t] [-T] [-V] [-C] [-N] [-s] [arg [...]]
-.PP
-.B conch --help
-.SH DESCRIPTION
-.PP
-The \fB\--help\fR prints out a usage message to standard output.
-.TP
-\fB-l\fR, \fB--user\fR <user>
-Log in using this user name.
-.TP
-\fB-e\fR, \fB--escape\fR <escape character>
-Set escape character; 'none' = disable (default: ~)
-.TP
-\fB-i\fR, \fB--identity\fR <identity>
-Add an identity file for public key authentication (default: ~/.ssh/identity)
-.TP
-\fB-c\fR, \fB--cipher\fR <cipher>
-Cipher algorithm to use.
-.TP
-\fB-m\fR, \fB--macs\fR <mac>
-Specify MAC algorithms for protocol version 2.
-.TP
-\fB-p\fR, \fB--port\fR <port>
-Port to connect to.
-.TP
-\fB-L\fR, \fB--localforward\fR <listen-port:host:port>
-Forward local port to remote address.
-.TP
-\fB-R\fR, \fB--remoteforward\fR <listen-port:host:port>
-Forward remote port to local address.
-.TP
-\fB-t\fR, \fB--tty\fR
-Allocate a tty even if command is given.
-.TP
-\fB-n\fR, \fB--notty\fR
-Do not allocate a tty.
-.TP
-\fB-V\fR, \fB--version\fR
-Display version number only.
-.TP
-\fB-C\fR, \fB--compress\fR
-Enable compression.
-.TP
-\fB-a\fR, \fB--ansilog\fR
-Print the received data to stdout.
-.TP
-\fB-N\fR, \fB--noshell\fR
-Do not execute a shell or command.
-.TP
-\fB-s\fR, \fB--subsystem\fR
-Invoke command (mandatory) as SSH2 subsystem.
-.TP
-\fB--log\fR
-Print the receieved data to stderr.
-.SH DESCRIPTION
-Open an SSH connection to specified server, and either run the command
-given there or open a remote interactive shell.
-.SH AUTHOR
-Written by Moshe Zadka, based on conch's help messages
-.SH "REPORTING BUGS"
-To report a bug, visit \fIhttp://twistedmatrix.com/bugs/\fR
-.SH COPYRIGHT
-Copyright \(co 2002-2008 Twisted Matrix Laboratories.
-.br
-This is free software; see the source for copying conditions.  There is NO
-warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-.SH "SEE ALSO"
-ssh(1)

+ 0 - 66
desktop/core/ext-py/Twisted/doc/core/benchmarks/failure.py

@@ -1,66 +0,0 @@
-
-"""See how slow failure creation is"""
-
-import random
-from twisted.python import failure
-
-random.seed(10050)
-O = [0, 20, 40, 60, 80, 10, 30, 50, 70, 90]
-DEPTH = 30
-
-def pickVal():
-    return random.choice([None, 1, 'Hello', [], {1: 1}, (1, 2, 3)])
-
-def makeLocals(n):
-    return ';'.join(['x%d = %s' % (i, pickVal()) for i in range(n)])
-
-for nLocals in O:
-    for i in range(DEPTH):
-        s = """
-def deepFailure%d_%d():
-    %s
-    deepFailure%d_%d()
-""" % (nLocals, i, makeLocals(nLocals), nLocals, i + 1)
-    exec s
-
-    exec """
-def deepFailure%d_%d():
-    1 / 0
-""" % (nLocals, DEPTH)
-
-R = range(5000)
-def fail(n):
-    for i in R:
-        try:
-            eval('deepFailure%d_0' % n)()
-        except:
-            failure.Failure()
-
-def fail_str(n):
-    for i in R:
-        try:
-            eval('deepFailure%d_0' % n)()
-        except:
-            str(failure.Failure())
-
-class PythonException(Exception): pass
-
-def fail_easy(n):
-    for i in R:
-        try:
-            failure.Failure(PythonException())
-        except:
-            pass
-
-from timer import timeit
-# for i in O:
-#     timeit(fail, 1, i)
-
-# for i in O:
-#     print 'easy failing', i, timeit(fail_easy, 1, i)
-
-for i in O:
-    print 'failing', i, timeit(fail, 1, i)
-
-# for i in O:
-#     print 'string failing', i, timeit(fail_str, 1, i)

+ 0 - 47
desktop/core/ext-py/Twisted/doc/core/benchmarks/linereceiver.py

@@ -1,47 +0,0 @@
-import math, time
-
-from twisted.protocols import basic
-
-class CollectingLineReceiver(basic.LineReceiver):
-    def __init__(self):
-        self.lines = []
-        self.lineReceived = self.lines.append
-
-def deliver(proto, chunks):
-    map(proto.dataReceived, chunks)
-
-def benchmark(chunkSize, lineLength, numLines):
-    bytes = ('x' * lineLength + '\r\n') * numLines
-    chunkCount = len(bytes) / chunkSize + 1
-    chunks = []
-    for n in xrange(chunkCount):
-        chunks.append(bytes[n*chunkSize:(n+1)*chunkSize])
-    assert ''.join(chunks) == bytes, (chunks, bytes)
-    p = CollectingLineReceiver()
-
-    before = time.clock()
-    deliver(p, chunks)
-    after = time.clock()
-
-    assert bytes.splitlines() == p.lines, (bytes.splitlines(), p.lines)
-
-    print 'chunkSize:', chunkSize,
-    print 'lineLength:', lineLength,
-    print 'numLines:', numLines,
-    print 'CPU Time: ', after - before
-
-
-
-def main():
-    for numLines in 100, 1000:
-        for lineLength in (10, 100, 1000):
-            for chunkSize in (1, 500, 5000):
-                benchmark(chunkSize, lineLength, numLines)
-
-    for numLines in 10000, 50000:
-        for lineLength in (1000, 2000):
-            for chunkSize in (51, 500, 5000):
-                benchmark(chunkSize, lineLength, numLines)
-
-if __name__ == '__main__':
-    main()

+ 0 - 26
desktop/core/ext-py/Twisted/doc/core/benchmarks/task.py

@@ -1,26 +0,0 @@
-
-"""
-Benchmarks for L{twisted.internet.task}.
-"""
-
-from timer import timeit
-
-from twisted.internet import task
-
-def test_performance():
-    """
-    L{LoopingCall} should not take long to skip a lot of iterations.
-    """
-    clock = task.Clock()
-    call = task.LoopingCall(lambda: None)
-    call.clock = clock
-
-    call.start(0.1)
-    clock.advance(1000000)
-
-
-def main():
-    print "LoopingCall large advance takes", timeit(test_performance, iter=1)
-
-if __name__ == '__main__':
-    main()

+ 0 - 19
desktop/core/ext-py/Twisted/doc/core/benchmarks/timer.py

@@ -1,19 +0,0 @@
-
-"""Helper stuff for things"""
-
-import gc
-gc.disable()
-print 'Disabled GC'
-
-def timeit(func, iter = 1000, *args, **kwargs):
-    """timeit(func, iter = 1000 *args, **kwargs) -> elapsed time
-    
-    calls func iter times with args and kwargs, returns time elapsed
-    """
-
-    import time
-    r = range(iter)
-    t = time.time()
-    for i in r:
-        func(*args, **kwargs)
-    return time.time() - t

+ 0 - 60
desktop/core/ext-py/Twisted/doc/core/benchmarks/tpclient.py

@@ -1,60 +0,0 @@
-"""Throughput test."""
-
-import time, sys
-from twisted.internet import reactor, protocol
-from twisted.python import log
-
-TIMES = 10000
-S = "0123456789" * 1240
-
-toReceive = len(S) * TIMES
-
-class Sender(protocol.Protocol):
-
-    def connectionMade(self):
-        start()
-        self.numSent = 0
-        self.received = 0
-        self.transport.registerProducer(self, 0)
-
-    def stopProducing(self):
-        pass
-
-    def pauseProducing(self):
-        pass
-    
-    def resumeProducing(self):
-        self.numSent += 1
-        self.transport.write(S)
-        if self.numSent == TIMES:
-            self.transport.unregisterProducer()
-            self.transport.loseConnection()
-
-    def connectionLost(self, reason):
-        shutdown(self.numSent == TIMES)
-
-
-started = None
-
-def start():
-    global started
-    started = time.time()
-
-def shutdown(success):
-    if not success:
-        raise SystemExit, "failure or something"
-    passed = time.time() - started
-    print "Throughput (send): %s kbytes/sec" % ((toReceive / passed) / 1024)
-    reactor.stop()
-
-
-def main():
-    f = protocol.ClientFactory()
-    f.protocol = Sender
-    reactor.connectTCP(sys.argv[1], int(sys.argv[2]), f)
-    reactor.run()
-
-
-if __name__ == '__main__':
-    #log.startLogging(sys.stdout)
-    main()

+ 0 - 22
desktop/core/ext-py/Twisted/doc/core/benchmarks/tpclient_nt.py

@@ -1,22 +0,0 @@
-"""Non-twisted throughput client."""
-
-import socket, time, sys
-
-TIMES = 50000
-S = "0123456789" * 1024
-sent = len(S) * TIMES
-
-def main():
-    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-    s.connect((sys.argv[1], int(sys.argv[2])))
-    start = time.time()
-    i = 0
-    while i < TIMES:
-        i += 1
-        s.sendall(S)
-    passed = time.time() - start
-    print "Throughput: %s kbytes/sec" % ((sent / passed) / 1024)
-    s.close()
-
-if __name__ == '__main__':
-    main()

+ 0 - 19
desktop/core/ext-py/Twisted/doc/core/benchmarks/tpserver.py

@@ -1,19 +0,0 @@
-"""Throughput server."""
-
-import sys
-
-from twisted.protocols.wire import Discard
-from twisted.internet import protocol, reactor
-from twisted.python import log
-
-
-def main():
-    f = protocol.ServerFactory()
-    f.protocol = Discard
-    reactor.listenTCP(8000, f)
-    reactor.run()
-
-
-if __name__ == '__main__':
-    main()
-

+ 0 - 22
desktop/core/ext-py/Twisted/doc/core/benchmarks/tpserver_nt.py

@@ -1,22 +0,0 @@
-"""Non-twisted throughput server."""
-
-import socket, signal, sys
-
-def signalhandler(*args):
-    print "alarm!"
-    sys.stdout.flush()
-
-signal.signal(signal.SIGALRM, signalhandler)
-
-s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-s.bind(('', 8001))
-s.listen(1)
-while 1:
-    c, (h, p) = s.accept()
-    c.settimeout(30)
-    signal.alarm(5)
-    while 1:
-        d = c.recv(16384)
-        if not d:
-            break
-    c.close()

+ 0 - 26
desktop/core/ext-py/Twisted/doc/core/examples/ampclient.py

@@ -1,26 +0,0 @@
-from twisted.internet import reactor, defer
-from twisted.internet.protocol import ClientCreator
-from twisted.protocols import amp
-from ampserver import Sum, Divide
-
-
-def doMath():
-    d1 = ClientCreator(reactor, amp.AMP).connectTCP(
-        '127.0.0.1', 1234).addCallback(
-            lambda p: p.callRemote(Sum, a=13, b=81)).addCallback(
-                lambda result: result['total'])
-    def trapZero(result):
-        result.trap(ZeroDivisionError)
-        print "Divided by zero: returning INF"
-        return 1e1000
-    d2 = ClientCreator(reactor, amp.AMP).connectTCP(
-        '127.0.0.1', 1234).addCallback(
-            lambda p: p.callRemote(Divide, numerator=1234,
-                                   denominator=0)).addErrback(trapZero)
-    def done(result):
-        print 'Done with math:', result
-    defer.DeferredList([d1, d2]).addCallback(done)
-
-if __name__ == '__main__':
-    doMath()
-    reactor.run()

+ 0 - 40
desktop/core/ext-py/Twisted/doc/core/examples/ampserver.py

@@ -1,40 +0,0 @@
-from twisted.protocols import amp
-
-class Sum(amp.Command):
-    arguments = [('a', amp.Integer()),
-                 ('b', amp.Integer())]
-    response = [('total', amp.Integer())]
-
-
-class Divide(amp.Command):
-    arguments = [('numerator', amp.Integer()),
-                 ('denominator', amp.Integer())]
-    response = [('result', amp.Float())]
-    errors = {ZeroDivisionError: 'ZERO_DIVISION'}
-
-
-class Math(amp.AMP):
-    def sum(self, a, b):
-        total = a + b
-        print 'Did a sum: %d + %d = %d' % (a, b, total)
-        return {'total': total}
-    Sum.responder(sum)
-
-    def divide(self, numerator, denominator):
-        result = float(numerator) / denominator
-        print 'Divided: %d / %d = %f' % (numerator, denominator, result)
-        return {'result': result}
-    Divide.responder(divide)
-
-
-def main():
-    from twisted.internet import reactor
-    from twisted.internet.protocol import Factory
-    pf = Factory()
-    pf.protocol = Math
-    reactor.listenTCP(1234, pf)
-    print 'started'
-    reactor.run()
-
-if __name__ == '__main__':
-    main()

+ 0 - 79
desktop/core/ext-py/Twisted/doc/core/examples/bananabench.py

@@ -1,79 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-import sys
-import time
-try:
-    import cStringIO as StringIO
-except ImportError:
-    import StringIO
-    
-# Twisted Imports
-from twisted.spread import banana
-from twisted.internet import protocol
-
-iterationCount = 10000
-
-class BananaBench:
-    r = range( iterationCount )
-    def setUp(self, encClass):
-        self.io = StringIO.StringIO()
-        self.enc = encClass()
-        self.enc.makeConnection(protocol.FileWrapper(self.io))
-        self.enc._selectDialect("none")
-        self.enc.expressionReceived = self.putResult
-
-    def putResult(self, result):
-        self.result = result
-
-    def tearDown(self):
-        self.enc.connectionLost()
-        del self.enc
-
-    def testEncode(self, value):
-        starttime = time.time()
-        for i in self.r:
-            self.enc.sendEncoded(value)
-            self.io.truncate(0)
-        endtime = time.time()
-        print '    Encode took %s seconds' % (endtime - starttime)
-        return endtime - starttime
-
-    def testDecode(self, value):
-        self.enc.sendEncoded(value)
-        encoded = self.io.getvalue()
-        starttime = time.time()
-        for i in self.r:
-            self.enc.dataReceived(encoded)
-        endtime = time.time()
-        print '    Decode took %s seconds' % (endtime - starttime)
-        return endtime - starttime
-
-    def performTest(self, method, data, encClass):
-        self.setUp(encClass)
-        method(data)
-        self.tearDown()
-
-    def runTests(self, testData):
-        print 'Test data is: %s' % testData
-        print '  Using Pure Python Banana:'
-        self.performTest(self.testEncode, testData, banana.Banana)
-        self.performTest(self.testDecode, testData, banana.Banana)
-
-bench = BananaBench()
-print 'Doing %s iterations of each test.' % iterationCount
-print ''
-testData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
-bench.runTests(testData)
-testData = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
-bench.runTests(testData)
-testData = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
-bench.runTests(testData)
-testData = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
-bench.runTests(testData)
-testData = [1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l, 9l, 10l]
-bench.runTests(testData)
-testData = [1, 2, [3, 4], [30.5, 40.2], 5, ["six", "seven", ["eight", 9]], [10], []]
-bench.runTests(testData)
-

+ 0 - 37
desktop/core/ext-py/Twisted/doc/core/examples/chatserver.py

@@ -1,37 +0,0 @@
-"""The most basic chat protocol possible.
-
-run me with twistd -y chatserver.py, and then connect with multiple
-telnet clients to port 1025
-"""
-
-from twisted.protocols import basic
-
-
-
-class MyChat(basic.LineReceiver):
-    def connectionMade(self):
-        print "Got new client!"
-        self.factory.clients.append(self)
-
-    def connectionLost(self, reason):
-        print "Lost a client!"
-        self.factory.clients.remove(self)
-
-    def lineReceived(self, line):
-        print "received", repr(line)
-        for c in self.factory.clients:
-            c.message(line)
-
-    def message(self, message):
-        self.transport.write(message + '\n')
-
-
-from twisted.internet import protocol
-from twisted.application import service, internet
-
-factory = protocol.ServerFactory()
-factory.protocol = MyChat
-factory.clients = []
-
-application = service.Application("chatserver")
-internet.TCPServer(1025, factory).setServiceParent(application)

+ 0 - 105
desktop/core/ext-py/Twisted/doc/core/examples/courier.py

@@ -1,105 +0,0 @@
-#!/usr/bin/python
-"""Example of a interfacing to Courier's mail filter interface"""
-
-LOGFILE = '/tmp/filter.log'
-
-# Setup log file
-from twisted.python import log
-log.startLogging(open(LOGFILE, 'a'))
-import sys
-sys.stderr = log.logfile
-
-# Twisted imports
-from twisted.internet import reactor, stdio
-from twisted.internet.protocol import Protocol, Factory
-from twisted.protocols import basic
-
-FILTERS='/var/lib/courier/filters'
-ALLFILTERS='/var/lib/courier/allfilters'
-FILTERNAME='twistedfilter'
-
-import os, os.path 
-from syslog import syslog, openlog, LOG_MAIL
-from rfc822 import Message
-
-def trace_dump():
-    t,v,tb = sys.exc_info()
-    openlog(FILTERNAME, 0, LOG_MAIL)
-    syslog('Unhandled exception: %s - %s' % (v, t))
-    while tb:
-        syslog('Trace: %s:%s %s' % (tb.tb_frame.f_code.co_filename,tb.tb_frame.f_code.co_name,tb.tb_lineno))
-        tb = tb.tb_next
-    # just to be safe
-    del tb
-
-def safe_del(file):
-    try:
-        if os.path.isdir(file):
-            os.removedirs(file)
-        else:
-            os.remove(file)
-    except OSError:
-        pass
-
-
-class DieWhenLost(Protocol):
-    def connectionLost(self, reason=None):
-        reactor.stop()
-
-
-class MailProcessor(basic.LineReceiver):
-    """I process a mail message.
-    
-    Override filterMessage to do any filtering you want."""
-    messageFilename = None
-    delimiter = '\n'
-    
-    def connectionMade(self):
-    log.msg('Connection from %r' % self.transport)
-        self.state = 'connected'
-        self.metaInfo = []
-
-    def lineReceived(self, line):
-        if self.state == 'connected':
-            self.messageFilename = line
-            self.state = 'gotMessageFilename'
-        if self.state == 'gotMessageFilename':
-            if line:
-                self.metaInfo.append(line)
-            else:
-                if not self.metaInfo:
-                    self.transport.loseConnection()
-                    return
-                self.filterMessage()
-
-    def filterMessage(self):
-        """Override this.
-
-        A trivial example is included.
-        """
-        try:
-            m = Message(open(self.messageFilename))
-            self.sendLine('200 Ok')
-        except:
-            trace_dump()
-            self.sendLine('435 %s processing error' % FILTERNAME)
-        
-
-def main():
-    # Listen on the UNIX socket
-    f = Factory()
-    f.protocol = MailProcessor
-    safe_del('%s/%s' % (ALLFILTERS, FILTERNAME))
-    reactor.listenUNIX('%s/%s' % (ALLFILTERS, FILTERNAME), f, 10)
-
-    # Once started, close fd 3 to let Courier know we're ready
-    reactor.callLater(0, os.close, 3)
-
-    # When stdin is closed, it's time to exit.
-    s = stdio.StandardIO(DieWhenLost())
-
-    # Go!
-    reactor.run()
-
-if __name__ == '__main__':
-    main()

+ 0 - 163
desktop/core/ext-py/Twisted/doc/core/examples/cred.py

@@ -1,163 +0,0 @@
-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-
-import sys
-from zope.interface import implements, Interface
-
-from twisted.protocols import basic
-from twisted.internet import protocol
-from twisted.python import log
-
-from twisted.cred import error
-from twisted.cred import portal
-from twisted.cred import checkers
-from twisted.cred import credentials
-
-class IProtocolUser(Interface):
-    def getPrivileges():
-        """Return a list of privileges this user has."""
-
-    def logout():
-        """Cleanup per-login resources allocated to this avatar"""
-
-class AnonymousUser:
-    implements(IProtocolUser)
-    
-    def getPrivileges(self):
-        return [1, 2, 3]
-
-    def logout(self):
-        print "Cleaning up anonymous user resources"
-
-class RegularUser:
-    implements(IProtocolUser)
-    
-    def getPrivileges(self):
-        return [1, 2, 3, 5, 6]
-
-    def logout(self):
-        print "Cleaning up regular user resources"
-
-class Administrator:
-    implements(IProtocolUser)
-    
-    def getPrivileges(self):
-        return range(50)
-
-    def logout(self):
-        print "Cleaning up administrator resources"
-
-class Protocol(basic.LineReceiver):
-    user = None
-    portal = None
-    avatar = None
-    logout = None
-
-    def connectionMade(self):
-        self.sendLine("Login with USER <name> followed by PASS <password> or ANON")
-        self.sendLine("Check privileges with PRIVS")
-
-    def connectionLost(self, reason):
-        if self.logout:
-            self.logout()
-            self.avatar = None
-            self.logout = None
-    
-    def lineReceived(self, line):
-        f = getattr(self, 'cmd_' + line.upper().split()[0])
-        if f:
-            try:
-                f(*line.split()[1:])
-            except TypeError:
-                self.sendLine("Wrong number of arguments.")
-            except:
-                self.sendLine("Server error (probably your fault)")
-
-    def cmd_ANON(self):
-        if self.portal:
-            self.portal.login(credentials.Anonymous(), None, IProtocolUser
-                ).addCallbacks(self._cbLogin, self._ebLogin
-                )
-        else:
-            self.sendLine("DENIED")
-    
-    def cmd_USER(self, name):
-        self.user = name
-        self.sendLine("Alright.  Now PASS?")
-    
-    def cmd_PASS(self, password):
-        if not self.user:
-            self.sendLine("USER required before PASS")
-        else:
-            if self.portal:
-                self.portal.login(
-                    credentials.UsernamePassword(self.user, password),
-                    None,
-                    IProtocolUser
-                ).addCallbacks(self._cbLogin, self._ebLogin
-                )
-            else:
-                self.sendLine("DENIED")
-
-    def cmd_PRIVS(self):
-        self.sendLine("You have the following privileges: ")
-        self.sendLine(" ".join(map(str, self.avatar.getPrivileges())))
-
-    def _cbLogin(self, (interface, avatar, logout)):
-        assert interface is IProtocolUser
-        self.avatar = avatar
-        self.logout = logout
-        self.sendLine("Login successful.  Available commands: PRIVS")
-    
-    def _ebLogin(self, failure):
-        failure.trap(error.UnauthorizedLogin)
-        self.sendLine("Login denied!  Go away.")
-
-class ServerFactory(protocol.ServerFactory):
-    protocol = Protocol
-    
-    def __init__(self, portal):
-        self.portal = portal
-    
-    def buildProtocol(self, addr):
-        p = protocol.ServerFactory.buildProtocol(self, addr)
-        p.portal = self.portal
-        return p
-
-class Realm:
-    implements(portal.IRealm)
-
-    def requestAvatar(self, avatarId, mind, *interfaces):
-        if IProtocolUser in interfaces:
-            if avatarId == checkers.ANONYMOUS:
-                av = AnonymousUser()
-            elif avatarId.isupper():
-                # Capitalized usernames are administrators.
-                av = Administrator()
-            else:
-                av = RegularUser()
-            return IProtocolUser, av, av.logout
-        raise NotImplementedError("Only IProtocolUser interface is supported by this realm")
-
-def main():
-    r = Realm()
-    p = portal.Portal(r)
-    c = checkers.InMemoryUsernamePasswordDatabaseDontUse()
-    c.addUser("auser", "thepass")
-    c.addUser("SECONDUSER", "secret")
-    p.registerChecker(c)
-    p.registerChecker(checkers.AllowAnonymousAccess())
-    
-    f = ServerFactory(p)
-
-    log.startLogging(sys.stdout)
-
-    from twisted.internet import reactor
-    reactor.listenTCP(4738, f)
-    reactor.run()
-
-if __name__ == '__main__':
-    main()

+ 0 - 178
desktop/core/ext-py/Twisted/doc/core/examples/dbcred.py

@@ -1,178 +0,0 @@
-#!/usr/bin/python
-# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Simple example of a db checker: define a L{ICredentialsChecker} implementation
-that deals with a database backend to authenticate a user.
-"""
-
-from twisted.cred import error
-from twisted.cred.credentials import IUsernameHashedPassword, IUsernamePassword
-from twisted.cred.checkers import ICredentialsChecker
-from twisted.internet.defer import Deferred
-
-from zope.interface import implements
-
-
-class DBCredentialsChecker(object):
-    """
-    This class checks the credentials of incoming connections
-    against a user table in a database.
-    """
-    implements(ICredentialsChecker)
-
-    def __init__(self, runQuery,
-        query="SELECT username, password FROM user WHERE username = %s",
-        customCheckFunc=None, caseSensitivePasswords=True):
-        """
-        @param runQuery: This will be called to get the info from the db.
-            Generally you'd want to create a
-            L{twisted.enterprice.adbapi.ConnectionPool} and pass it's runQuery
-            method here. Otherwise pass a function with the same prototype.
-        @type runQuery: C{callable}
-
-        @type query: query used to authenticate user.
-        @param query: C{str}
-
-        @param customCheckFunc: Use this if the passwords in the db are stored
-            as hashes. We'll just call this, so you can do the checking
-            yourself. It takes the following params:
-            (username, suppliedPass, dbPass) and must return a boolean.
-        @type customCheckFunc: C{callable}
-
-        @param caseSensitivePasswords: If true requires that every letter in
-            C{credentials.password} is exactly the same case as the it's
-            counterpart letter in the database.
-            This is only relevant if C{customCheckFunc} is not used.
-        @type caseSensitivePasswords: C{bool}
-        """
-        self.runQuery = runQuery
-        self.caseSensitivePasswords = caseSensitivePasswords
-        self.customCheckFunc = customCheckFunc
-        # We can't support hashed password credentials if we only have a hash
-        # in the DB
-        if customCheckFunc:
-            self.credentialInterfaces = (IUsernamePassword,)
-        else:
-            self.credentialInterfaces = (
-                IUsernamePassword, IUsernameHashedPassword,)
-
-        self.sql = query
-
-    def requestAvatarId(self, credentials):
-        """
-        Authenticates the kiosk against the database.
-        """
-        # Check that the credentials instance implements at least one of our
-        # interfaces
-        for interface in self.credentialInterfaces:
-            if interface.providedBy(credentials):
-                break
-        else:
-            raise error.UnhandledCredentials()
-        # Ask the database for the username and password
-        dbDeferred = self.runQuery(self.sql, (credentials.username,))
-        # Setup our deferred result
-        deferred = Deferred()
-        dbDeferred.addCallbacks(self._cbAuthenticate, self._ebAuthenticate,
-                callbackArgs=(credentials, deferred),
-                errbackArgs=(credentials, deferred))
-        return deferred
-
-    def _cbAuthenticate(self, result, credentials, deferred):
-        """
-        Checks to see if authentication was good. Called once the info has
-        been retrieved from the DB.
-        """
-        if len(result) == 0:
-            # Username not found in db
-            deferred.errback(error.UnauthorizedLogin('Username unknown'))
-        else:
-            username, password = result[0]
-            if self.customCheckFunc:
-                # Let the owner do the checking
-                if self.customCheckFunc(
-                        username, credentials.password, password):
-                    deferred.callback(credentials.username)
-                else:
-                    deferred.errback(
-                        error.UnauthorizedLogin('Password mismatch'))
-            else:
-                # It's up to us or the credentials object to do the checking
-                # now
-                if IUsernameHashedPassword.providedBy(credentials):
-                    # Let the hashed password checker do the checking
-                    if credentials.checkPassword(password):
-                        deferred.callback(credentials.username)
-                    else:
-                        deferred.errback(
-                            error.UnauthorizedLogin('Password mismatch'))
-                elif IUsernamePassword.providedBy(credentials):
-                    # Compare the passwords, deciging whether or not to use
-                    # case sensitivity
-                    if self.caseSensitivePasswords:
-                        passOk = (
-                            password.lower() == credentials.password.lower())
-                    else:
-                        passOk = password == credentials.password
-                    # See if they match
-                    if passOk:
-                        deferred.callback(credentials.username)
-                    else:
-                        deferred.errback(
-                            error.UnauthorizedLogin('Password mismatch'))
-                else:
-                    # OK, we don't know how to check this
-                    deferred.errback(error.UnhandledCredentials())
-
-    def _ebAuthenticate(self, message, credentials, deferred):
-        """
-        The database lookup failed for some reason.
-        """
-        deferred.errback(error.LoginFailed(message))
-
-
-def main():
-    """
-    Run a simple echo pb server to test the checker. It defines a custom query
-    for dealing with sqlite special quoting, but otherwise it's a
-    straightforward use of the object.
-
-    You can test it running C{pbechoclient.py}.
-    """
-    import sys
-    from twisted.python import log
-    log.startLogging(sys.stdout)
-    import os
-    if os.path.isfile('testcred'):
-        os.remove('testcred')
-    from twisted.enterprise import adbapi
-    pool = adbapi.ConnectionPool('pysqlite2.dbapi2', 'testcred')
-    # Create the table that will be used
-    query1 = """CREATE TABLE user (
-            username string,
-            password string
-        )"""
-    # Insert a test user
-    query2 = """INSERT INTO user VALUES ('guest', 'guest')"""
-    def cb(res):
-        pool.runQuery(query2)
-    pool.runQuery(query1).addCallback(cb)
-
-    checker = DBCredentialsChecker(pool.runQuery,
-        query="SELECT username, password FROM user WHERE username = ?")
-    from twisted.cred.portal import Portal
-
-    import pbecho
-    from twisted.spread import pb
-    portal = Portal(pbecho.SimpleRealm())
-    portal.registerChecker(checker)
-    reactor.listenTCP(pb.portno, pb.PBServerFactory(portal))
-
-
-if __name__ == "__main__":
-    from twisted.internet import reactor
-    reactor.callWhenRunning(main)
-    reactor.run()
-

+ 0 - 40
desktop/core/ext-py/Twisted/doc/core/examples/echoclient.py

@@ -1,40 +0,0 @@
-#!/usr/bin/python
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-from twisted.internet.protocol import ClientFactory
-from twisted.protocols.basic import LineReceiver
-from twisted.internet import reactor
-import sys
-
-class EchoClient(LineReceiver):
-    end="Bye-bye!"
-    def connectionMade(self):
-        self.sendLine("Hello, world!")
-        self.sendLine("What a fine day it is.")
-        self.sendLine(self.end)
-
-    def lineReceived(self, line):
-        print "receive:", line
-        if line==self.end:
-            self.transport.loseConnection()
-
-class EchoClientFactory(ClientFactory):
-    protocol = EchoClient
-
-    def clientConnectionFailed(self, connector, reason):
-        print 'connection failed:', reason.getErrorMessage()
-        reactor.stop()
-
-    def clientConnectionLost(self, connector, reason):
-        print 'connection lost:', reason.getErrorMessage()
-        reactor.stop()
-
-def main():
-    factory = EchoClientFactory()
-    reactor.connectTCP('localhost', 8000, factory)
-    reactor.run()
-
-if __name__ == '__main__':
-    main()

+ 0 - 46
desktop/core/ext-py/Twisted/doc/core/examples/echoclient_ssl.py

@@ -1,46 +0,0 @@
-#!/usr/bin/python
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-from OpenSSL import SSL
-import sys
-
-from twisted.internet.protocol import ClientFactory
-from twisted.protocols.basic import LineReceiver
-from twisted.internet import ssl, reactor
-
-
-class EchoClient(LineReceiver):
-    end="Bye-bye!"
-    def connectionMade(self):
-        self.sendLine("Hello, world!")
-        self.sendLine("What a fine day it is.")
-        self.sendLine(self.end)
-
-    def connectionLost(self, reason):
-        print 'connection lost (protocol)'
-
-    def lineReceived(self, line):
-        print "receive:", line
-        if line==self.end:
-            self.transport.loseConnection()
-
-class EchoClientFactory(ClientFactory):
-    protocol = EchoClient
-
-    def clientConnectionFailed(self, connector, reason):
-        print 'connection failed:', reason.getErrorMessage()
-        reactor.stop()
-
-    def clientConnectionLost(self, connector, reason):
-        print 'connection lost:', reason.getErrorMessage()
-        reactor.stop()
-
-def main():
-    factory = EchoClientFactory()
-    reactor.connectSSL('localhost', 8000, factory, ssl.ClientContextFactory())
-    reactor.run()
-
-if __name__ == '__main__':
-    main()

+ 0 - 37
desktop/core/ext-py/Twisted/doc/core/examples/echoclient_udp.py

@@ -1,37 +0,0 @@
-#!/usr/bin/python
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-from twisted.internet.protocol import DatagramProtocol
-from twisted.internet import reactor
-
-class EchoClientDatagramProtocol(DatagramProtocol):
-    strings = [
-        "Hello, world!",
-        "What a fine day it is.",
-        "Bye-bye!"
-    ]
-    
-    def startProtocol(self):
-        self.transport.connect('127.0.0.1', 8000)
-        self.sendDatagram()
-    
-    def sendDatagram(self):
-        if len(self.strings):
-            datagram = self.strings.pop(0)
-            self.transport.write(datagram)
-        else:
-            reactor.stop()
-
-    def datagramReceived(self, datagram, host):
-        print 'Datagram received: ', repr(datagram)
-        self.sendDatagram()
-
-def main():
-    protocol = EchoClientDatagramProtocol()
-    t = reactor.listenUDP(0, protocol)
-    reactor.run()
-
-if __name__ == '__main__':
-    main()

+ 0 - 26
desktop/core/ext-py/Twisted/doc/core/examples/echoserv.py

@@ -1,26 +0,0 @@
-#!/usr/bin/python
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-from twisted.internet.protocol import Protocol, Factory
-from twisted.internet import reactor
-
-### Protocol Implementation
-
-# This is just about the simplest possible protocol
-class Echo(Protocol):
-    def dataReceived(self, data):
-        """As soon as any data is received, write it back."""
-        self.transport.write(data)
-
-
-def main():
-    f = Factory()
-    f.protocol = Echo
-    reactor.listenTCP(8000, f)
-    reactor.run()
-
-if __name__ == '__main__':
-    main()

+ 0 - 30
desktop/core/ext-py/Twisted/doc/core/examples/echoserv_ssl.py

@@ -1,30 +0,0 @@
-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-from OpenSSL import SSL
-
-class ServerContextFactory:
-    
-    def getContext(self):
-        """Create an SSL context.
-        
-        This is a sample implementation that loads a certificate from a file 
-        called 'server.pem'."""
-        ctx = SSL.Context(SSL.SSLv23_METHOD)
-        ctx.use_certificate_file('server.pem')
-        ctx.use_privatekey_file('server.pem')
-        return ctx
-
-
-if __name__ == '__main__':
-    import echoserv, sys
-    from twisted.internet.protocol import Factory
-    from twisted.internet import ssl, reactor
-    from twisted.python import log
-    log.startLogging(sys.stdout)
-    factory = Factory()
-    factory.protocol = echoserv.Echo
-    reactor.listenSSL(8000, factory, ServerContextFactory())
-    reactor.run()

+ 0 - 20
desktop/core/ext-py/Twisted/doc/core/examples/echoserv_udp.py

@@ -1,20 +0,0 @@
-#!/usr/bin/python
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-
-from twisted.internet.protocol import DatagramProtocol
-from twisted.internet import reactor
-
-# Here's a UDP version of the simplest possible protocol
-class EchoUDP(DatagramProtocol):
-    def datagramReceived(self, datagram, address):
-        self.transport.write(datagram, address)
-
-def main():
-    reactor.listenUDP(8000, EchoUDP())
-    reactor.run()
-
-if __name__ == '__main__':
-    main()

+ 0 - 17
desktop/core/ext-py/Twisted/doc/core/examples/filewatch.py

@@ -1,17 +0,0 @@
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-#
-from twisted.application import internet
-
-def watch(fp):
-    fp.seek(fp.tell())
-    for line in fp.readlines():
-        sys.stdout.write(line) 
-
-import sys
-from twisted.internet import reactor
-s = internet.TimerService(0.1, watch, file(sys.argv[1]))
-s.startService()
-reactor.run()
-s.stopService()

+ 0 - 113
desktop/core/ext-py/Twisted/doc/core/examples/ftpclient.py

@@ -1,113 +0,0 @@
-
-# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-
-"""
-An example of using the FTP client
-"""
-
-# Twisted imports
-from twisted.protocols.ftp import FTPClient, FTPFileListProtocol
-from twisted.internet.protocol import Protocol, ClientCreator
-from twisted.python import usage
-from twisted.internet import reactor
-
-# Standard library imports
-import string
-import sys
-try:
-    from cStringIO import StringIO
-except ImportError:
-    from StringIO import StringIO
-
-
-class BufferingProtocol(Protocol):
-    """Simple utility class that holds all data written to it in a buffer."""
-    def __init__(self):
-        self.buffer = StringIO()
-
-    def dataReceived(self, data):
-        self.buffer.write(data)
-
-# Define some callbacks
-
-def success(response):
-    print 'Success!  Got response:'
-    print '---'
-    if response is None:
-        print None
-    else:
-        print string.join(response, '\n')
-    print '---'
-
-
-def fail(error):
-    print 'Failed.  Error was:'
-    print error
-
-def showFiles(result, fileListProtocol):
-    print 'Processed file listing:'
-    for file in fileListProtocol.files:
-        print '    %s: %d bytes, %s' \
-              % (file['filename'], file['size'], file['date'])
-    print 'Total: %d files' % (len(fileListProtocol.files))
-
-def showBuffer(result, bufferProtocol):
-    print 'Got data:'
-    print bufferProtocol.buffer.getvalue()
-
-
-class Options(usage.Options):
-    optParameters = [['host', 'h', 'localhost'],
-                     ['port', 'p', 21],
-                     ['username', 'u', 'anonymous'],
-                     ['password', None, 'twisted@'],
-                     ['passive', None, 0],
-                     ['debug', 'd', 1],
-                    ]
-
-def run():
-    # Get config
-    config = Options()
-    config.parseOptions()
-    config.opts['port'] = int(config.opts['port'])
-    config.opts['passive'] = int(config.opts['passive'])
-    config.opts['debug'] = int(config.opts['debug'])
-    
-    # Create the client
-    FTPClient.debug = config.opts['debug']
-    creator = ClientCreator(reactor, FTPClient, config.opts['username'],
-                            config.opts['password'], passive=config.opts['passive'])
-    creator.connectTCP(config.opts['host'], config.opts['port']).addCallback(connectionMade).addErrback(connectionFailed)
-    reactor.run()
-
-def connectionFailed(f):
-    print "Connection Failed:", f
-    reactor.stop()
-
-def connectionMade(ftpClient):
-    # Get the current working directory
-    ftpClient.pwd().addCallbacks(success, fail)
-
-    # Get a detailed listing of the current directory
-    fileList = FTPFileListProtocol()
-    d = ftpClient.list('.', fileList)
-    d.addCallbacks(showFiles, fail, callbackArgs=(fileList,))
-
-    # Change to the parent directory
-    ftpClient.cdup().addCallbacks(success, fail)
-    
-    # Create a buffer
-    proto = BufferingProtocol()
-
-    # Get short listing of current directory, and quit when done
-    d = ftpClient.nlst('.', proto)
-    d.addCallbacks(showBuffer, fail, callbackArgs=(proto,))
-    d.addCallback(lambda result: reactor.stop())
-
-
-# this only runs if the module was *not* imported
-if __name__ == '__main__':
-    run()
-

+ 0 - 55
desktop/core/ext-py/Twisted/doc/core/examples/ftpserver.py

@@ -1,55 +0,0 @@
-# Copyright (c) 2008 Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-An example FTP server with minimal user authentication.
-"""
-
-from twisted.protocols.ftp import FTPFactory, FTPRealm
-from twisted.cred.portal import Portal
-from twisted.cred.checkers import AllowAnonymousAccess, FilePasswordDB
-from twisted.internet import reactor
-
-#
-# First, set up a portal (twisted.cred.portal.Portal). This will be used
-# to authenticate user logins, including anonymous logins.
-#
-# Part of this will be to establish the "realm" of the server - the most
-# important task in this case is to establish where anonymous users will
-# have default access to. In a real world scenario this would typically
-# point to something like '/pub' but for this example it is pointed at the
-# current working directory.
-#
-# The other important part of the portal setup is to point it to a list of
-# credential checkers. In this case, the first of these is used to grant
-# access to anonymous users and is relatively simple; the second is a very
-# primitive password checker.  This example uses a plain text password file
-# that has one username:password pair per line. This checker *does* provide
-# a hashing interface, and one would normally want to use it instead of
-# plain text storage for anything remotely resembling a 'live' network. In
-# this case, the file "pass.dat" is used, and stored in the same directory
-# as the server. BAD.
-#
-# Create a pass.dat file which looks like this:
-#
-# =====================
-#   jeff:bozo
-#   grimmtooth:bozo2
-# =====================
-#
-p = Portal(FTPRealm('./'),
-           [AllowAnonymousAccess(), FilePasswordDB("pass.dat")])
-
-#
-# Once the portal is set up, start up the FTPFactory and pass the portal to
-# it on startup. FTPFactory will start up a twisted.protocols.ftp.FTP()
-# handler for each incoming OPEN request. Business as usual in Twisted land.
-#
-f = FTPFactory(p)
-
-#
-# You know this part. Point the reactor to port 21 coupled with the above factory,
-# and start the event loop.
-#
-reactor.listenTCP(21, f)
-reactor.run()

+ 0 - 69
desktop/core/ext-py/Twisted/doc/core/examples/gpsfix.py

@@ -1,69 +0,0 @@
-#!/usr/bin/python
-"""
-GPSTest is a simple example using the SerialPort transport and the NMEA 0183 and Rockwell Zodiac GPS protocols to display fix data as it is received from the device.
-"""
-from twisted.python import log, usage
-import sys
-
-if sys.platform == 'win32':
-    from twisted.internet import win32eventreactor
-    win32eventreactor.install()
-
-
-class GPSFixLogger:
-    def handle_fix(self, *args):
-      """handle_fix gets called whenever either rockwell.Zodiac or nmea.NMEAReceiver receives
-      and decodes fix data.  Generally, GPS receivers will report a fix at 1hz.  
-      Implementing only this method is sufficient for most purposes unless tracking of ground speed,
-      course, utc date, or detailed satellite information is necessary.
-
-      For example, plotting a map from MapQuest or a similar service only requires longitude and latitude.
-      """
-      log.msg('fix:\n' + 
-      '\n'.join(map(lambda n: '  %s = %s' % tuple(n), zip(('utc', 'lon', 'lat', 'fix', 'sat', 'hdp', 'alt', 'geo', 'dgp'), map(repr, args)))))
-
-class GPSOptions(usage.Options):
-    optFlags = [
-        ['zodiac', 'z', 'Use Rockwell Zodiac (DeLorme Earthmate) [default: NMEA 0183]'],
-    ]
-    optParameters = [
-        ['outfile', 'o', None, 'Logfile [default: sys.stdout]'],
-        ['baudrate', 'b', None, 'Serial baudrate [default: 4800 for NMEA, 9600 for Zodiac]'],
-        ['port', 'p', '/dev/ttyS0', 'Serial Port device'],
-    ]
-
-
-if __name__ == '__main__':
-    from twisted.internet import reactor
-    from twisted.internet.serialport import SerialPort
-
-    o = GPSOptions()
-    try:
-        o.parseOptions()
-    except usage.UsageError, errortext:
-        print '%s: %s' % (sys.argv[0], errortext)
-        print '%s: Try --help for usage details.' % (sys.argv[0])
-        raise SystemExit, 1
-
-    logFile = o.opts['outfile']
-    if logFile is None:
-        logFile = sys.stdout
-    log.startLogging(logFile)
-
-    if o.opts['zodiac']:
-        from twisted.protocols.gps.rockwell import Zodiac as GPSProtocolBase
-        baudrate = 9600
-    else:
-        from twisted.protocols.gps.nmea import NMEAReceiver as GPSProtocolBase
-        baudrate = 4800
-    class GPSTest(GPSProtocolBase, GPSFixLogger):
-        pass
-    
-    if o.opts['baudrate']:
-        baudrate = int(o.opts['baudrate'])
-
-
-    port = o.opts['port']
-    log.msg('Attempting to open %s at %dbps as a %s device' % (port, baudrate, GPSProtocolBase.__name__))
-    s = SerialPort(GPSTest(), o.opts['port'], reactor, baudrate=baudrate)
-    reactor.run()

Неке датотеке нису приказане због велике количине промена