summaryrefslogtreecommitdiffstats
path: root/third_party/pyftpdlib
diff options
context:
space:
mode:
authorerikkay@google.com <erikkay@google.com@0039d316-1c4b-4281-b951-d872f2087c98>2008-12-23 19:39:42 +0000
committererikkay@google.com <erikkay@google.com@0039d316-1c4b-4281-b951-d872f2087c98>2008-12-23 19:39:42 +0000
commit25963381f55ce81bf44e3d511ec44e634942204f (patch)
tree5182d1adaa98faf2c5d35c2c89687cff03a23504 /third_party/pyftpdlib
parentbfe835e3e3d5aea1415886dec94bdc760db6cded (diff)
downloadchromium_src-25963381f55ce81bf44e3d511ec44e634942204f.zip
chromium_src-25963381f55ce81bf44e3d511ec44e634942204f.tar.gz
chromium_src-25963381f55ce81bf44e3d511ec44e634942204f.tar.bz2
Add pyftpdlib for future ftp unit tests.
From http://codereview.chromium.org/16429/ by contributor ibrar.ahmed@gmail.com TBR=pamg Review URL: http://codereview.chromium.org/16454 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@7427 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'third_party/pyftpdlib')
-rw-r--r--third_party/pyftpdlib/CREDITS97
-rw-r--r--third_party/pyftpdlib/HISTORY216
-rw-r--r--third_party/pyftpdlib/INSTALL4
-rw-r--r--third_party/pyftpdlib/LICENSE22
-rw-r--r--third_party/pyftpdlib/README10
-rw-r--r--third_party/pyftpdlib/README.google12
-rw-r--r--third_party/pyftpdlib/build/lib/pyftpdlib/ftpserver.py3127
-rw-r--r--third_party/pyftpdlib/demo/basic_ftpd.py44
-rw-r--r--third_party/pyftpdlib/demo/md5_ftpd.py29
-rw-r--r--third_party/pyftpdlib/demo/throttled_ftpd.py89
-rw-r--r--third_party/pyftpdlib/demo/unix_ftpd.py88
-rw-r--r--third_party/pyftpdlib/demo/winnt_ftpd.py115
-rw-r--r--third_party/pyftpdlib/doc/adoptions.lnk.html12
-rw-r--r--third_party/pyftpdlib/doc/faq.html98
-rw-r--r--third_party/pyftpdlib/doc/index.html158
-rw-r--r--third_party/pyftpdlib/doc/install.html34
-rw-r--r--third_party/pyftpdlib/doc/release-notes.html47
-rw-r--r--third_party/pyftpdlib/doc/rfcs-compliance.html720
-rw-r--r--third_party/pyftpdlib/doc/roadmap.lnk.html12
-rw-r--r--third_party/pyftpdlib/doc/tutorial.html329
-rw-r--r--third_party/pyftpdlib/pyftpdlib/ftpserver.py3127
-rw-r--r--third_party/pyftpdlib/setup.py40
-rw-r--r--third_party/pyftpdlib/test/test_ftpd.py1623
23 files changed, 10053 insertions, 0 deletions
diff --git a/third_party/pyftpdlib/CREDITS b/third_party/pyftpdlib/CREDITS
new file mode 100644
index 0000000..9bc0c94
--- /dev/null
+++ b/third_party/pyftpdlib/CREDITS
@@ -0,0 +1,97 @@
+
+Intro
+=====
+
+I would like to recognize some of the people who have been
+instrumental in the development of pyftpdlib.
+I'm sure I am forgetting some people (feel free to email
+me), but here is a short list.
+It's modeled after the Linux CREDITS file where the fields
+are:
+name (N), e-mail (E), web-address (W), country (C) description (D).
+Really thanks to all of you.
+
+
+Maintainers
+===========
+
+N: Giampaolo Rodola'
+C: Italy
+E: g.rodola@gmail.com
+D: Original pyftpdlib author and maintainer
+
+N: Jay Loden
+C: NJ, USA
+E: jloden@gmail.com
+W: http://www.jayloden.com
+D: OS X and Linux platform development/testing
+
+N: Li-Wen Hsu
+C: Taiwan
+E: lwhsu@lwhsu.org
+W: http://lwhsu.org
+D: FreeBSD port maintainer
+
+
+Contributors
+============
+
+N: Anatoly Techtonik
+C: Belarus
+E: techtonik@gmail.com
+D: Inclusion of pyftpdlib in Far Manager, a file and archive manager for Windows
+ operating systems (http://enforum.farmanager.com/viewtopic.php?t=640).
+
+N: Arkadiusz Wahlig
+C: Germany
+W: http://arkadiusz-wahlig.blogspot.com
+D: Inclusion of pyftpdlib in gpftpd project, an FTP daemon for managing files
+ hosted on Google Pages
+ (http://arkadiusz-wahlig.blogspot.com/2008/04/hosting-files-on-google.html).
+
+N: Walco van Loon
+C: Netherlands
+E: walco@n--tree.net
+D: Inclusion of pyftpdlib in aksy project
+ (http://walco.n--tree.net/projects/aksy).
+
+N: Shinya Okano
+C: Japan
+E: xxshss@yahoo.co.jp
+D: Japanese translation of pyftpdlib announces. Inclusion of pyftpdlib in
+ unbox-ftpd project (http://code.google.com/p/unboxftpd).
+
+N: Yan Raber
+C: Italy
+E: yanraber@gmail.com
+D: Fix of Issue #9 (Path traversal vulnerability)
+
+N: Alex Martelli
+C: Italy
+E: aleax@gmail.com
+D: Various useful suggestions
+
+N: Knic
+C: Redmond, USA
+E: oneeyedelf1@googlemail.com
+D: Bug report #24 (some troubles on PythonCE), tester for various platforms
+ including Windows Mobile, Windows Server 2008 and various 64 bit OSes.
+
+N: Greg Copeland
+E: gcopeland@efjohnson.com
+D: Bug report #16 (Extending compatibility with older python versions)
+
+N: Roger Erens
+E: rogererens@gmail.com
+D: Bug report affecting unix_ftpd.py's authorizer
+
+N: Coronado Ivan
+D: Bug report #70 (Wrong NOOP response code)
+
+N: Rauli Ruohonen
+D: Bug report #71 (Socket handles are leaked when a data transfer is in progress
+ and user QUITs)
+
+N: Equand
+E: equand@gmail.com
+D: Bug report #77 (incorrect OOB data management on FreeBSD).
diff --git a/third_party/pyftpdlib/HISTORY b/third_party/pyftpdlib/HISTORY
new file mode 100644
index 0000000..9d315b0
--- /dev/null
+++ b/third_party/pyftpdlib/HISTORY
@@ -0,0 +1,216 @@
+Issue tracker at http://code.google.com/p/pyftpdlib/issues/list
+
+
+History
+=======
+
+Version: 0.5.0 - Date: 2008-09-20
+---------------------------------
+
+Major enhancements:
+
+ * Issue #72: pyftpdlib now provides configurable idle timeouts to disconnect
+ client after a long time of inactivity.
+
+ * Issue #73: impose a delay before replying for invalid credentials to minimize
+ the risk of brute force password guessing.
+
+ * Issue #74: it is now possible to define permission exceptions for certain
+ directories (e.g. creating a user which does not have write permission except
+ for one sub-directory in FTP root).
+
+ * Improved bandwidth throttling capabilities of demo/throttled_ftpd.py script
+ by having used the new CallLater class which drastically reduces the number
+ of calls to time.time().
+
+Bugfixes:
+
+ * Issue #62: some unit tests were failing on dual core machines.
+
+ * Issue #71: socket handles are leaked when a data transfer is in progress and
+ user QUITs.
+
+ * Issue #75: orphaned file was left behind in case STOU failed for insufficient
+ user permissions.
+
+ * Issue #77: incorrect OOB data management on FreeBSD.
+
+
+Version: 0.4.0 - Date: 2008-05-16
+---------------------------------
+
+Major enhancements:
+
+ * Issue #65: assume the id of real users when using system dependent
+ authorizers.
+ * Issue #67: added IPv6 support.
+
+Bugfixes:
+
+ * Issue #64: issue when authenticating as anonymous user using user-defined
+ authorizers.
+ * Issue #66: WinNTAuthorizer does not determine the real user home directory.
+ * Issue #69: DummyAuthorizer incorrectly uses class attribute instead of
+ instance attribute for user_table dictionary.
+ * Issue #70: wrong NOOP response code.
+
+API changes since 0.3.0:
+
+ * DummyAuthorizer class changes:
+ * impersonate_user() and terminate_impersonation() methods have been
+ added.
+
+
+Version: 0.3.0 - Date: 2008-01-17
+---------------------------------
+
+Major enhancements:
+
+ * Issue #48: real permissions, owner, and group for files on UNIX platforms are
+ now provided when processing LIST.
+ * Issue #51: added the new demo/throttled_ftpd.py script.
+ * Issue #59: iterators are now used for calculating requests requiring long
+ time to complete (LIST and MLSD commands).
+ * Issue #61: extended the set of assignable user permissions.
+
+RFC-related enhancements:
+
+ * Issue #42: implemented FEAT command defined in RFC-2389.
+ * Issue #52: implemented MLST and MLSD commands defined in RFC-3659.
+ * Issue #58: implemented OPTS command define in RFC-2389.
+
+Bugfixes:
+
+ * Issue #41: error occurred on quit if user was not yet authenticated.
+ * Issue #43: hidden the server identifier when returning STAT response.
+ * Issue #44: a wrong response code was given on PORT if the data connection
+ attempt failed.
+ * Issue #45: a wrong response code was given on HELP if argument was incorrect.
+ * Issue #46: a wrong response code was given on PASV if remote peer had a
+ foreign internet address.
+ * Issue #47: can't use FTPServer.max_cons option with Python 2.3.
+ * Issue #48: problem when LISTing "broken" symbolic links.
+ * Issue #49: data channel did not respect the outgoing data buffer.
+ * Issue #53: received strings having trailing white spaces was erroneously
+ stripped.
+ * Issue #54: LIST/NLST/STAT outputs are now sorted by file name.
+ * Issue #55: path traversal vulnerability in case of symlinks.
+ * Issue #56: can't rename broken symbolic links.
+ * Issue #57: wrong LIST/NLST behavior when processing symbolic links.
+ * Issue #60: error occurred in case of bad formatted PORT command requests.
+
+API changes since 0.2.0:
+
+ * New IteratorProducer and BufferedIteratorProducer classes have been added.
+ * DummyAuthorizer class changes:
+ * The permissions management has been changed and the set of available
+ permissions have been extended (see Issue #61). add_user() method
+ now accepts "eladfm" permissions beyond the old "r" and "w".
+ * r_perm() and w_perm() methods have been removed.
+ * New has_perm() and get_perms() methods have been added.
+* AbstractedFS class changes:
+ * normalize() method has been renamed in ftpnorm().
+ * translate() method has been renamed in ftp2fs().
+ * New methods: fs2ftp(), stat(), lstat(), islink(), realpath(), lexists(),
+ validpath().
+ * get_list_dir(), get_stat_dir() and format_list() methods now return an
+ iterator object instead of a string.
+ * format_list() method has a new "ignore_err" keyword argument.
+* global debug() function has been removed.
+
+
+Version: 0.2.0 - Date: 2007-09-17
+----------------------------------
+
+Major enhancements:
+
+ * Issue #5: provided a way to configure / limit the number of maximum
+ acceptable connections.
+ * Issue #5: provided a way to configure / limit the maximum number of clients
+ which may be connected from the same IP address.
+ * Issue #36: added support for FXP site-to-site transfer to allow transfers
+ between FTP servers.
+ * Issue #39: added NAT/Firewall support with PASV (passive) mode connections
+ for FTP servers behind NAT.
+ * Issue #40: provided new FTPHandler.passive_ports attribute to control what
+ ports to use for passive data-transfers.
+
+RFC-related enhancements:
+
+ * Issue #6: accept and process TYPE AN and TYPE L8 commands.
+ * Issue #7: a new USER command can now be entered at any point to begin the
+ login sequence again.
+ * Issue #8: be compliant with STOU output format defined in RFC 1123.
+ * Issue #10: HELP command arguments are now accepted.
+ * Issue #12: 554 error response is now returned on RETR/STOR if REST fails.
+ * Issue #15: STAT used with an argument return directory LISTing over the
+ command channel.
+
+Security enhancements:
+
+ * Issue #3: stop buffering when extremely long lines are received.
+ * Issue #11: reject data connection when a privileged port is specified on
+ PORT command.
+ * Issue #25: limit the number of attempts to find a unique filename for
+ STOU command.
+
+Usability enhancements:
+
+ * Provided an overridable attribute to easily set number of maximum login
+ attempts before disconnecting.
+ * Docstrings are now provided for almost every method and function.
+ * Issue #30: command help strings quality improved by adding command
+ syntaxes.
+ * Issue #31: a compact list of recognized commands is now provided on HELP.
+ * Issue #32: we now provide a detailed error message on connection and file
+ system errors.
+ * Issue #38: anonymous user write access can now be optionally granted.
+
+Test suite enhancements:
+
+ * File creation/removal moved into setUp and tearDown methods to avoid leaving
+ behind orphaned temporary files in the event of a test suite failure.
+ * Issue #7: added tests for a new USER provided while already
+ authenticated.
+ * Issue #7: added tests for REIN while a transfer is in progress.
+ * Issue #28: added tests for ABOR command.
+
+Bugfixes:
+
+ * Issue #4: socket's "reuse_address" feature was used after the socket's
+ binding.
+ * Issue #9: corrected path traversal vulnerability affecting file-system path
+ translations.
+ * Issue #14: a wrong response code was returned on CDUP.
+ * Issue #17: reject SIZE if pathname is a directory.
+ * Issue #18: a wrong ABOR response code type was returned.
+ * Issue #19: watch for STOU preceded by REST which makes no sense.
+ * Issue #20: "attempted login" counter wasn't incremented on wrong username.
+ * Issue #21: STAT wasn't permitted if user wasn't authenticated yet.
+ * Issue #22: corrected memory leaks occurring on KeyboardInterrupt/SIGTERM.
+ * Issue #23: PASS wasn't rejected when user was already authenticated.
+ * Issue #24: can't use os.strerror() on pythonCE.
+ * Issue #24: problem occurred on Windows when using '\\' as user's home
+ directory.
+ * Issue #26: used select() by default instead of poll() because of an asyncore
+ module's defect.
+ * Issue #33: some FTPHandler class attributes wasn't resetted on REIN.
+ * Issue #35: watch for APPE preceded by REST which makes no sense.
+
+
+Version: 0.1.1 - Date: 2007-03-27
+----------------------------------
+
+ * Port selection on PASV command has been randomized to prevent a remote user
+ to know how many data connections are in progress on the server.
+ * Fixed bug in demo/unix_ftpd.py script (reported by Roger Erens).
+ * Little modification to add_anonymous method of dummy_authorizer class.
+ * ftp_server.serve_forever automatically re-use address if current system is
+ unix.
+ * License changed into a MIT style one.
+
+
+Version: 0.1.0 - Date: 2007-02-26
+----------------------------------
+
+ * First proof of concept beta release.
diff --git a/third_party/pyftpdlib/INSTALL b/third_party/pyftpdlib/INSTALL
new file mode 100644
index 0000000..63b71f97
--- /dev/null
+++ b/third_party/pyftpdlib/INSTALL
@@ -0,0 +1,4 @@
+Install
+=======
+
+See doc/install.html \ No newline at end of file
diff --git a/third_party/pyftpdlib/LICENSE b/third_party/pyftpdlib/LICENSE
new file mode 100644
index 0000000..b2b65fa
--- /dev/null
+++ b/third_party/pyftpdlib/LICENSE
@@ -0,0 +1,22 @@
+======================================================================
+Copyright (C) 2007 Giampaolo Rodola' <g.rodola@gmail.com>
+
+ 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, and that the name of
+Giampaolo Rodola' not be used in advertising or publicity pertaining to
+distribution of the software without specific, written prior
+permission.
+
+Giampaolo Rodola' DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
+NO EVENT Giampaolo Rodola' BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+====================================================================== \ No newline at end of file
diff --git a/third_party/pyftpdlib/README b/third_party/pyftpdlib/README
new file mode 100644
index 0000000..d45738c
--- /dev/null
+++ b/third_party/pyftpdlib/README
@@ -0,0 +1,10 @@
+
+About
+=====
+
+Python FTP server library provides an high-level portable interface to easily
+write asynchronous FTP servers with Python. Based on asyncore framework
+pyftpdlib is currently the most complete RFC-959 FTP server implementation
+available for Python programming language.
+
+Learn more by visiting: http://code.google.com/p/pyftpdlib/ \ No newline at end of file
diff --git a/third_party/pyftpdlib/README.google b/third_party/pyftpdlib/README.google
new file mode 100644
index 0000000..a36b118
--- /dev/null
+++ b/third_party/pyftpdlib/README.google
@@ -0,0 +1,12 @@
+This library was downloaded from http://code.google.com/p/pyftpdlib/
+
+For licensing information please LICENSE file
+
+Python FTP server library provides an high-level portable interface to easily
+write asynchronous FTP servers with Python. Based on asyncore framework
+pyftpdlib is currently the most complete RFC-959 FTP server implementation
+available for Python programming language.
+
+Version: 0.5.0
+
+Learn more by visiting: http://code.google.com/p/pyftpdlib/wiki/FAQ \ No newline at end of file
diff --git a/third_party/pyftpdlib/build/lib/pyftpdlib/ftpserver.py b/third_party/pyftpdlib/build/lib/pyftpdlib/ftpserver.py
new file mode 100644
index 0000000..d273f84
--- /dev/null
+++ b/third_party/pyftpdlib/build/lib/pyftpdlib/ftpserver.py
@@ -0,0 +1,3127 @@
+#!/usr/bin/env python
+# ftpserver.py
+#
+# pyftpdlib is released under the MIT license, reproduced below:
+# ======================================================================
+# Copyright (C) 2007 Giampaolo Rodola' <g.rodola@gmail.com>
+#
+# 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, and that the name of
+# Giampaolo Rodola' not be used in advertising or publicity pertaining to
+# distribution of the software without specific, written prior
+# permission.
+#
+# Giampaolo Rodola' DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
+# NO EVENT Giampaolo Rodola' BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+# ======================================================================
+
+
+"""pyftpdlib: RFC-959 asynchronous FTP server.
+
+pyftpdlib implements a fully functioning asynchronous FTP server as
+defined in RFC-959. A hierarchy of classes outlined below implement
+the backend functionality for the FTPd:
+
+ [FTPServer] - the base class for the backend.
+
+ [FTPHandler] - a class representing the server-protocol-interpreter
+ (server-PI, see RFC-959). Each time a new connection occurs
+ FTPServer will create a new FTPHandler instance to handle the
+ current PI session.
+
+ [ActiveDTP], [PassiveDTP] - base classes for active/passive-DTP
+ backends.
+
+ [DTPHandler] - this class handles processing of data transfer
+ operations (server-DTP, see RFC-959).
+
+ [DummyAuthorizer] - an "authorizer" is a class handling FTPd
+ authentications and permissions. It is used inside FTPHandler class
+ to verify user passwords, to get user's home directory and to get
+ permissions when a filesystem read/write occurs. "DummyAuthorizer"
+ is the base authorizer class providing a platform independent
+ interface for managing virtual users.
+
+ [AbstractedFS] - class used to interact with the file system,
+ providing a high level, cross-platform interface compatible
+ with both Windows and UNIX style filesystems.
+
+ [CallLater] - calls a function at a later time whithin the polling
+ loop asynchronously.
+
+ [AuthorizerError] - base class for authorizers exceptions.
+
+
+pyftpdlib also provides 3 different logging streams through 3 functions
+which can be overridden to allow for custom logging.
+
+ [log] - the main logger that logs the most important messages for
+ the end user regarding the FTPd.
+
+ [logline] - this function is used to log commands and responses
+ passing through the control FTP channel.
+
+ [logerror] - log traceback outputs occurring in case of errors.
+
+
+Usage example:
+
+>>> from pyftpdlib import ftpserver
+>>> authorizer = ftpserver.DummyAuthorizer()
+>>> authorizer.add_user('user', 'password', '/home/user', perm='elradfmw')
+>>> authorizer.add_anonymous('/home/nobody')
+>>> ftp_handler = ftpserver.FTPHandler
+>>> ftp_handler.authorizer = authorizer
+>>> address = ("127.0.0.1", 21)
+>>> ftpd = ftpserver.FTPServer(address, ftp_handler)
+>>> ftpd.serve_forever()
+Serving FTP on 127.0.0.1:21
+[]127.0.0.1:2503 connected.
+127.0.0.1:2503 ==> 220 Ready.
+127.0.0.1:2503 <== USER anonymous
+127.0.0.1:2503 ==> 331 Username ok, send password.
+127.0.0.1:2503 <== PASS ******
+127.0.0.1:2503 ==> 230 Login successful.
+[anonymous]@127.0.0.1:2503 User anonymous logged in.
+127.0.0.1:2503 <== TYPE A
+127.0.0.1:2503 ==> 200 Type set to: ASCII.
+127.0.0.1:2503 <== PASV
+127.0.0.1:2503 ==> 227 Entering passive mode (127,0,0,1,9,201).
+127.0.0.1:2503 <== LIST
+127.0.0.1:2503 ==> 150 File status okay. About to open data connection.
+[anonymous]@127.0.0.1:2503 OK LIST "/". Transfer starting.
+127.0.0.1:2503 ==> 226 Transfer complete.
+[anonymous]@127.0.0.1:2503 Transfer complete. 706 bytes transmitted.
+127.0.0.1:2503 <== QUIT
+127.0.0.1:2503 ==> 221 Goodbye.
+[anonymous]@127.0.0.1:2503 Disconnected.
+"""
+
+
+import asyncore
+import asynchat
+import socket
+import os
+import sys
+import traceback
+import errno
+import time
+import glob
+import tempfile
+import warnings
+import random
+import stat
+import heapq
+from tarfile import filemode
+
+try:
+ import pwd
+ import grp
+except ImportError:
+ pwd = grp = None
+
+
+__all__ = ['proto_cmds', 'Error', 'log', 'logline', 'logerror', 'DummyAuthorizer',
+ 'AuthorizerError', 'FTPHandler', 'FTPServer', 'PassiveDTP',
+ 'ActiveDTP', 'DTPHandler', 'FileProducer', 'BufferedIteratorProducer',
+ 'AbstractedFS', 'CallLater']
+
+
+__pname__ = 'Python FTP server library (pyftpdlib)'
+__ver__ = '0.5.0'
+__date__ = '2008-09-20'
+__author__ = "Giampaolo Rodola' <g.rodola@gmail.com>"
+__web__ = 'http://code.google.com/p/pyftpdlib/'
+
+
+proto_cmds = {
+ # cmd : (perm, auth, arg, path, help)
+ 'ABOR': (None, True, False, False, 'Syntax: ABOR (abort transfer).'),
+ 'ALLO': (None, True, True, False, 'Syntax: ALLO <SP> bytes (obsolete; allocate storage).'),
+ 'APPE': ('a', True, True, True, 'Syntax: APPE <SP> file-name (append data to an existent file).'),
+ 'CDUP': ('e', True, False, True, 'Syntax: CDUP (go to parent directory).'),
+ 'CWD' : ('e', True, None, True, 'Syntax: CWD [<SP> dir-name] (change current working directory).'),
+ 'DELE': ('d', True, True, True, 'Syntax: DELE <SP> file-name (delete file).'),
+ 'EPRT': (None, True, True, False, 'Syntax: EPRT <SP> |proto|ip|port| (set server in extended active mode).'),
+ 'EPSV': (None, True, None, False, 'Syntax: EPSV [<SP> proto/"ALL"] (set server in extended passive mode).'),
+ 'FEAT': (None, False, False, False, 'Syntax: FEAT (list all new features supported).'),
+ 'HELP': (None, False, None, False, 'Syntax: HELP [<SP> cmd] (show help).'),
+ 'LIST': ('l', True, None, True, 'Syntax: LIST [<SP> path-name] (list files).'),
+ 'MDTM': (None, True, True, True, 'Syntax: MDTM [<SP> file-name] (get last modification time).'),
+ 'MLSD': ('l', True, None, True, 'Syntax: MLSD [<SP> dir-name] (list files in a machine-processable form)'),
+ 'MLST': (None, True, None, True, 'Syntax: MLST [<SP> path-name] (show a path in a machine-processable form)'),
+ 'MODE': (None, True, True, False, 'Syntax: MODE <SP> mode (obsolete; set data transfer mode).'),
+ 'MKD' : ('m', True, True, True, 'Syntax: MDK <SP> dir-name (create directory).'),
+ 'NLST': ('l', True, None, True, 'Syntax: NLST [<SP> path-name] (list files in a compact form).'),
+ 'NOOP': (None, False, False, False, 'Syntax: NOOP (just do nothing).'),
+ 'OPTS': (None, True, True, False, 'Syntax: OPTS <SP> ftp-command [<SP> option] (specify options for FTP commands)'),
+ 'PASS': (None, False, True, False, 'Syntax: PASS <SP> user-name (set user password).'),
+ 'PASV': (None, True, False, False, 'Syntax: PASV (set server in passive mode).'),
+ 'PORT': (None, True, True, False, 'Syntax: PORT <sp> h1,h2,h3,h4,p1,p2 (set server in active mode).'),
+ 'PWD' : (None, True, False, False, 'Syntax: PWD (get current working directory).'),
+ 'QUIT': (None, False, False, False, 'Syntax: QUIT (quit current session).'),
+ 'REIN': (None, True, False, False, 'Syntax: REIN (reinitialize / flush account).'),
+ 'REST': (None, True, True, False, 'Syntax: REST <SP> marker (restart file position).'),
+ 'RETR': ('r', True, True, True, 'Syntax: RETR <SP> file-name (retrieve a file).'),
+ 'RMD' : ('d', True, True, True, 'Syntax: RMD <SP> dir-name (remove directory).'),
+ 'RNFR': ('f', True, True, True, 'Syntax: RNFR <SP> file-name (file renaming (source name)).'),
+ 'RNTO': (None, True, True, True, 'Syntax: RNTO <SP> file-name (file renaming (destination name)).'),
+ 'SIZE': (None, True, True, True, 'Syntax: HELP <SP> file-name (get file size).'),
+ 'STAT': ('l', False, None, True, 'Syntax: STAT [<SP> path name] (status information [list files]).'),
+ 'STOR': ('w', True, True, True, 'Syntax: STOR <SP> file-name (store a file).'),
+ 'STOU': ('w', True, None, True, 'Syntax: STOU [<SP> file-name] (store a file with a unique name).'),
+ 'STRU': (None, True, True, False, 'Syntax: STRU <SP> type (obsolete; set file structure).'),
+ 'SYST': (None, False, False, False, 'Syntax: SYST (get operating system type).'),
+ 'TYPE': (None, True, True, False, 'Syntax: TYPE <SP> [A | I] (set transfer type).'),
+ 'USER': (None, False, True, False, 'Syntax: USER <SP> user-name (set username).'),
+ 'XCUP': ('e', True, False, True, 'Syntax: XCUP (obsolete; go to parent directory).'),
+ 'XCWD': ('e', True, None, True, 'Syntax: XCWD [<SP> dir-name] (obsolete; change current directory).'),
+ 'XMKD': ('m', True, True, True, 'Syntax: XMDK <SP> dir-name (obsolete; create directory).'),
+ 'XPWD': (None, True, False, False, 'Syntax: XPWD (obsolete; get current dir).'),
+ 'XRMD': ('d', True, True, True, 'Syntax: XRMD <SP> dir-name (obsolete; remove directory).'),
+ }
+
+class _CommandProperty:
+ def __init__(self, perm, auth_needed, arg_needed, check_path, help):
+ self.perm = perm
+ self.auth_needed = auth_needed
+ self.arg_needed = arg_needed
+ self.check_path = check_path
+ self.help = help
+
+for cmd, properties in proto_cmds.iteritems():
+ proto_cmds[cmd] = _CommandProperty(*properties)
+del cmd, properties
+
+
+# hack around format_exc function of traceback module to grant
+# backward compatibility with python < 2.4
+if not hasattr(traceback, 'format_exc'):
+ try:
+ import cStringIO as StringIO
+ except ImportError:
+ import StringIO
+
+ def _format_exc():
+ f = StringIO.StringIO()
+ traceback.print_exc(file=f)
+ data = f.getvalue()
+ f.close()
+ return data
+
+ traceback.format_exc = _format_exc
+
+
+def _strerror(err):
+ """A wrap around os.strerror() which may be not available on all
+ platforms (e.g. pythonCE).
+
+ - (instance) err: an EnvironmentError or derived class instance.
+ """
+ if hasattr(os, 'strerror'):
+ return os.strerror(err.errno)
+ else:
+ return err.strerror
+
+# the heap used for the scheduled tasks
+_tasks = []
+
+def _scheduler():
+ """Run the scheduled functions due to expire soonest (if any)."""
+ now = time.time()
+ while _tasks and now >= _tasks[0].timeout:
+ call = heapq.heappop(_tasks)
+ if call.repush:
+ heapq.heappush(_tasks, call)
+ call.repush = False
+ continue
+ try:
+ call.call()
+ finally:
+ if not call.cancelled:
+ call.cancel()
+
+
+class CallLater:
+ """Calls a function at a later time.
+
+ It can be used to asynchronously schedule a call within the polling
+ loop without blocking it. The instance returned is an object that
+ can be used to cancel or reschedule the call.
+ """
+
+ def __init__(self, seconds, target, *args, **kwargs):
+ """
+ - (int) seconds: the number of seconds to wait
+ - (obj) target: the callable object to call later
+ - args: the arguments to call it with
+ - kwargs: the keyword arguments to call it with
+ """
+ assert callable(target), "%s is not callable" %target
+ assert sys.maxint >= seconds >= 0, "%s is not greater than or equal " \
+ "to 0 seconds" % (seconds)
+ self.__delay = seconds
+ self.__target = target
+ self.__args = args
+ self.__kwargs = kwargs
+ # seconds from the epoch at which to call the function
+ self.timeout = time.time() + self.__delay
+ self.repush = False
+ self.cancelled = False
+ heapq.heappush(_tasks, self)
+
+ def __le__(self, other):
+ return self.timeout <= other.timeout
+
+ def call(self):
+ """Call this scheduled function."""
+ assert not self.cancelled, "Already cancelled"
+ self.__target(*self.__args, **self.__kwargs)
+
+ def reset(self):
+ """Reschedule this call resetting the current countdown."""
+ assert not self.cancelled, "Already cancelled"
+ self.timeout = time.time() + self.__delay
+ self.repush = True
+
+ def delay(self, seconds):
+ """Reschedule this call for a later time."""
+ assert not self.cancelled, "Already cancelled."
+ assert sys.maxint >= seconds >= 0, "%s is not greater than or equal " \
+ "to 0 seconds" %(seconds)
+ self.__delay = seconds
+ newtime = time.time() + self.__delay
+ if newtime > self.timeout:
+ self.timeout = newtime
+ self.repush = True
+ else:
+ # XXX - slow, can be improved
+ self.timeout = newtime
+ heapq.heapify(_tasks)
+
+ def cancel(self):
+ """Unschedule this call."""
+ assert not self.cancelled, "Already cancelled"
+ self.cancelled = True
+ del self.__target, self.__args, self.__kwargs
+ if self in _tasks:
+ pos = _tasks.index(self)
+ if pos == 0:
+ heapq.heappop(_tasks)
+ elif pos == len(_tasks) - 1:
+ _tasks.pop(pos)
+ else:
+ _tasks[pos] = _tasks.pop()
+ heapq._siftup(_tasks, pos)
+
+
+# --- library defined exceptions
+
+class Error(Exception):
+ """Base class for module exceptions."""
+
+class AuthorizerError(Error):
+ """Base class for authorizer exceptions."""
+
+
+# --- loggers
+
+def log(msg):
+ """Log messages intended for the end user."""
+ print msg
+
+def logline(msg):
+ """Log commands and responses passing through the command channel."""
+ print msg
+
+def logerror(msg):
+ """Log traceback outputs occurring in case of errors."""
+ sys.stderr.write(str(msg) + '\n')
+ sys.stderr.flush()
+
+
+# --- authorizers
+
+class DummyAuthorizer:
+ """Basic "dummy" authorizer class, suitable for subclassing to
+ create your own custom authorizers.
+
+ An "authorizer" is a class handling authentications and permissions
+ of the FTP server. It is used inside FTPHandler class for verifying
+ user's password, getting users home directory, checking user
+ permissions when a file read/write event occurs and changing user
+ before accessing the filesystem.
+
+ DummyAuthorizer is the base authorizer, providing a platform
+ independent interface for managing "virtual" FTP users. System
+ dependent authorizers can by written by subclassing this base
+ class and overriding appropriate methods as necessary.
+ """
+
+ read_perms = "elr"
+ write_perms = "adfmw"
+
+ def __init__(self):
+ self.user_table = {}
+
+ def add_user(self, username, password, homedir, perm='elr',
+ msg_login="Login successful.", msg_quit="Goodbye."):
+ """Add a user to the virtual users table.
+
+ AuthorizerError exceptions raised on error conditions such as
+ invalid permissions, missing home directory or duplicate usernames.
+
+ Optional perm argument is a string referencing the user's
+ permissions explained below:
+
+ Read permissions:
+ - "e" = change directory (CWD command)
+ - "l" = list files (LIST, NLST, MLSD commands)
+ - "r" = retrieve file from the server (RETR command)
+
+ Write permissions:
+ - "a" = append data to an existing file (APPE command)
+ - "d" = delete file or directory (DELE, RMD commands)
+ - "f" = rename file or directory (RNFR, RNTO commands)
+ - "m" = create directory (MKD command)
+ - "w" = store a file to the server (STOR, STOU commands)
+
+ Optional msg_login and msg_quit arguments can be specified to
+ provide customized response strings when user log-in and quit.
+ """
+ if self.has_user(username):
+ raise AuthorizerError('User "%s" already exists' %username)
+ if not os.path.isdir(homedir):
+ raise AuthorizerError('No such directory: "%s"' %homedir)
+ homedir = os.path.realpath(homedir)
+ self._check_permissions(username, perm)
+ dic = {'pwd': str(password),
+ 'home': homedir,
+ 'perm': perm,
+ 'operms': {},
+ 'msg_login': str(msg_login),
+ 'msg_quit': str(msg_quit)
+ }
+ self.user_table[username] = dic
+
+ def add_anonymous(self, homedir, **kwargs):
+ """Add an anonymous user to the virtual users table.
+
+ AuthorizerError exception raised on error conditions such as
+ invalid permissions, missing home directory, or duplicate
+ anonymous users.
+
+ The keyword arguments in kwargs are the same expected by
+ add_user method: "perm", "msg_login" and "msg_quit".
+
+ The optional "perm" keyword argument is a string defaulting to
+ "elr" referencing "read-only" anonymous user's permissions.
+
+ Using write permission values ("adfmw") results in a
+ RuntimeWarning.
+ """
+ DummyAuthorizer.add_user(self, 'anonymous', '', homedir, **kwargs)
+
+ def remove_user(self, username):
+ """Remove a user from the virtual users table."""
+ del self.user_table[username]
+
+ def override_perm(self, username, directory, perm, recursive=False):
+ """Override permissions for a given directory."""
+ self._check_permissions(username, perm)
+ if not os.path.isdir(directory):
+ raise AuthorizerError('No such directory: "%s"' %directory)
+ directory = os.path.normcase(os.path.realpath(directory))
+ home = os.path.normcase(self.get_home_dir(username))
+ if directory == home:
+ raise AuthorizerError("Can't override home directory permissions")
+ if not self._issubpath(directory, home):
+ raise AuthorizerError("Path escapes user home directory")
+ self.user_table[username]['operms'][directory] = perm, recursive
+
+ def validate_authentication(self, username, password):
+ """Return True if the supplied username and password match the
+ stored credentials."""
+ return self.user_table[username]['pwd'] == password
+
+ def impersonate_user(self, username, password):
+ """Impersonate another user (noop).
+
+ It is always called before accessing the filesystem.
+ By default it does nothing. The subclass overriding this
+ method is expected to provide a mechanism to change the
+ current user.
+ """
+
+ def terminate_impersonation(self):
+ """Terminate impersonation (noop).
+
+ It is always called after having accessed the filesystem.
+ By default it does nothing. The subclass overriding this
+ method is expected to provide a mechanism to switch back
+ to the original user.
+ """
+
+ def has_user(self, username):
+ """Whether the username exists in the virtual users table."""
+ return username in self.user_table
+
+ def has_perm(self, username, perm, path=None):
+ """Whether the user has permission over path (an absolute
+ pathname of a file or a directory).
+
+ Expected perm argument is one of the following letters:
+ "elradfmw".
+ """
+ if path is None:
+ return perm in self.user_table[username]['perm']
+
+ path = os.path.normcase(path)
+ for dir in self.user_table[username]['operms'].keys():
+ operm, recursive = self.user_table[username]['operms'][dir]
+ if self._issubpath(path, dir):
+ if recursive:
+ return perm in operm
+ if (path == dir) or (os.path.dirname(path) == dir \
+ and not os.path.isdir(path)):
+ return perm in operm
+
+ return perm in self.user_table[username]['perm']
+
+ def get_perms(self, username):
+ """Return current user permissions."""
+ return self.user_table[username]['perm']
+
+ def get_home_dir(self, username):
+ """Return the user's home directory."""
+ return self.user_table[username]['home']
+
+ def get_msg_login(self, username):
+ """Return the user's login message."""
+ return self.user_table[username]['msg_login']
+
+ def get_msg_quit(self, username):
+ """Return the user's quitting message."""
+ return self.user_table[username]['msg_quit']
+
+ def _check_permissions(self, username, perm):
+ warned = 0
+ for p in perm:
+ if p not in 'elradfmw':
+ raise AuthorizerError('No such permission "%s"' %p)
+ if (username == 'anonymous') and (p in "adfmw") and not warned:
+ warnings.warn("Write permissions assigned to anonymous user.",
+ RuntimeWarning)
+ warned = 1
+
+ def _issubpath(self, a, b):
+ """Return True if a is a sub-path of b or if the paths are equal."""
+ p1 = a.rstrip(os.sep).split(os.sep)
+ p2 = b.rstrip(os.sep).split(os.sep)
+ return p1[:len(p2)] == p2
+
+
+
+# --- DTP classes
+
+class PassiveDTP(asyncore.dispatcher):
+ """This class is an asyncore.disptacher subclass. It creates a
+ socket listening on a local port, dispatching the resultant
+ connection to DTPHandler.
+
+ - (int) timeout: the timeout for a remote client to establish
+ connection with the listening socket. Defaults to 30 seconds.
+ """
+ timeout = 30
+
+ def __init__(self, cmd_channel, extmode=False):
+ """Initialize the passive data server.
+
+ - (instance) cmd_channel: the command channel class instance.
+ - (bool) extmode: wheter use extended passive mode response type.
+ """
+ asyncore.dispatcher.__init__(self)
+ self.cmd_channel = cmd_channel
+ if self.timeout:
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+ else:
+ self.idler = None
+
+ ip = self.cmd_channel.getsockname()[0]
+ self.create_socket(self.cmd_channel.af, socket.SOCK_STREAM)
+
+ if self.cmd_channel.passive_ports is None:
+ # By using 0 as port number value we let kernel choose a
+ # free unprivileged random port.
+ self.bind((ip, 0))
+ else:
+ ports = list(self.cmd_channel.passive_ports)
+ while ports:
+ port = ports.pop(random.randint(0, len(ports) -1))
+ try:
+ self.bind((ip, port))
+ except socket.error, why:
+ if why[0] == errno.EADDRINUSE: # port already in use
+ if ports:
+ continue
+ # If cannot use one of the ports in the configured
+ # range we'll use a kernel-assigned port, and log
+ # a message reporting the issue.
+ # By using 0 as port number value we let kernel
+ # choose a free unprivileged random port.
+ else:
+ self.bind((ip, 0))
+ self.cmd_channel.log(
+ "Can't find a valid passive port in the "
+ "configured range. A random kernel-assigned "
+ "port will be used."
+ )
+ else:
+ raise
+ else:
+ break
+ self.listen(5)
+ port = self.socket.getsockname()[1]
+ if not extmode:
+ if self.cmd_channel.masquerade_address:
+ ip = self.cmd_channel.masquerade_address
+ # The format of 227 response in not standardized.
+ # This is the most expected:
+ self.cmd_channel.respond('227 Entering passive mode (%s,%d,%d).' %(
+ ip.replace('.', ','), port / 256, port % 256))
+ else:
+ self.cmd_channel.respond('229 Entering extended passive mode '
+ '(|||%d|).' %port)
+
+ # --- connection / overridden
+
+ def handle_accept(self):
+ """Called when remote client initiates a connection."""
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+ sock, addr = self.accept()
+
+ # Check the origin of data connection. If not expressively
+ # configured we drop the incoming data connection if remote
+ # IP address does not match the client's IP address.
+ if (self.cmd_channel.remote_ip != addr[0]):
+ if not self.cmd_channel.permit_foreign_addresses:
+ try:
+ sock.close()
+ except socket.error:
+ pass
+ msg = 'Rejected data connection from foreign address %s:%s.' \
+ %(addr[0], addr[1])
+ self.cmd_channel.respond("425 %s" %msg)
+ self.cmd_channel.log(msg)
+ # do not close listening socket: it couldn't be client's blame
+ return
+ else:
+ # site-to-site FTP allowed
+ msg = 'Established data connection with foreign address %s:%s.'\
+ %(addr[0], addr[1])
+ self.cmd_channel.log(msg)
+ # Immediately close the current channel (we accept only one
+ # connection at time) and avoid running out of max connections
+ # limit.
+ self.close()
+ # delegate such connection to DTP handler
+ handler = self.cmd_channel.dtp_handler(sock, self.cmd_channel)
+ self.cmd_channel.data_channel = handler
+ self.cmd_channel.on_dtp_connection()
+
+ def handle_timeout(self):
+ self.cmd_channel.respond("421 Passive data channel timed out.")
+ self.close()
+
+ def writable(self):
+ return 0
+
+ def handle_error(self):
+ """Called to handle any uncaught exceptions."""
+ try:
+ raise
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ raise
+ logerror(traceback.format_exc())
+ self.close()
+
+ def close(self):
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+ asyncore.dispatcher.close(self)
+
+
+class ActiveDTP(asyncore.dispatcher):
+ """This class is an asyncore.disptacher subclass. It creates a
+ socket resulting from the connection to a remote user-port,
+ dispatching it to DTPHandler.
+
+ - (int) timeout: the timeout for us to establish connection with
+ the client's listening data socket.
+ """
+ timeout = 30
+
+ def __init__(self, ip, port, cmd_channel):
+ """Initialize the active data channel attemping to connect
+ to remote data socket.
+
+ - (str) ip: the remote IP address.
+ - (int) port: the remote port.
+ - (instance) cmd_channel: the command channel class instance.
+ """
+ asyncore.dispatcher.__init__(self)
+ self.cmd_channel = cmd_channel
+ if self.timeout:
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+ else:
+ self.idler = None
+ self.create_socket(self.cmd_channel.af, socket.SOCK_STREAM)
+ try:
+ self.connect((ip, port))
+ except socket.gaierror:
+ self.cmd_channel.respond("425 Can't connect to specified address.")
+ self.close()
+
+ # --- connection / overridden
+
+ def handle_write(self):
+ # NOOP, overridden to prevent unhandled write event msg to
+ # be printed on Python < 2.6
+ pass
+
+ def handle_connect(self):
+ """Called when connection is established."""
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+ self.cmd_channel.respond('200 Active data connection established.')
+ # delegate such connection to DTP handler
+ handler = self.cmd_channel.dtp_handler(self.socket, self.cmd_channel)
+ self.cmd_channel.data_channel = handler
+ self.cmd_channel.on_dtp_connection()
+ #self.close() # <-- (done automatically)
+
+ def handle_timeout(self):
+ self.cmd_channel.respond("421 Active data channel timed out.")
+ self.close()
+
+ def handle_expt(self):
+ self.cmd_channel.respond("425 Can't connect to specified address.")
+ self.close()
+
+ def handle_error(self):
+ """Called to handle any uncaught exceptions."""
+ try:
+ raise
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ raise
+ except socket.error:
+ pass
+ except:
+ logerror(traceback.format_exc())
+ self.cmd_channel.respond("425 Can't connect to specified address.")
+ self.close()
+
+ def close(self):
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+ asyncore.dispatcher.close(self)
+
+
+try:
+ from collections import deque
+except ImportError:
+ # backward compatibility with Python < 2.4 by replacing deque with a list
+ class deque(list):
+ def appendleft(self, obj):
+ list.insert(self, 0, obj)
+
+
+class DTPHandler(asyncore.dispatcher):
+ """Class handling server-data-transfer-process (server-DTP, see
+ RFC-959) managing data-transfer operations involving sending
+ and receiving data.
+
+ Instance attributes defined in this class, initialized when
+ channel is opened:
+
+ - (int) timeout: the timeout which roughly is the maximum time we
+ permit data transfers to stall for with no progress. If the
+ timeout triggers, the remote client will be kicked off.
+
+ - (instance) cmd_channel: the command channel class instance.
+ - (file) file_obj: the file transferred (if any).
+ - (bool) receive: True if channel is used for receiving data.
+ - (bool) transfer_finished: True if transfer completed successfully.
+ - (int) tot_bytes_sent: the total bytes sent.
+ - (int) tot_bytes_received: the total bytes received.
+
+ DTPHandler implementation note:
+
+ When a producer is consumed and close_when_done() has been called
+ previously, refill_buffer() erroneously calls close() instead of
+ handle_close() - (see: http://bugs.python.org/issue1740572)
+
+ To avoid this problem DTPHandler is implemented as a subclass of
+ asyncore.dispatcher instead of asynchat.async_chat.
+ This implementation follows the same approach that asynchat module
+ should use in Python 2.6.
+
+ The most important change in the implementation is related to
+ producer_fifo, which is a pure deque object instead of a
+ producer_fifo instance.
+
+ Since we don't want to break backward compatibily with older python
+ versions (deque has been introduced in Python 2.4), if deque is not
+ available we use a list instead.
+ """
+
+ timeout = 300
+ ac_in_buffer_size = 8192
+ ac_out_buffer_size = 8192
+
+ def __init__(self, sock_obj, cmd_channel):
+ """Initialize the command channel.
+
+ - (instance) sock_obj: the socket object instance of the newly
+ established connection.
+ - (instance) cmd_channel: the command channel class instance.
+ """
+ asyncore.dispatcher.__init__(self, sock_obj)
+ # we toss the use of the asynchat's "simple producer" and
+ # replace it with a pure deque, which the original fifo
+ # was a wrapping of
+ self.producer_fifo = deque()
+
+ self.cmd_channel = cmd_channel
+ self.file_obj = None
+ self.receive = False
+ self.transfer_finished = False
+ self.tot_bytes_sent = 0
+ self.tot_bytes_received = 0
+ self.data_wrapper = lambda x: x
+ self._lastdata = 0
+ self._closed = False
+ if self.timeout:
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+ else:
+ self.idler = None
+
+ # --- utility methods
+
+ def enable_receiving(self, type):
+ """Enable receiving of data over the channel. Depending on the
+ TYPE currently in use it creates an appropriate wrapper for the
+ incoming data.
+
+ - (str) type: current transfer type, 'a' (ASCII) or 'i' (binary).
+ """
+ if type == 'a':
+ self.data_wrapper = lambda x: x.replace('\r\n', os.linesep)
+ elif type == 'i':
+ self.data_wrapper = lambda x: x
+ else:
+ raise TypeError, "Unsupported type"
+ self.receive = True
+
+ def get_transmitted_bytes(self):
+ "Return the number of transmitted bytes."
+ return self.tot_bytes_sent + self.tot_bytes_received
+
+ def transfer_in_progress(self):
+ "Return True if a transfer is in progress, else False."
+ return self.get_transmitted_bytes() != 0
+
+ # --- connection
+
+ def handle_read(self):
+ """Called when there is data waiting to be read."""
+ try:
+ chunk = self.recv(self.ac_in_buffer_size)
+ except socket.error:
+ self.handle_error()
+ else:
+ self.tot_bytes_received += len(chunk)
+ if not chunk:
+ self.transfer_finished = True
+ #self.close() # <-- asyncore.recv() already do that...
+ return
+ # while we're writing on the file an exception could occur
+ # in case that filesystem gets full; if this happens we
+ # let handle_error() method handle this exception, providing
+ # a detailed error message.
+ self.file_obj.write(self.data_wrapper(chunk))
+
+ def handle_write(self):
+ """Called when data is ready to be written, initiates send."""
+ self.initiate_send()
+
+ def push(self, data):
+ """Push data onto the deque and initiate send."""
+ sabs = self.ac_out_buffer_size
+ if len(data) > sabs:
+ for i in xrange(0, len(data), sabs):
+ self.producer_fifo.append(data[i:i+sabs])
+ else:
+ self.producer_fifo.append(data)
+ self.initiate_send()
+
+ def push_with_producer(self, producer):
+ """Push data using a producer and initiate send."""
+ self.producer_fifo.append(producer)
+ self.initiate_send()
+
+ def readable(self):
+ """Predicate for inclusion in the readable for select()."""
+ return self.receive
+
+ def writable(self):
+ """Predicate for inclusion in the writable for select()."""
+ return self.producer_fifo or (not self.connected)
+
+ def close_when_done(self):
+ """Automatically close this channel once the outgoing queue is empty."""
+ self.producer_fifo.append(None)
+
+ def initiate_send(self):
+ """Attempt to send data in fifo order."""
+ while self.producer_fifo and self.connected:
+ first = self.producer_fifo[0]
+ # handle empty string/buffer or None entry
+ if not first:
+ del self.producer_fifo[0]
+ if first is None:
+ self.transfer_finished = True
+ self.handle_close()
+ return
+
+ # handle classic producer behavior
+ obs = self.ac_out_buffer_size
+ try:
+ data = buffer(first, 0, obs)
+ except TypeError:
+ data = first.more()
+ if data:
+ self.producer_fifo.appendleft(data)
+ else:
+ del self.producer_fifo[0]
+ continue
+
+ # send the data
+ try:
+ num_sent = self.send(data)
+ except socket.error:
+ self.handle_error()
+ return
+
+ if num_sent:
+ self.tot_bytes_sent += num_sent
+ if num_sent < len(data) or obs < len(first):
+ self.producer_fifo[0] = first[num_sent:]
+ else:
+ del self.producer_fifo[0]
+ # we tried to send some actual data
+ return
+
+ def handle_timeout(self):
+ """Called cyclically to check if data trasfer is stalling with
+ no progress in which case the client is kicked off.
+ """
+ if self.get_transmitted_bytes() > self._lastdata:
+ self._lastdata = self.get_transmitted_bytes()
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+ else:
+ msg = "Data connection timed out."
+ self.cmd_channel.log(msg)
+ self.cmd_channel.respond("421 " + msg)
+ self.cmd_channel.close_when_done()
+ self.close()
+
+ def handle_expt(self):
+ """Called on "exceptional" data events."""
+ self.cmd_channel.respond("426 Connection error; transfer aborted.")
+ self.close()
+
+ def handle_error(self):
+ """Called when an exception is raised and not otherwise handled."""
+ try:
+ raise
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ raise
+ except socket.error, err:
+ # fix around asyncore bug (http://bugs.python.org/issue1736101)
+ if err[0] in (errno.ECONNRESET, errno.ENOTCONN, errno.ESHUTDOWN, \
+ errno.ECONNABORTED):
+ self.handle_close()
+ return
+ else:
+ error = str(err[1])
+ # an error could occur in case we fail reading / writing
+ # from / to file (e.g. file system gets full)
+ except EnvironmentError, err:
+ error = _strerror(err)
+ except:
+ # some other exception occurred; we don't want to provide
+ # confidential error messages
+ logerror(traceback.format_exc())
+ error = "Internal error"
+ self.cmd_channel.respond("426 %s; transfer aborted." %error)
+ self.close()
+
+ def handle_close(self):
+ """Called when the socket is closed."""
+ # If we used channel for receiving we assume that transfer is
+ # finished when client close connection , if we used channel
+ # for sending we have to check that all data has been sent
+ # (responding with 226) or not (responding with 426).
+ if self.receive:
+ self.transfer_finished = True
+ action = 'received'
+ else:
+ action = 'sent'
+ if self.transfer_finished:
+ self.cmd_channel.respond("226 Transfer complete.")
+ if self.file_obj:
+ fname = self.cmd_channel.fs.fs2ftp(self.file_obj.name)
+ self.cmd_channel.log('"%s" %s.' %(fname, action))
+ else:
+ tot_bytes = self.get_transmitted_bytes()
+ msg = "Transfer aborted; %d bytes transmitted." %tot_bytes
+ self.cmd_channel.respond("426 " + msg)
+ self.cmd_channel.log(msg)
+ self.close()
+
+ def close(self):
+ """Close the data channel, first attempting to close any remaining
+ file handles."""
+ if not self._closed:
+ self._closed = True
+ if self.file_obj is not None and not self.file_obj.closed:
+ self.file_obj.close()
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+ asyncore.dispatcher.close(self)
+ self.cmd_channel.on_dtp_close()
+
+
+# --- producers
+
+class FileProducer:
+ """Producer wrapper for file[-like] objects."""
+
+ buffer_size = 65536
+
+ def __init__(self, file, type):
+ """Initialize the producer with a data_wrapper appropriate to TYPE.
+
+ - (file) file: the file[-like] object.
+ - (str) type: the current TYPE, 'a' (ASCII) or 'i' (binary).
+ """
+ self.done = False
+ self.file = file
+ if type == 'a':
+ self.data_wrapper = lambda x: x.replace(os.linesep, '\r\n')
+ elif type == 'i':
+ self.data_wrapper = lambda x: x
+ else:
+ raise TypeError, "Unsupported type"
+
+ def more(self):
+ """Attempt a chunk of data of size self.buffer_size."""
+ if self.done:
+ return ''
+ data = self.data_wrapper(self.file.read(self.buffer_size))
+ if not data:
+ self.done = True
+ if not self.file.closed:
+ self.file.close()
+ return data
+
+
+class BufferedIteratorProducer:
+ """Producer for iterator objects with buffer capabilities."""
+ # how many times iterator.next() will be called before
+ # returning some data
+ loops = 20
+
+ def __init__(self, iterator):
+ self.iterator = iterator
+
+ def more(self):
+ """Attempt a chunk of data from iterator by calling
+ its next() method different times.
+ """
+ buffer = []
+ for x in xrange(self.loops):
+ try:
+ buffer.append(self.iterator.next())
+ except StopIteration:
+ break
+ return ''.join(buffer)
+
+
+# --- filesystem
+
+class AbstractedFS:
+ """A class used to interact with the file system, providing a high
+ level, cross-platform interface compatible with both Windows and
+ UNIX style filesystems.
+
+ It provides some utility methods and some wraps around operations
+ involved in file creation and file system operations like moving
+ files or removing directories.
+
+ Instance attributes:
+ - (str) root: the user home directory.
+ - (str) cwd: the current working directory.
+ - (str) rnfr: source file to be renamed.
+ """
+
+ def __init__(self):
+ self.root = None
+ self.cwd = '/'
+ self.rnfr = None
+
+ # --- Pathname / conversion utilities
+
+ def ftpnorm(self, ftppath):
+ """Normalize a "virtual" ftp pathname (tipically the raw string
+ coming from client) depending on the current working directory.
+
+ Example (having "/foo" as current working directory):
+ 'x' -> '/foo/x'
+
+ Note: directory separators are system independent ("/").
+ Pathname returned is always absolutized.
+ """
+ if os.path.isabs(ftppath):
+ p = os.path.normpath(ftppath)
+ else:
+ p = os.path.normpath(os.path.join(self.cwd, ftppath))
+ # normalize string in a standard web-path notation having '/'
+ # as separator.
+ p = p.replace("\\", "/")
+ # os.path.normpath supports UNC paths (e.g. "//a/b/c") but we
+ # don't need them. In case we get an UNC path we collapse
+ # redundant separators appearing at the beginning of the string
+ while p[:2] == '//':
+ p = p[1:]
+ # Anti path traversal: don't trust user input, in the event
+ # that self.cwd is not absolute, return "/" as a safety measure.
+ # This is for extra protection, maybe not really necessary.
+ if not os.path.isabs(p):
+ p = "/"
+ return p
+
+ def ftp2fs(self, ftppath):
+ """Translate a "virtual" ftp pathname (tipically the raw string
+ coming from client) into equivalent absolute "real" filesystem
+ pathname.
+
+ Example (having "/home/user" as root directory):
+ 'x' -> '/home/user/x'
+
+ Note: directory separators are system dependent.
+ """
+ # as far as I know, it should always be path traversal safe...
+ if os.path.normpath(self.root) == os.sep:
+ return os.path.normpath(self.ftpnorm(ftppath))
+ else:
+ p = self.ftpnorm(ftppath)[1:]
+ return os.path.normpath(os.path.join(self.root, p))
+
+ def fs2ftp(self, fspath):
+ """Translate a "real" filesystem pathname into equivalent
+ absolute "virtual" ftp pathname depending on the user's
+ root directory.
+
+ Example (having "/home/user" as root directory):
+ '/home/user/x' -> '/x'
+
+ As for ftpnorm, directory separators are system independent
+ ("/") and pathname returned is always absolutized.
+
+ On invalid pathnames escaping from user's root directory
+ (e.g. "/home" when root is "/home/user") always return "/".
+ """
+ if os.path.isabs(fspath):
+ p = os.path.normpath(fspath)
+ else:
+ p = os.path.normpath(os.path.join(self.root, fspath))
+ if not self.validpath(p):
+ return '/'
+ p = p.replace(os.sep, "/")
+ p = p[len(self.root):]
+ if not p.startswith('/'):
+ p = '/' + p
+ return p
+
+ # alias for backward compatibility with 0.2.0
+ normalize = ftpnorm
+ translate = ftp2fs
+
+ def validpath(self, path):
+ """Check whether the path belongs to user's home directory.
+ Expected argument is a "real" filesystem pathname.
+
+ If path is a symbolic link it is resolved to check its real
+ destination.
+
+ Pathnames escaping from user's root directory are considered
+ not valid.
+ """
+ root = self.realpath(self.root)
+ path = self.realpath(path)
+ if not self.root.endswith(os.sep):
+ root = self.root + os.sep
+ if not path.endswith(os.sep):
+ path = path + os.sep
+ if path[0:len(root)] == root:
+ return True
+ return False
+
+ # --- Wrapper methods around open() and tempfile.mkstemp
+
+ def open(self, filename, mode):
+ """Open a file returning its handler."""
+ return open(filename, mode)
+
+ def mkstemp(self, suffix='', prefix='', dir=None, mode='wb'):
+ """A wrap around tempfile.mkstemp creating a file with a unique
+ name. Unlike mkstemp it returns an object with a file-like
+ interface.
+ """
+ class FileWrapper:
+ def __init__(self, fd, name):
+ self.file = fd
+ self.name = name
+ def __getattr__(self, attr):
+ return getattr(self.file, attr)
+
+ text = not 'b' in mode
+ # max number of tries to find out a unique file name
+ tempfile.TMP_MAX = 50
+ fd, name = tempfile.mkstemp(suffix, prefix, dir, text=text)
+ file = os.fdopen(fd, mode)
+ return FileWrapper(file, name)
+
+ # --- Wrapper methods around os.*
+
+ def chdir(self, path):
+ """Change the current directory."""
+ # temporarily join the specified directory to see if we have
+ # permissions to do so
+ basedir = os.getcwd()
+ try:
+ os.chdir(path)
+ except os.error:
+ raise
+ else:
+ os.chdir(basedir)
+ self.cwd = self.fs2ftp(path)
+
+ def mkdir(self, path):
+ """Create the specified directory."""
+ os.mkdir(path)
+
+ def listdir(self, path):
+ """List the content of a directory."""
+ return os.listdir(path)
+
+ def rmdir(self, path):
+ """Remove the specified directory."""
+ os.rmdir(path)
+
+ def remove(self, path):
+ """Remove the specified file."""
+ os.remove(path)
+
+ def rename(self, src, dst):
+ """Rename the specified src file to the dst filename."""
+ os.rename(src, dst)
+
+ def stat(self, path):
+ """Perform a stat() system call on the given path."""
+ return os.stat(path)
+
+ def lstat(self, path):
+ """Like stat but does not follow symbolic links."""
+ return os.lstat(path)
+
+ if not hasattr(os, 'lstat'):
+ lstat = stat
+
+ # --- Wrapper methods around os.path.*
+
+ def isfile(self, path):
+ """Return True if path is a file."""
+ return os.path.isfile(path)
+
+ def islink(self, path):
+ """Return True if path is a symbolic link."""
+ return os.path.islink(path)
+
+ def isdir(self, path):
+ """Return True if path is a directory."""
+ return os.path.isdir(path)
+
+ def getsize(self, path):
+ """Return the size of the specified file in bytes."""
+ return os.path.getsize(path)
+
+ def getmtime(self, path):
+ """Return the last modified time as a number of seconds since
+ the epoch."""
+ return os.path.getmtime(path)
+
+ def realpath(self, path):
+ """Return the canonical version of path eliminating any
+ symbolic links encountered in the path (if they are
+ supported by the operating system).
+ """
+ return os.path.realpath(path)
+
+ def lexists(self, path):
+ """Return True if path refers to an existing path, including
+ a broken or circular symbolic link.
+ """
+ if hasattr(os.path, 'lexists'):
+ return os.path.lexists(path)
+ # grant backward compatibility with python 2.3
+ elif hasattr(os, 'lstat'):
+ try:
+ os.lstat(path)
+ except os.error:
+ return False
+ return True
+ # fallback
+ else:
+ return os.path.exists(path)
+
+ exists = lexists # alias for backward compatibility with 0.2.0
+
+ # --- Listing utilities
+
+ # note: the following operations are no more blocking
+
+ def get_list_dir(self, path):
+ """"Return an iterator object that yields a directory listing
+ in a form suitable for LIST command.
+ """
+ if self.isdir(path):
+ listing = self.listdir(path)
+ listing.sort()
+ return self.format_list(path, listing)
+ # if path is a file or a symlink we return information about it
+ else:
+ basedir, filename = os.path.split(path)
+ self.lstat(path) # raise exc in case of problems
+ return self.format_list(basedir, [filename])
+
+ def format_list(self, basedir, listing, ignore_err=True):
+ """Return an iterator object that yields the entries of given
+ directory emulating the "/bin/ls -lA" UNIX command output.
+
+ - (str) basedir: the absolute dirname.
+ - (list) listing: the names of the entries in basedir
+ - (bool) ignore_err: when False raise exception if os.lstat()
+ call fails.
+
+ On platforms which do not support the pwd and grp modules (such
+ as Windows), ownership is printed as "owner" and "group" as a
+ default, and number of hard links is always "1". On UNIX
+ systems, the actual owner, group, and number of links are
+ printed.
+
+ This is how output appears to client:
+
+ -rw-rw-rw- 1 owner group 7045120 Sep 02 3:47 music.mp3
+ drwxrwxrwx 1 owner group 0 Aug 31 18:50 e-books
+ -rw-rw-rw- 1 owner group 380 Sep 02 3:40 module.py
+ """
+ for basename in listing:
+ file = os.path.join(basedir, basename)
+ try:
+ st = self.lstat(file)
+ except os.error:
+ if ignore_err:
+ continue
+ raise
+ perms = filemode(st.st_mode) # permissions
+ nlinks = st.st_nlink # number of links to inode
+ if not nlinks: # non-posix system, let's use a bogus value
+ nlinks = 1
+ size = st.st_size # file size
+ if pwd and grp:
+ # get user and group name, else just use the raw uid/gid
+ try:
+ uname = pwd.getpwuid(st.st_uid).pw_name
+ except KeyError:
+ uname = st.st_uid
+ try:
+ gname = grp.getgrgid(st.st_gid).gr_name
+ except KeyError:
+ gname = st.st_gid
+ else:
+ # on non-posix systems the only chance we use default
+ # bogus values for owner and group
+ uname = "owner"
+ gname = "group"
+ # stat.st_mtime could fail (-1) if last mtime is too old
+ # in which case we return the local time as last mtime
+ try:
+ mtime = time.strftime("%b %d %H:%M", time.localtime(st.st_mtime))
+ except ValueError:
+ mtime = time.strftime("%b %d %H:%M")
+ # if the file is a symlink, resolve it, e.g. "symlink -> realfile"
+ if stat.S_ISLNK(st.st_mode) and hasattr(os, 'readlink'):
+ basename = basename + " -> " + os.readlink(file)
+
+ # formatting is matched with proftpd ls output
+ yield "%s %3s %-8s %-8s %8s %s %s\r\n" %(perms, nlinks, uname, gname,
+ size, mtime, basename)
+
+ def format_mlsx(self, basedir, listing, perms, facts, ignore_err=True):
+ """Return an iterator object that yields the entries of a given
+ directory or of a single file in a form suitable with MLSD and
+ MLST commands.
+
+ Every entry includes a list of "facts" referring the listed
+ element. See RFC-3659, chapter 7, to see what every single
+ fact stands for.
+
+ - (str) basedir: the absolute dirname.
+ - (list) listing: the names of the entries in basedir
+ - (str) perms: the string referencing the user permissions.
+ - (str) facts: the list of "facts" to be returned.
+ - (bool) ignore_err: when False raise exception if os.stat()
+ call fails.
+
+ Note that "facts" returned may change depending on the platform
+ and on what user specified by using the OPTS command.
+
+ This is how output could appear to the client issuing
+ a MLSD request:
+
+ type=file;size=156;perm=r;modify=20071029155301;unique=801cd2; music.mp3
+ type=dir;size=0;perm=el;modify=20071127230206;unique=801e33; ebooks
+ type=file;size=211;perm=r;modify=20071103093626;unique=801e32; module.py
+ """
+ permdir = ''.join([x for x in perms if x not in 'arw'])
+ permfile = ''.join([x for x in perms if x not in 'celmp'])
+ if ('w' in perms) or ('a' in perms) or ('f' in perms):
+ permdir += 'c'
+ if 'd' in perms:
+ permdir += 'p'
+ type = size = perm = modify = create = unique = mode = uid = gid = ""
+ for basename in listing:
+ file = os.path.join(basedir, basename)
+ try:
+ st = self.stat(file)
+ except OSError:
+ if ignore_err:
+ continue
+ raise
+ # type + perm
+ if stat.S_ISDIR(st.st_mode):
+ if 'type' in facts:
+ if basename == '.':
+ type = 'type=cdir;'
+ elif basename == '..':
+ type = 'type=pdir;'
+ else:
+ type = 'type=dir;'
+ if 'perm' in facts:
+ perm = 'perm=%s;' %permdir
+ else:
+ if 'type' in facts:
+ type = 'type=file;'
+ if 'perm' in facts:
+ perm = 'perm=%s;' %permfile
+ if 'size' in facts:
+ size = 'size=%s;' %st.st_size # file size
+ # last modification time
+ if 'modify' in facts:
+ try:
+ modify = 'modify=%s;' %time.strftime("%Y%m%d%H%M%S",
+ time.localtime(st.st_mtime))
+ except ValueError:
+ # stat.st_mtime could fail (-1) if last mtime is too old
+ modify = ""
+ if 'create' in facts:
+ # on Windows we can provide also the creation time
+ try:
+ create = 'create=%s;' %time.strftime("%Y%m%d%H%M%S",
+ time.localtime(st.st_ctime))
+ except ValueError:
+ create = ""
+ # UNIX only
+ if 'unix.mode' in facts:
+ mode = 'unix.mode=%s;' %oct(st.st_mode & 0777)
+ if 'unix.uid' in facts:
+ uid = 'unix.uid=%s;' %st.st_uid
+ if 'unix.gid' in facts:
+ gid = 'unix.gid=%s;' %st.st_gid
+ # We provide unique fact (see RFC-3659, chapter 7.5.2) on
+ # posix platforms only; we get it by mixing st_dev and
+ # st_ino values which should be enough for granting an
+ # uniqueness for the file listed.
+ # The same approach is used by pure-ftpd.
+ # Implementors who want to provide unique fact on other
+ # platforms should use some platform-specific method (e.g.
+ # on Windows NTFS filesystems MTF records could be used).
+ if 'unique' in facts:
+ unique = "unique=%x%x;" %(st.st_dev, st.st_ino)
+
+ yield "%s%s%s%s%s%s%s%s%s %s\r\n" %(type, size, perm, modify, create,
+ mode, uid, gid, unique, basename)
+
+
+# --- FTP
+
+class FTPHandler(asynchat.async_chat):
+ """Implements the FTP server Protocol Interpreter (see RFC-959),
+ handling commands received from the client on the control channel.
+
+ All relevant session information is stored in class attributes
+ reproduced below and can be modified before instantiating this
+ class.
+
+ - (int) timeout:
+ The timeout which is the maximum time a remote client may spend
+ between FTP commands. If the timeout triggers, the remote client
+ will be kicked off. Defaults to 300 seconds.
+
+ - (str) banner: the string sent when client connects.
+
+ - (int) max_login_attempts:
+ the maximum number of wrong authentications before disconnecting
+ the client (default 3).
+
+ - (bool)permit_foreign_addresses:
+ FTP site-to-site transfer feature: also referenced as "FXP" it
+ permits for transferring a file between two remote FTP servers
+ without the transfer going through the client's host (not
+ recommended for security reasons as described in RFC-2577).
+ Having this attribute set to False means that all data
+ connections from/to remote IP addresses which do not match the
+ client's IP address will be dropped (defualt False).
+
+ - (bool) permit_privileged_ports:
+ set to True if you want to permit active data connections (PORT)
+ over privileged ports (not recommended, defaulting to False).
+
+ - (str) masquerade_address:
+ the "masqueraded" IP address to provide along PASV reply when
+ pyftpdlib is running behind a NAT or other types of gateways.
+ When configured pyftpdlib will hide its local address and
+ instead use the public address of your NAT (default None).
+
+ - (list) passive_ports:
+ what ports ftpd will use for its passive data transfers.
+ Value expected is a list of integers (e.g. range(60000, 65535)).
+ When configured pyftpdlib will no longer use kernel-assigned
+ random ports (default None).
+
+
+ All relevant instance attributes initialized when client connects
+ are reproduced below. You may be interested in them in case you
+ want to subclass the original FTPHandler.
+
+ - (bool) authenticated: True if client authenticated himself.
+ - (str) username: the name of the connected user (if any).
+ - (int) attempted_logins: number of currently attempted logins.
+ - (str) current_type: the current transfer type (default "a")
+ - (int) af: the address family (IPv4/IPv6)
+ - (instance) server: the FTPServer class instance.
+ - (instance) data_server: the data server instance (if any).
+ - (instance) data_channel: the data channel instance (if any).
+ """
+ # these are overridable defaults
+
+ # default classes
+ authorizer = DummyAuthorizer()
+ active_dtp = ActiveDTP
+ passive_dtp = PassiveDTP
+ dtp_handler = DTPHandler
+ abstracted_fs = AbstractedFS
+
+ # session attributes (explained in the docstring)
+ timeout = 300
+ banner = "pyftpdlib %s ready." %__ver__
+ max_login_attempts = 3
+ permit_foreign_addresses = False
+ permit_privileged_ports = False
+ masquerade_address = None
+ passive_ports = None
+
+ def __init__(self, conn, server):
+ """Initialize the command channel.
+
+ - (instance) conn: the socket object instance of the newly
+ established connection.
+ - (instance) server: the ftp server class instance.
+ """
+ asynchat.async_chat.__init__(self, conn)
+ self.set_terminator("\r\n")
+ # try to handle urgent data inline
+ try:
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_OOBINLINE, 1)
+ except socket.error:
+ pass
+
+ # public session attributes
+ self.server = server
+ self.remote_ip, self.remote_port = self.socket.getpeername()[:2]
+ self.fs = self.abstracted_fs()
+ self.authenticated = False
+ self.username = ""
+ self.password = ""
+ self.attempted_logins = 0
+ self.current_type = 'a'
+ self.restart_position = 0
+ self.quit_pending = False
+ self.sleeping = False
+ self.data_server = None
+ self.data_channel = None
+ if self.timeout:
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+ else:
+ self.idler = None
+ if hasattr(self.socket, 'family'):
+ self.af = self.socket.family
+ else: # python < 2.5
+ ip, port = self.socket.getsockname()[:2]
+ self.af = socket.getaddrinfo(ip, port, socket.AF_UNSPEC,
+ socket.SOCK_STREAM)[0][0]
+
+ # private session attributes
+ self._in_buffer = []
+ self._in_buffer_len = 0
+ self._epsvall = False
+ self._in_dtp_queue = None
+ self._out_dtp_queue = None
+ self._closed = False
+ self._current_facts = ['type', 'perm', 'size', 'modify']
+ if os.name == 'posix':
+ self._current_facts.append('unique')
+ self._available_facts = self._current_facts[:]
+ if pwd and grp:
+ self._available_facts += ['unix.mode', 'unix.uid', 'unix.gid']
+ if os.name == 'nt':
+ self._available_facts.append('create')
+
+ def handle(self):
+ """Return a 220 'Ready' response to the client over the command
+ channel.
+ """
+ if len(self.banner) <= 75:
+ self.respond("220 %s" %str(self.banner))
+ else:
+ self.push('220-%s\r\n' %str(self.banner))
+ self.respond('220 ')
+
+ def handle_max_cons(self):
+ """Called when limit for maximum number of connections is reached."""
+ msg = "Too many connections. Service temporary unavailable."
+ self.respond("421 %s" %msg)
+ self.log(msg)
+ # If self.push is used, data could not be sent immediately in
+ # which case a new "loop" will occur exposing us to the risk of
+ # accepting new connections. Since this could cause asyncore to
+ # run out of fds (...and exposes the server to DoS attacks), we
+ # immediately close the channel by using close() instead of
+ # close_when_done(). If data has not been sent yet client will
+ # be silently disconnected.
+ self.close()
+
+ def handle_max_cons_per_ip(self):
+ """Called when too many clients are connected from the same IP."""
+ msg = "Too many connections from the same IP address."
+ self.respond("421 %s" %msg)
+ self.log(msg)
+ self.close_when_done()
+
+ def handle_timeout(self):
+ """Called when client does not send any command within the time
+ specified in <timeout> attribute."""
+ msg = "Control connection timed out."
+ self.log(msg)
+ self.respond("421 " + msg)
+ self.close_when_done()
+
+ # --- asyncore / asynchat overridden methods
+
+ def readable(self):
+ # if there's a quit pending we stop reading data from socket
+ return not self.sleeping
+
+ def collect_incoming_data(self, data):
+ """Read incoming data and append to the input buffer."""
+ self._in_buffer.append(data)
+ self._in_buffer_len += len(data)
+ # Flush buffer if it gets too long (possible DoS attacks).
+ # RFC-959 specifies that a 500 response could be given in
+ # such cases
+ buflimit = 2048
+ if self._in_buffer_len > buflimit:
+ self.respond('500 Command too long.')
+ self.log('Command received exceeded buffer limit of %s.' %(buflimit))
+ self._in_buffer = []
+ self._in_buffer_len = 0
+
+ def found_terminator(self):
+ r"""Called when the incoming data stream matches the \r\n
+ terminator.
+
+ Depending on the command received it calls the command's
+ corresponding method (e.g. for received command "MKD pathname",
+ ftp_MKD() method is called with "pathname" as the argument).
+ """
+ if self.idler and not self.idler.cancelled:
+ self.idler.reset()
+
+ line = ''.join(self._in_buffer)
+ self._in_buffer = []
+ self._in_buffer_len = 0
+
+ cmd = line.split(' ')[0].upper()
+ space = line.find(' ')
+ if space != -1:
+ arg = line[space + 1:]
+ else:
+ arg = ""
+
+ if cmd != 'PASS':
+ self.logline("<== %s" %line)
+ else:
+ self.logline("<== %s %s" %(line.split(' ')[0], '*' * 6))
+
+ # Recognize those commands having "special semantics". They
+ # may be sent as OOB data but since many ftp clients does
+ # not follow the procedure from the RFC to send Telnet IP
+ # and Synch first, we check the last 4 characters only.
+ if not cmd in proto_cmds:
+ if cmd[-4:] in ('ABOR', 'STAT', 'QUIT'):
+ cmd = cmd[-4:]
+ else:
+ self.respond('500 Command "%s" not understood.' %cmd)
+ return
+
+ if not arg and proto_cmds[cmd].arg_needed is True:
+ self.respond("501 Syntax error: command needs an argument.")
+ return
+ if arg and proto_cmds[cmd].arg_needed is False:
+ self.respond("501 Syntax error: command does not accept arguments.")
+ return
+
+ if not self.authenticated:
+ if proto_cmds[cmd].auth_needed or (cmd == 'STAT' and arg):
+ self.respond("530 Log in with USER and PASS first.")
+ else:
+ method = getattr(self, 'ftp_' + cmd)
+ method(arg) # call the proper ftp_* method
+ else:
+ if cmd == 'STAT' and not arg:
+ self.ftp_STAT('')
+ return
+
+ # for file-system related commands check whether real path
+ # destination is valid
+ if proto_cmds[cmd].check_path and cmd != 'STOU':
+ if cmd in ('CWD', 'XCWD'):
+ arg = self.fs.ftp2fs(arg or '/')
+ elif cmd in ('CDUP', 'XCUP'):
+ arg = self.fs.ftp2fs('..')
+ elif cmd == 'LIST':
+ if arg.lower() in ('-a', '-l', '-al', '-la'):
+ arg = self.fs.ftp2fs(self.fs.cwd)
+ else:
+ arg = self.fs.ftp2fs(arg or self.fs.cwd)
+ elif cmd == 'STAT':
+ if glob.has_magic(arg):
+ self.respond('550 Globbing not supported.')
+ return
+ arg = self.fs.ftp2fs(arg or self.fs.cwd)
+ else: # LIST, NLST, MLSD, MLST
+ arg = self.fs.ftp2fs(arg or self.fs.cwd)
+
+ if not self.fs.validpath(arg):
+ line = self.fs.fs2ftp(arg)
+ err = '"%s" points to a path which is outside ' \
+ "the user's root directory" %line
+ self.respond("550 %s." %err)
+ self.log('FAIL %s "%s". %s.' %(cmd, line, err))
+ return
+
+ # check permission
+ perm = proto_cmds[cmd].perm
+ if perm is not None and cmd != 'STOU':
+ if not self.authorizer.has_perm(self.username, perm, arg):
+ self.log('FAIL %s "%s". Not enough privileges.' \
+ %(cmd, self.fs.fs2ftp(arg)))
+ self.respond("550 Can't %s. Not enough privileges." %cmd)
+ return
+
+ # call the proper ftp_* method
+ method = getattr(self, 'ftp_' + cmd)
+ method(arg)
+
+ def handle_expt(self):
+ """Called when there is out of band (OOB) data to be read.
+ This could happen in case of such clients strictly following
+ the RFC-959 directives of sending Telnet IP and Synch as OOB
+ data before issuing ABOR, STAT and QUIT commands.
+ It should never be called since the SO_OOBINLINE option is
+ enabled except on some systems like FreeBSD where it doesn't
+ seem to have effect.
+ """
+ if hasattr(socket, 'MSG_OOB'):
+ try:
+ data = self.socket.recv(1024, socket.MSG_OOB)
+ except socket.error, why:
+ if why[0] == errno.EINVAL:
+ return
+ else:
+ self._in_buffer.append(data)
+ return
+ self.log("Can't handle OOB data.")
+ self.close()
+
+ def handle_error(self):
+ try:
+ raise
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ raise
+ except socket.error, err:
+ # fix around asyncore bug (http://bugs.python.org/issue1736101)
+ if err[0] in (errno.ECONNRESET, errno.ENOTCONN, errno.ESHUTDOWN, \
+ errno.ECONNABORTED):
+ self.handle_close()
+ return
+ else:
+ logerror(traceback.format_exc())
+ except:
+ logerror(traceback.format_exc())
+ self.close()
+
+ def handle_close(self):
+ self.close()
+
+ def close(self):
+ """Close the current channel disconnecting the client."""
+ if not self._closed:
+ self._closed = True
+ if self.data_server is not None:
+ self.data_server.close()
+ del self.data_server
+
+ if self.data_channel is not None:
+ self.data_channel.close()
+ del self.data_channel
+
+ del self._out_dtp_queue
+ del self._in_dtp_queue
+
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+
+ # remove client IP address from ip map
+ self.server.ip_map.remove(self.remote_ip)
+ asynchat.async_chat.close(self)
+ self.log("Disconnected.")
+
+ # --- callbacks
+
+ def on_dtp_connection(self):
+ """Called every time data channel connects (either active or
+ passive).
+
+ Incoming and outgoing queues are checked for pending data.
+ If outbound data is pending, it is pushed into the data channel.
+ If awaiting inbound data, the data channel is enabled for
+ receiving.
+ """
+ if self.data_server is not None:
+ self.data_server.close()
+ self.data_server = None
+
+ # stop the idle timer as long as the data transfer is not finished
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+
+ # check for data to send
+ if self._out_dtp_queue is not None:
+ data, isproducer, file = self._out_dtp_queue
+ if file:
+ self.data_channel.file_obj = file
+ if not isproducer:
+ self.data_channel.push(data)
+ else:
+ self.data_channel.push_with_producer(data)
+ if self.data_channel is not None:
+ self.data_channel.close_when_done()
+ self._out_dtp_queue = None
+
+ # check for data to receive
+ elif self._in_dtp_queue is not None:
+ self.data_channel.file_obj = self._in_dtp_queue
+ self.data_channel.enable_receiving(self.current_type)
+ self._in_dtp_queue = None
+
+ def on_dtp_close(self):
+ """Called every time the data channel is closed."""
+ self.data_channel = None
+ if self.quit_pending:
+ self.close_when_done()
+ elif self.timeout:
+ # data transfer finished, restart the idle timer
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+
+ # --- utility
+
+ def respond(self, resp):
+ """Send a response to the client using the command channel."""
+ self.push(resp + '\r\n')
+ self.logline('==> %s' % resp)
+
+ def push_dtp_data(self, data, isproducer=False, file=None):
+ """Pushes data into the data channel.
+
+ It is usually called for those commands requiring some data to
+ be sent over the data channel (e.g. RETR).
+ If data channel does not exist yet, it queues the data to send
+ later; data will then be pushed into data channel when
+ on_dtp_connection() will be called.
+
+ - (str/classobj) data: the data to send which may be a string
+ or a producer object).
+ - (bool) isproducer: whether treat data as a producer.
+ - (file) file: the file[-like] object to send (if any).
+ """
+ if self.data_channel is not None:
+ self.respond("125 Data connection already open. Transfer starting.")
+ if file:
+ self.data_channel.file_obj = file
+ if not isproducer:
+ self.data_channel.push(data)
+ else:
+ self.data_channel.push_with_producer(data)
+ if self.data_channel is not None:
+ self.data_channel.close_when_done()
+ else:
+ self.respond("150 File status okay. About to open data connection.")
+ self._out_dtp_queue = (data, isproducer, file)
+
+ def log(self, msg):
+ """Log a message, including additional identifying session data."""
+ log("[%s]@%s:%s %s" %(self.username, self.remote_ip,
+ self.remote_port, msg))
+
+ def logline(self, msg):
+ """Log a line including additional indentifying session data."""
+ logline("%s:%s %s" %(self.remote_ip, self.remote_port, msg))
+
+ def flush_account(self):
+ """Flush account information by clearing attributes that need
+ to be reset on a REIN or new USER command.
+ """
+ if self.data_channel is not None:
+ if not self.data_channel.transfer_in_progress():
+ self.data_channel.close()
+ self.data_channel = None
+ if self.data_server is not None:
+ self.data_server.close()
+ self.data_server = None
+
+ self.fs.rnfr = None
+ self.authenticated = False
+ self.username = ""
+ self.password = ""
+ self.attempted_logins = 0
+ self.current_type = 'a'
+ self.restart_position = 0
+ self.quit_pending = False
+ self.sleeping = False
+ self._in_dtp_queue = None
+ self._out_dtp_queue = None
+
+ def run_as_current_user(self, function, *args, **kwargs):
+ """Execute a function impersonating the current logged-in user."""
+ self.authorizer.impersonate_user(self.username, self.password)
+ try:
+ return function(*args, **kwargs)
+ finally:
+ self.authorizer.terminate_impersonation()
+
+ # --- connection
+
+ def _make_eport(self, ip, port):
+ """Establish an active data channel with remote client which
+ issued a PORT or EPRT command.
+ """
+ # FTP bounce attacks protection: according to RFC-2577 it's
+ # recommended to reject PORT if IP address specified in it
+ # does not match client IP address.
+ if not self.permit_foreign_addresses and ip != self.remote_ip:
+ self.log("Rejected data connection to foreign address %s:%s."
+ %(ip, port))
+ self.respond("501 Can't connect to a foreign address.")
+ return
+
+ # ...another RFC-2577 recommendation is rejecting connections
+ # to privileged ports (< 1024) for security reasons.
+ if not self.permit_privileged_ports and port < 1024:
+ self.log('PORT against the privileged port "%s" refused.' %port)
+ self.respond("501 Can't connect over a privileged port.")
+ return
+
+ # close existent DTP-server instance, if any.
+ if self.data_server is not None:
+ self.data_server.close()
+ self.data_server = None
+ if self.data_channel is not None:
+ self.data_channel.close()
+ self.data_channel = None
+
+ # make sure we are not hitting the max connections limit
+ if self.server.max_cons and len(self._map) >= self.server.max_cons:
+ msg = "Too many connections. Can't open data channel."
+ self.respond("425 %s" %msg)
+ self.log(msg)
+ return
+
+ # open data channel
+ self.active_dtp(ip, port, self)
+
+ def _make_epasv(self, extmode=False):
+ """Initialize a passive data channel with remote client which
+ issued a PASV or EPSV command.
+ If extmode argument is False we assume that client issued EPSV in
+ which case extended passive mode will be used (see RFC-2428).
+ """
+ # close existing DTP-server instance, if any
+ if self.data_server is not None:
+ self.data_server.close()
+ self.data_server = None
+
+ if self.data_channel is not None:
+ self.data_channel.close()
+ self.data_channel = None
+
+ # make sure we are not hitting the max connections limit
+ if self.server.max_cons and len(self._map) >= self.server.max_cons:
+ msg = "Too many connections. Can't open data channel."
+ self.respond("425 %s" %msg)
+ self.log(msg)
+ return
+
+ # open data channel
+ self.data_server = self.passive_dtp(self, extmode)
+
+ def ftp_PORT(self, line):
+ """Start an active data channel by using IPv4."""
+ if self._epsvall:
+ self.respond("501 PORT not allowed after EPSV ALL.")
+ return
+ if self.af != socket.AF_INET:
+ self.respond("425 You cannot use PORT on IPv6 connections. "
+ "Use EPRT instead.")
+ return
+ # Parse PORT request for getting IP and PORT.
+ # Request comes in as:
+ # > h1,h2,h3,h4,p1,p2
+ # ...where the client's IP address is h1.h2.h3.h4 and the TCP
+ # port number is (p1 * 256) + p2.
+ try:
+ addr = map(int, line.split(','))
+ assert len(addr) == 6
+ for x in addr[:4]:
+ assert 0 <= x <= 255
+ ip = '%d.%d.%d.%d' %tuple(addr[:4])
+ port = (addr[4] * 256) + addr[5]
+ assert 0 <= port <= 65535
+ except (AssertionError, ValueError, OverflowError):
+ self.respond("501 Invalid PORT format.")
+ return
+ self._make_eport(ip, port)
+
+ def ftp_EPRT(self, line):
+ """Start an active data channel by choosing the network protocol
+ to use (IPv4/IPv6) as defined in RFC-2428.
+ """
+ if self._epsvall:
+ self.respond("501 EPRT not allowed after EPSV ALL.")
+ return
+ # Parse EPRT request for getting protocol, IP and PORT.
+ # Request comes in as:
+ # # <d>proto<d>ip<d>port<d>
+ # ...where <d> is an arbitrary delimiter character (usually "|") and
+ # <proto> is the network protocol to use (1 for IPv4, 2 for IPv6).
+ try:
+ af, ip, port = line.split(line[0])[1:-1]
+ port = int(port)
+ assert 0 <= port <= 65535
+ except (AssertionError, ValueError, IndexError, OverflowError):
+ self.respond("501 Invalid EPRT format.")
+ return
+
+ if af == "1":
+ if self.af != socket.AF_INET:
+ self.respond('522 Network protocol not supported (use 2).')
+ else:
+ try:
+ octs = map(int, ip.split('.'))
+ assert len(octs) == 4
+ for x in octs:
+ assert 0 <= x <= 255
+ except (AssertionError, ValueError, OverflowError):
+ self.respond("501 Invalid EPRT format.")
+ else:
+ self._make_eport(ip, port)
+ elif af == "2":
+ if self.af == socket.AF_INET:
+ self.respond('522 Network protocol not supported (use 1).')
+ else:
+ self._make_eport(ip, port)
+ else:
+ if self.af == socket.AF_INET:
+ self.respond('501 Unknown network protocol (use 1).')
+ else:
+ self.respond('501 Unknown network protocol (use 2).')
+
+ def ftp_PASV(self, line):
+ """Start a passive data channel by using IPv4."""
+ if self._epsvall:
+ self.respond("501 PASV not allowed after EPSV ALL.")
+ return
+ if self.af != socket.AF_INET:
+ self.respond("425 You cannot use PASV on IPv6 connections. "
+ "Use EPSV instead.")
+ else:
+ self._make_epasv(extmode=False)
+
+ def ftp_EPSV(self, line):
+ """Start a passive data channel by using IPv4 or IPv6 as defined
+ in RFC-2428.
+ """
+ # RFC-2428 specifies that if an optional parameter is given,
+ # we have to determine the address family from that otherwise
+ # use the same address family used on the control connection.
+ # In such a scenario a client may use IPv4 on the control channel
+ # and choose to use IPv6 for the data channel.
+ # But how could we use IPv6 on the data channel without knowing
+ # which IPv6 address to use for binding the socket?
+ # Unfortunately RFC-2428 does not provide satisfing information
+ # on how to do that. The assumption is that we don't have any way
+ # to know wich address to use, hence we just use the same address
+ # family used on the control connection.
+ if not line:
+ self._make_epasv(extmode=True)
+ elif line == "1":
+ if self.af != socket.AF_INET:
+ self.respond('522 Network protocol not supported (use 2).')
+ else:
+ self._make_epasv(extmode=True)
+ elif line == "2":
+ if self.af == socket.AF_INET:
+ self.respond('522 Network protocol not supported (use 1).')
+ else:
+ self._make_epasv(extmode=True)
+ elif line.lower() == 'all':
+ self._epsvall = True
+ self.respond('220 Other commands other than EPSV are now disabled.')
+ else:
+ if self.af == socket.AF_INET:
+ self.respond('501 Unknown network protocol (use 1).')
+ else:
+ self.respond('501 Unknown network protocol (use 2).')
+
+ def ftp_QUIT(self, line):
+ """Quit the current session disconnecting the client."""
+ if self.authenticated:
+ msg_quit = self.authorizer.get_msg_quit(self.username)
+ else:
+ msg_quit = "Goodbye."
+ if len(msg_quit) <= 75:
+ self.respond("221 %s" %msg_quit)
+ else:
+ self.push("221-%s\r\n" %msg_quit)
+ self.respond("221 ")
+
+ # From RFC-959:
+ # If file transfer is in progress, the connection will remain
+ # open for result response and the server will then close it.
+ # We also stop responding to any further command.
+ if self.data_channel:
+ self.quit_pending = True
+ self.sleeping = True
+ else:
+ self.close_when_done()
+
+ # --- data transferring
+
+ def ftp_LIST(self, path):
+ """Return a list of files in the specified directory to the
+ client.
+ """
+ # - If no argument, fall back on cwd as default.
+ # - Some older FTP clients erroneously issue /bin/ls-like LIST
+ # formats in which case we fall back on cwd as default.
+ line = self.fs.fs2ftp(path)
+ try:
+ iterator = self.run_as_current_user(self.fs.get_list_dir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL LIST "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK LIST "%s". Transfer starting.' %line)
+ producer = BufferedIteratorProducer(iterator)
+ self.push_dtp_data(producer, isproducer=True)
+
+ def ftp_NLST(self, path):
+ """Return a list of files in the specified directory in a
+ compact form to the client.
+ """
+ line = self.fs.fs2ftp(path)
+ try:
+ if self.fs.isdir(path):
+ listing = self.run_as_current_user(self.fs.listdir, path)
+ else:
+ # if path is a file we just list its name
+ self.fs.lstat(path) # raise exc in case of problems
+ listing = [os.path.basename(path)]
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL NLST "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ data = ''
+ if listing:
+ listing.sort()
+ data = '\r\n'.join(listing) + '\r\n'
+ self.log('OK NLST "%s". Transfer starting.' %line)
+ self.push_dtp_data(data)
+
+ # --- MLST and MLSD commands
+
+ # The MLST and MLSD commands are intended to standardize the file and
+ # directory information returned by the server-FTP process. These
+ # commands differ from the LIST command in that the format of the
+ # replies is strictly defined although extensible.
+
+ def ftp_MLST(self, path):
+ """Return information about a pathname in a machine-processable
+ form as defined in RFC-3659.
+ """
+ line = self.fs.fs2ftp(path)
+ basedir, basename = os.path.split(path)
+ perms = self.authorizer.get_perms(self.username)
+ try:
+ iterator = self.run_as_current_user(self.fs.format_mlsx, basedir,
+ [basename], perms, self._current_facts, ignore_err=False)
+ data = ''.join(iterator)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL MLST "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ # since TVFS is supported (see RFC-3659 chapter 6), a fully
+ # qualified pathname should be returned
+ data = data.split(' ')[0] + ' %s\r\n' %line
+ # response is expected on the command channel
+ self.push('250-Listing "%s":\r\n' %line)
+ # the fact set must be preceded by a space
+ self.push(' ' + data)
+ self.respond('250 End MLST.')
+
+ def ftp_MLSD(self, path):
+ """Return contents of a directory in a machine-processable form
+ as defined in RFC-3659.
+ """
+ line = self.fs.fs2ftp(path)
+ # RFC-3659 requires 501 response code if path is not a directory
+ if not self.fs.isdir(path):
+ err = 'No such directory'
+ self.log('FAIL MLSD "%s". %s.' %(line, err))
+ self.respond("501 %s." %err)
+ return
+ try:
+ listing = self.run_as_current_user(self.fs.listdir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL MLSD "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ perms = self.authorizer.get_perms(self.username)
+ iterator = self.fs.format_mlsx(path, listing, perms,
+ self._current_facts)
+ producer = BufferedIteratorProducer(iterator)
+ self.log('OK MLSD "%s". Transfer starting.' %line)
+ self.push_dtp_data(producer, isproducer=True)
+
+ def ftp_RETR(self, file):
+ """Retrieve the specified file (transfer from the server to the
+ client)
+ """
+ line = self.fs.fs2ftp(file)
+ try:
+ fd = self.run_as_current_user(self.fs.open, file, 'rb')
+ except IOError, err:
+ why = _strerror(err)
+ self.log('FAIL RETR "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ return
+
+ if self.restart_position:
+ # Make sure that the requested offset is valid (within the
+ # size of the file being resumed).
+ # According to RFC-1123 a 554 reply may result in case that
+ # the existing file cannot be repositioned as specified in
+ # the REST.
+ ok = 0
+ try:
+ assert not self.restart_position > self.fs.getsize(file)
+ fd.seek(self.restart_position)
+ ok = 1
+ except AssertionError:
+ why = "Invalid REST parameter"
+ except IOError, err:
+ why = _strerror(err)
+ self.restart_position = 0
+ if not ok:
+ self.respond('554 %s' %why)
+ self.log('FAIL RETR "%s". %s.' %(line, why))
+ return
+ self.log('OK RETR "%s". Download starting.' %line)
+ producer = FileProducer(fd, self.current_type)
+ self.push_dtp_data(producer, isproducer=True, file=fd)
+
+ def ftp_STOR(self, file, mode='w'):
+ """Store a file (transfer from the client to the server)."""
+ # A resume could occur in case of APPE or REST commands.
+ # In that case we have to open file object in different ways:
+ # STOR: mode = 'w'
+ # APPE: mode = 'a'
+ # REST: mode = 'r+' (to permit seeking on file object)
+ if 'a' in mode:
+ cmd = 'APPE'
+ else:
+ cmd = 'STOR'
+ line = self.fs.fs2ftp(file)
+ if self.restart_position:
+ mode = 'r+'
+ try:
+ fd = self.run_as_current_user(self.fs.open, file, mode + 'b')
+ except IOError, err:
+ why = _strerror(err)
+ self.log('FAIL %s "%s". %s.' %(cmd, line, why))
+ self.respond('550 %s.' %why)
+ return
+
+ if self.restart_position:
+ # Make sure that the requested offset is valid (within the
+ # size of the file being resumed).
+ # According to RFC-1123 a 554 reply may result in case
+ # that the existing file cannot be repositioned as
+ # specified in the REST.
+ ok = 0
+ try:
+ assert not self.restart_position > self.fs.getsize(file)
+ fd.seek(self.restart_position)
+ ok = 1
+ except AssertionError:
+ why = "Invalid REST parameter"
+ except IOError, err:
+ why = _strerror(err)
+ self.restart_position = 0
+ if not ok:
+ self.respond('554 %s' %why)
+ self.log('FAIL %s "%s". %s.' %(cmd, line, why))
+ return
+
+ self.log('OK %s "%s". Upload starting.' %(cmd, line))
+ if self.data_channel is not None:
+ self.respond("125 Data connection already open. Transfer starting.")
+ self.data_channel.file_obj = fd
+ self.data_channel.enable_receiving(self.current_type)
+ else:
+ self.respond("150 File status okay. About to open data connection.")
+ self._in_dtp_queue = fd
+
+
+ def ftp_STOU(self, line):
+ """Store a file on the server with a unique name."""
+ # Note 1: RFC-959 prohibited STOU parameters, but this
+ # prohibition is obsolete.
+ # Note 2: 250 response wanted by RFC-959 has been declared
+ # incorrect in RFC-1123 that wants 125/150 instead.
+ # Note 3: RFC-1123 also provided an exact output format
+ # defined to be as follow:
+ # > 125 FILE: pppp
+ # ...where pppp represents the unique path name of the
+ # file that will be written.
+
+ # watch for STOU preceded by REST, which makes no sense.
+ if self.restart_position:
+ self.respond("450 Can't STOU while REST request is pending.")
+ return
+
+ if line:
+ basedir, prefix = os.path.split(self.fs.ftp2fs(line))
+ prefix = prefix + '.'
+ else:
+ basedir = self.fs.ftp2fs(self.fs.cwd)
+ prefix = 'ftpd.'
+ try:
+ fd = self.run_as_current_user(self.fs.mkstemp, prefix=prefix,
+ dir=basedir)
+ except IOError, err:
+ # hitted the max number of tries to find out file with
+ # unique name
+ if err.errno == errno.EEXIST:
+ why = 'No usable unique file name found'
+ # something else happened
+ else:
+ why = _strerror(err)
+ self.respond("450 %s." %why)
+ self.log('FAIL STOU "%s". %s.' %(self.fs.ftpnorm(line), why))
+ return
+
+ if not self.authorizer.has_perm(self.username, 'w', fd.name):
+ try:
+ fd.close()
+ self.run_as_current_user(self.fs.remove, fd.name)
+ except os.error:
+ pass
+ self.log('FAIL STOU "%s". Not enough privileges'
+ %self.fs.ftpnorm(line))
+ self.respond("550 Can't STOU: not enough privileges.")
+ return
+
+ # now just acts like STOR except that restarting isn't allowed
+ filename = os.path.basename(fd.name)
+ self.log('OK STOU "%s". Upload starting.' %filename)
+ if self.data_channel is not None:
+ self.respond("125 FILE: %s" %filename)
+ self.data_channel.file_obj = fd
+ self.data_channel.enable_receiving(self.current_type)
+ else:
+ self.respond("150 FILE: %s" %filename)
+ self._in_dtp_queue = fd
+
+
+ def ftp_APPE(self, file):
+ """Append data to an existing file on the server."""
+ # watch for APPE preceded by REST, which makes no sense.
+ if self.restart_position:
+ self.respond("550 Can't APPE while REST request is pending.")
+ else:
+ self.ftp_STOR(file, mode='a')
+
+ def ftp_REST(self, line):
+ """Restart a file transfer from a previous mark."""
+ try:
+ marker = int(line)
+ if marker < 0:
+ raise ValueError
+ except (ValueError, OverflowError):
+ self.respond("501 Invalid parameter.")
+ else:
+ self.respond("350 Restarting at position %s. " \
+ "Now use RETR/STOR for resuming." %marker)
+ self.log("OK REST %s." %marker)
+ self.restart_position = marker
+
+ def ftp_ABOR(self, line):
+ """Abort the current data transfer."""
+
+ # ABOR received while no data channel exists
+ if (self.data_server is None) and (self.data_channel is None):
+ resp = "225 No transfer to abort."
+ else:
+ # a PASV was received but connection wasn't made yet
+ if self.data_server is not None:
+ self.data_server.close()
+ self.data_server = None
+ resp = "225 ABOR command successful; data channel closed."
+
+ # If a data transfer is in progress the server must first
+ # close the data connection, returning a 426 reply to
+ # indicate that the transfer terminated abnormally, then it
+ # must send a 226 reply, indicating that the abort command
+ # was successfully processed.
+ # If no data has been transmitted we just respond with 225
+ # indicating that no transfer was in progress.
+ if self.data_channel is not None:
+ if self.data_channel.transfer_in_progress():
+ self.data_channel.close()
+ self.data_channel = None
+ self.respond("426 Connection closed; transfer aborted.")
+ self.log("OK ABOR. Transfer aborted, data channel closed.")
+ resp = "226 ABOR command successful."
+ else:
+ self.data_channel.close()
+ self.data_channel = None
+ self.log("OK ABOR. Data channel closed.")
+ resp = "225 ABOR command successful; data channel closed."
+ self.respond(resp)
+
+
+ # --- authentication
+
+ def ftp_USER(self, line):
+ """Set the username for the current session."""
+ # we always treat anonymous user as lower-case string.
+ if line.lower() == "anonymous":
+ line = "anonymous"
+
+ # RFC-959 specifies a 530 response to the USER command if the
+ # username is not valid. If the username is valid is required
+ # ftpd returns a 331 response instead. In order to prevent a
+ # malicious client from determining valid usernames on a server,
+ # it is suggested by RFC-2577 that a server always return 331 to
+ # the USER command and then reject the combination of username
+ # and password for an invalid username when PASS is provided later.
+ if not self.authenticated:
+ self.respond('331 Username ok, send password.')
+ else:
+ # a new USER command could be entered at any point in order
+ # to change the access control flushing any user, password,
+ # and account information already supplied and beginning the
+ # login sequence again.
+ self.flush_account()
+ msg = 'Previous account information was flushed'
+ self.log('OK USER "%s". %s.' %(line, msg))
+ self.respond('331 %s, send password.' %msg)
+ self.username = line
+
+ def ftp_PASS(self, line):
+ """Check username's password against the authorizer."""
+ if self.authenticated:
+ self.respond("503 User already authenticated.")
+ return
+ if not self.username:
+ self.respond("503 Login with USER first.")
+ return
+
+ def auth_failed(msg="Authentication failed."):
+ if not self._closed:
+ self.attempted_logins += 1
+ if self.attempted_logins >= self.max_login_attempts:
+ msg = "530 " + msg + " Disconnecting."
+ self.respond(msg)
+ self.log(msg)
+ self.close_when_done()
+ else:
+ self.respond("530 " + msg)
+ self.log(msg)
+ self.sleeping = False
+
+ # username ok
+ if self.authorizer.has_user(self.username):
+ if self.username == 'anonymous' \
+ or self.authorizer.validate_authentication(self.username, line):
+ msg_login = self.authorizer.get_msg_login(self.username)
+ if len(msg_login) <= 75:
+ self.respond('230 %s' %msg_login)
+ else:
+ self.push("230-%s\r\n" %msg_login)
+ self.respond("230 ")
+
+ self.authenticated = True
+ self.password = line
+ self.attempted_logins = 0
+ self.fs.root = self.authorizer.get_home_dir(self.username)
+ self.log("User %s logged in." %self.username)
+ else:
+ CallLater(5, auth_failed)
+ self.username = ""
+ self.sleeping = True
+ # wrong username
+ else:
+ if self.username.lower() == 'anonymous':
+ CallLater(5, auth_failed, "Anonymous access not allowed.")
+ else:
+ CallLater(5, auth_failed)
+ self.username = ""
+ self.sleeping = True
+
+ def ftp_REIN(self, line):
+ """Reinitialize user's current session."""
+ # From RFC-959:
+ # REIN command terminates a USER, flushing all I/O and account
+ # information, except to allow any transfer in progress to be
+ # completed. All parameters are reset to the default settings
+ # and the control connection is left open. This is identical
+ # to the state in which a user finds himself immediately after
+ # the control connection is opened.
+ self.log("OK REIN. Flushing account information.")
+ self.flush_account()
+ # Note: RFC-959 erroneously mention "220" as the correct response
+ # code to be given in this case, but this is wrong...
+ self.respond("230 Ready for new user.")
+
+
+ # --- filesystem operations
+
+ def ftp_PWD(self, line):
+ """Return the name of the current working directory to the client."""
+ self.respond('257 "%s" is the current directory.' %self.fs.cwd)
+
+ def ftp_CWD(self, path):
+ """Change the current working directory."""
+ line = self.fs.fs2ftp(path)
+ try:
+ self.run_as_current_user(self.fs.chdir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL CWD "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK CWD "%s".' %self.fs.cwd)
+ self.respond('250 "%s" is the current directory.' %self.fs.cwd)
+
+ def ftp_CDUP(self, line):
+ """Change into the parent directory."""
+ # Note: RFC-959 says that code 200 is required but it also says
+ # that CDUP uses the same codes as CWD.
+ self.ftp_CWD('..')
+
+ def ftp_SIZE(self, path):
+ """Return size of file in a format suitable for using with
+ RESTart as defined in RFC-3659.
+
+ Implementation note:
+ properly handling the SIZE command when TYPE ASCII is used would
+ require to scan the entire file to perform the ASCII translation
+ logic (file.read().replace(os.linesep, '\r\n')) and then
+ calculating the len of such data which may be different than
+ the actual size of the file on the server. Considering that
+ calculating such result could be very resource-intensive it
+ could be easy for a malicious client to try a DoS attack, thus
+ we do not perform the ASCII translation.
+
+ However, clients in general should not be resuming downloads in
+ ASCII mode. Resuming downloads in binary mode is the recommended
+ way as specified in RFC-3659.
+ """
+ line = self.fs.fs2ftp(path)
+ if self.fs.isdir(path):
+ why = "%s is not retrievable" %line
+ self.log('FAIL SIZE "%s". %s.' %(line, why))
+ self.respond("550 %s." %why)
+ return
+ try:
+ size = self.run_as_current_user(self.fs.getsize, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL SIZE "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.respond("213 %s" %size)
+ self.log('OK SIZE "%s".' %line)
+
+ def ftp_MDTM(self, path):
+ """Return last modification time of file to the client as an ISO
+ 3307 style timestamp (YYYYMMDDHHMMSS) as defined in RFC-3659.
+ """
+ line = self.fs.fs2ftp(path)
+ if not self.fs.isfile(self.fs.realpath(path)):
+ why = "%s is not retrievable" %line
+ self.log('FAIL MDTM "%s". %s.' %(line, why))
+ self.respond("550 %s." %why)
+ return
+ try:
+ lmt = self.run_as_current_user(self.fs.getmtime, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL MDTM "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ lmt = time.strftime("%Y%m%d%H%M%S", time.localtime(lmt))
+ self.respond("213 %s" %lmt)
+ self.log('OK MDTM "%s".' %line)
+
+ def ftp_MKD(self, path):
+ """Create the specified directory."""
+ line = self.fs.fs2ftp(path)
+ try:
+ self.run_as_current_user(self.fs.mkdir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL MKD "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK MKD "%s".' %line)
+ self.respond("257 Directory created.")
+
+ def ftp_RMD(self, path):
+ """Remove the specified directory."""
+ line = self.fs.fs2ftp(path)
+ if self.fs.realpath(path) == self.fs.realpath(self.fs.root):
+ msg = "Can't remove root directory."
+ self.respond("550 %s" %msg)
+ self.log('FAIL MKD "/". %s' %msg)
+ return
+ try:
+ self.run_as_current_user(self.fs.rmdir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL RMD "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK RMD "%s".' %line)
+ self.respond("250 Directory removed.")
+
+ def ftp_DELE(self, path):
+ """Delete the specified file."""
+ line = self.fs.fs2ftp(path)
+ try:
+ self.run_as_current_user(self.fs.remove, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL DELE "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK DELE "%s".' %line)
+ self.respond("250 File removed.")
+
+ def ftp_RNFR(self, path):
+ """Rename the specified (only the source name is specified
+ here, see RNTO command)"""
+ if not self.fs.lexists(path):
+ self.respond("550 No such file or directory.")
+ elif self.fs.realpath(path) == self.fs.realpath(self.fs.root):
+ self.respond("550 Can't rename the home directory.")
+ else:
+ self.fs.rnfr = path
+ self.respond("350 Ready for destination name.")
+
+ def ftp_RNTO(self, path):
+ """Rename file (destination name only, source is specified with
+ RNFR).
+ """
+ if not self.fs.rnfr:
+ self.respond("503 Bad sequence of commands: use RNFR first.")
+ return
+ src = self.fs.rnfr
+ self.fs.rnfr = None
+ try:
+ self.run_as_current_user(self.fs.rename, src, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL RNFR/RNTO "%s ==> %s". %s.' \
+ %(self.fs.fs2ftp(src), self.fs.fs2ftp(path), why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK RNFR/RNTO "%s ==> %s".' \
+ %(self.fs.fs2ftp(src), self.fs.fs2ftp(path)))
+ self.respond("250 Renaming ok.")
+
+
+ # --- others
+
+ def ftp_TYPE(self, line):
+ """Set current type data type to binary/ascii"""
+ line = line.upper()
+ if line in ("A", "AN", "A N"):
+ self.respond("200 Type set to: ASCII.")
+ self.current_type = 'a'
+ elif line in ("I", "L8", "L 8"):
+ self.respond("200 Type set to: Binary.")
+ self.current_type = 'i'
+ else:
+ self.respond('504 Unsupported type "%s".' %line)
+
+ def ftp_STRU(self, line):
+ """Set file structure (obsolete)."""
+ # obsolete (backward compatibility with older ftp clients)
+ if line in ('f','F'):
+ self.respond('200 File transfer structure set to: F.')
+ else:
+ self.respond('504 Unimplemented STRU type.')
+
+ def ftp_MODE(self, line):
+ """Set data transfer mode (obsolete)"""
+ # obsolete (backward compatibility with older ftp clients)
+ if line in ('s', 'S'):
+ self.respond('200 Transfer mode set to: S')
+ else:
+ self.respond('504 Unimplemented MODE type.')
+
+ def ftp_STAT(self, path):
+ """Return statistics about current ftp session. If an argument
+ is provided return directory listing over command channel.
+
+ Implementation note:
+
+ RFC-959 does not explicitly mention globbing but many FTP
+ servers do support it as a measure of convenience for FTP
+ clients and users.
+
+ In order to search for and match the given globbing expression,
+ the code has to search (possibly) many directories, examine
+ each contained filename, and build a list of matching files in
+ memory. Since this operation can be quite intensive, both CPU-
+ and memory-wise, we do not support globbing.
+ """
+ # return STATus information about ftpd
+ if not path:
+ s = []
+ s.append('Connected to: %s:%s' %self.socket.getsockname()[:2])
+ if self.authenticated:
+ s.append('Logged in as: %s' %self.username)
+ else:
+ if not self.username:
+ s.append("Waiting for username.")
+ else:
+ s.append("Waiting for password.")
+ if self.current_type == 'a':
+ type = 'ASCII'
+ else:
+ type = 'Binary'
+ s.append("TYPE: %s; STRUcture: File; MODE: Stream" %type)
+ if self.data_server is not None:
+ s.append('Passive data channel waiting for connection.')
+ elif self.data_channel is not None:
+ bytes_sent = self.data_channel.tot_bytes_sent
+ bytes_recv = self.data_channel.tot_bytes_received
+ s.append('Data connection open:')
+ s.append('Total bytes sent: %s' %bytes_sent)
+ s.append('Total bytes received: %s' %bytes_recv)
+ else:
+ s.append('Data connection closed.')
+
+ self.push('211-FTP server status:\r\n')
+ self.push(''.join([' %s\r\n' %item for item in s]))
+ self.respond('211 End of status.')
+ # return directory LISTing over the command channel
+ else:
+ line = self.fs.fs2ftp(path)
+ try:
+ iterator = self.run_as_current_user(self.fs.get_list_dir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL STAT "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.push('213-Status of "%s":\r\n' %line)
+ self.push_with_producer(BufferedIteratorProducer(iterator))
+ self.respond('213 End of status.')
+
+ def ftp_FEAT(self, line):
+ """List all new features supported as defined in RFC-2398."""
+ features = ['EPRT','EPSV','MDTM','MLSD','REST STREAM','SIZE','TVFS']
+ s = ''
+ for fact in self._available_facts:
+ if fact in self._current_facts:
+ s += fact + '*;'
+ else:
+ s += fact + ';'
+ features.append('MLST ' + s)
+ features.sort()
+ self.push("211-Features supported:\r\n")
+ self.push("".join([" %s\r\n" %x for x in features]))
+ self.respond('211 End FEAT.')
+
+ def ftp_OPTS(self, line):
+ """Specify options for FTP commands as specified in RFC-2389."""
+ try:
+ assert (not line.count(' ') > 1), 'Invalid number of arguments'
+ if ' ' in line:
+ cmd, arg = line.split(' ')
+ assert (';' in arg), 'Invalid argument'
+ else:
+ cmd, arg = line, ''
+ # actually the only command able to accept options is MLST
+ assert (cmd.upper() == 'MLST'), 'Unsupported command "%s"' %cmd
+ except AssertionError, err:
+ self.respond('501 %s.' %err)
+ else:
+ facts = [x.lower() for x in arg.split(';')]
+ self._current_facts = [x for x in facts if x in self._available_facts]
+ f = ''.join([x + ';' for x in self._current_facts])
+ self.respond('200 MLST OPTS ' + f)
+
+ def ftp_NOOP(self, line):
+ """Do nothing."""
+ self.respond("200 I successfully done nothin'.")
+
+ def ftp_SYST(self, line):
+ """Return system type (always returns UNIX type: L8)."""
+ # This command is used to find out the type of operating system
+ # at the server. The reply shall have as its first word one of
+ # the system names listed in RFC-943.
+ # Since that we always return a "/bin/ls -lA"-like output on
+ # LIST we prefer to respond as if we would on Unix in any case.
+ self.respond("215 UNIX Type: L8")
+
+ def ftp_ALLO(self, line):
+ """Allocate bytes for storage (obsolete)."""
+ # obsolete (always respond with 202)
+ self.respond("202 No storage allocation necessary.")
+
+ def ftp_HELP(self, line):
+ """Return help text to the client."""
+ if line:
+ line = line.upper()
+ if line in proto_cmds:
+ self.respond("214 %s" %proto_cmds[line].help)
+ else:
+ self.respond("501 Unrecognized command.")
+ else:
+ # provide a compact list of recognized commands
+ def formatted_help():
+ cmds = []
+ keys = proto_cmds.keys()
+ keys.sort()
+ while keys:
+ elems = tuple((keys[0:8]))
+ cmds.append(' %-6s' * len(elems) %elems + '\r\n')
+ del keys[0:8]
+ return ''.join(cmds)
+
+ self.push("214-The following commands are recognized:\r\n")
+ self.push(formatted_help())
+ self.respond("214 Help command successful.")
+
+
+ # --- support for deprecated cmds
+
+ # RFC-1123 requires that the server treat XCUP, XCWD, XMKD, XPWD
+ # and XRMD commands as synonyms for CDUP, CWD, MKD, LIST and RMD.
+ # Such commands are obsoleted but some ftp clients (e.g. Windows
+ # ftp.exe) still use them.
+
+ def ftp_XCUP(self, line):
+ """Change to the parent directory. Synonym for CDUP. Deprecated."""
+ self.ftp_CDUP(line)
+
+ def ftp_XCWD(self, line):
+ """Change the current working directory. Synonym for CWD. Deprecated."""
+ self.ftp_CWD(line)
+
+ def ftp_XMKD(self, line):
+ """Create the specified directory. Synonym for MKD. Deprecated."""
+ self.ftp_MKD(line)
+
+ def ftp_XPWD(self, line):
+ """Return the current working directory. Synonym for PWD. Deprecated."""
+ self.ftp_PWD(line)
+
+ def ftp_XRMD(self, line):
+ """Remove the specified directory. Synonym for RMD. Deprecated."""
+ self.ftp_RMD(line)
+
+
+class FTPServer(asyncore.dispatcher):
+ """This class is an asyncore.disptacher subclass. It creates a FTP
+ socket listening on <address>, dispatching the requests to a <handler>
+ (typically FTPHandler class).
+
+ Depending on the type of address specified IPv4 or IPv6 connections
+ (or both, depending from the underlying system) will be accepted.
+
+ All relevant session information is stored in class attributes
+ described below.
+ Overriding them is strongly recommended to avoid running out of
+ file descriptors (DoS)!
+
+ - (int) max_cons:
+ number of maximum simultaneous connections accepted (defaults
+ to 0 == unlimited).
+
+ - (int) max_cons_per_ip:
+ number of maximum connections accepted for the same IP address
+ (defaults to 0 == unlimited).
+ """
+
+ max_cons = 0
+ max_cons_per_ip = 0
+
+ def __init__(self, address, handler):
+ """Initiate the FTP server opening listening on address.
+
+ - (tuple) address: the host:port pair on which the command
+ channel will listen.
+
+ - (classobj) handler: the handler class to use.
+ """
+ asyncore.dispatcher.__init__(self)
+ self.handler = handler
+ self.ip_map = []
+ host, port = address
+
+ # AF_INET or AF_INET6 socket
+ # Get the correct address family for our host (allows IPv6 addresses)
+ try:
+ info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
+ socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
+ except socket.gaierror:
+ # Probably a DNS issue. Assume IPv4.
+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.set_reuse_addr()
+ self.bind((host, port))
+ else:
+ for res in info:
+ af, socktype, proto, canonname, sa = res
+ try:
+ self.create_socket(af, socktype)
+ self.set_reuse_addr()
+ self.bind(sa)
+ except socket.error, msg:
+ if self.socket:
+ self.socket.close()
+ self.socket = None
+ continue
+ break
+ if not self.socket:
+ raise socket.error, msg
+ self.listen(5)
+
+ def set_reuse_addr(self):
+ # Overridden for convenience. Avoid to reuse address on Windows.
+ if (os.name in ('nt', 'ce')) or (sys.platform == 'cygwin'):
+ return
+ asyncore.dispatcher.set_reuse_addr(self)
+
+ def serve_forever(self, timeout=1, use_poll=False, map=None, count=None):
+ """A wrap around asyncore.loop(); starts the asyncore polling
+ loop including running the scheduler.
+ The arguments are the same expected by original asyncore.loop()
+ function.
+ """
+ if map is None:
+ map = asyncore.socket_map
+ # backward compatibility for python versions < 2.4
+ if not hasattr(self, '_map'):
+ self._map = self.handler._map = map
+
+ if use_poll and hasattr(asyncore.select, 'poll'):
+ poll_fun = asyncore.poll2
+ else:
+ poll_fun = asyncore.poll
+
+ if count is None:
+ log("Serving FTP on %s:%s" %self.socket.getsockname()[:2])
+ try:
+ while map or _tasks:
+ if map:
+ poll_fun(timeout, map)
+ if _tasks:
+ _scheduler()
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ log("Shutting down FTP server.")
+ self.close_all()
+ else:
+ while (map or _tasks) and count > 0:
+ if map:
+ poll_fun(timeout, map)
+ if _tasks:
+ _scheduler()
+ count = count - 1
+
+ def handle_accept(self):
+ """Called when remote client initiates a connection."""
+ sock_obj, addr = self.accept()
+ log("[]%s:%s Connected." %addr[:2])
+
+ handler = self.handler(sock_obj, self)
+ ip = addr[0]
+ self.ip_map.append(ip)
+
+ # For performance and security reasons we should always set a
+ # limit for the number of file descriptors that socket_map
+ # should contain. When we're running out of such limit we'll
+ # use the last available channel for sending a 421 response
+ # to the client before disconnecting it.
+ if self.max_cons:
+ if len(self._map) > self.max_cons:
+ handler.handle_max_cons()
+ return
+
+ # accept only a limited number of connections from the same
+ # source address.
+ if self.max_cons_per_ip:
+ if self.ip_map.count(ip) > self.max_cons_per_ip:
+ handler.handle_max_cons_per_ip()
+ return
+
+ handler.handle()
+
+ def writable(self):
+ return 0
+
+ def handle_error(self):
+ """Called to handle any uncaught exceptions."""
+ try:
+ raise
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ raise
+ logerror(traceback.format_exc())
+ self.close()
+
+ def close_all(self, map=None, ignore_all=False):
+ """Stop serving; close all existent connections disconnecting
+ clients.
+
+ - (dict) map:
+ A dictionary whose items are the channels to close.
+ If map is omitted, the default asyncore.socket_map is used.
+
+ - (bool) ignore_all:
+ having it set to False results in raising exception in case
+ of unexpected errors.
+
+ Implementation note:
+
+ Instead of using the current asyncore.close_all() function
+ which only close sockets, we iterate over all existent channels
+ calling close() method for each one of them, avoiding memory
+ leaks.
+
+ This is how asyncore.close_all() function should work in
+ Python 2.6.
+ """
+ if map is None:
+ map = self._map
+ for x in map.values():
+ try:
+ x.close()
+ except OSError, x:
+ if x[0] == errno.EBADF:
+ pass
+ elif not ignore_all:
+ raise
+ except (asyncore.ExitNow, KeyboardInterrupt, SystemExit):
+ raise
+ except:
+ if not ignore_all:
+ raise
+ map.clear()
+
+
+def test():
+ # cmd line usage (provide a read-only anonymous ftp server):
+ # python -m pyftpdlib.FTPServer
+ authorizer = DummyAuthorizer()
+ authorizer.add_anonymous(os.getcwd())
+ FTPHandler.authorizer = authorizer
+ address = ('', 21)
+ ftpd = FTPServer(address, FTPHandler)
+ ftpd.serve_forever()
+
+if __name__ == '__main__':
+ test()
diff --git a/third_party/pyftpdlib/demo/basic_ftpd.py b/third_party/pyftpdlib/demo/basic_ftpd.py
new file mode 100644
index 0000000..128eafc
--- /dev/null
+++ b/third_party/pyftpdlib/demo/basic_ftpd.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+# basic_ftpd.py
+
+"""A basic FTP server which uses a DummyAuthorizer for managing 'virtual
+users', setting a limit for incoming connections.
+"""
+
+import os
+
+from pyftpdlib import ftpserver
+
+
+if __name__ == "__main__":
+
+ # Instantiate a dummy authorizer for managing 'virtual' users
+ authorizer = ftpserver.DummyAuthorizer()
+
+ # Define a new user having full r/w permissions and a read-only
+ # anonymous user
+ authorizer.add_user('user', '12345', os.getcwd(), perm='elradfmw')
+ authorizer.add_anonymous(os.getcwd())
+
+ # Instantiate FTP handler class
+ ftp_handler = ftpserver.FTPHandler
+ ftp_handler.authorizer = authorizer
+
+ # Define a customized banner (string returned when client connects)
+ ftp_handler.banner = "pyftpdlib %s based ftpd ready." %ftpserver.__ver__
+
+ # Specify a masquerade address and the range of ports to use for
+ # passive connections. Decomment in case you're behind a NAT.
+ #ftp_handler.masquerade_address = '151.25.42.11'
+ #ftp_handler.passive_ports = range(60000, 65535)
+
+ # Instantiate FTP server class and listen to 0.0.0.0:21
+ address = ('', 21)
+ ftpd = ftpserver.FTPServer(address, ftp_handler)
+
+ # set a limit for connections
+ ftpd.max_cons = 256
+ ftpd.max_cons_per_ip = 5
+
+ # start ftp server
+ ftpd.serve_forever()
diff --git a/third_party/pyftpdlib/demo/md5_ftpd.py b/third_party/pyftpdlib/demo/md5_ftpd.py
new file mode 100644
index 0000000..ea51a58a
--- /dev/null
+++ b/third_party/pyftpdlib/demo/md5_ftpd.py
@@ -0,0 +1,29 @@
+#!/usr/bin/env python
+# md5_ftpd.py
+
+"""A basic ftpd storing passwords as hash digests (platform independent).
+"""
+
+import md5
+import os
+
+from pyftpdlib import ftpserver
+
+
+class DummyMD5Authorizer(ftpserver.DummyAuthorizer):
+
+ def validate_authentication(self, username, password):
+ hash = md5.new(password).hexdigest()
+ return self.user_table[username]['pwd'] == hash
+
+if __name__ == "__main__":
+ # get a hash digest from a clear-text password
+ hash = md5.new('12345').hexdigest()
+ authorizer = DummyMD5Authorizer()
+ authorizer.add_user('user', hash, os.getcwd(), perm='elradfmw')
+ authorizer.add_anonymous(os.getcwd())
+ ftp_handler = ftpserver.FTPHandler
+ ftp_handler.authorizer = authorizer
+ address = ('', 21)
+ ftpd = ftpserver.FTPServer(address, ftp_handler)
+ ftpd.serve_forever()
diff --git a/third_party/pyftpdlib/demo/throttled_ftpd.py b/third_party/pyftpdlib/demo/throttled_ftpd.py
new file mode 100644
index 0000000..dd3395c
--- /dev/null
+++ b/third_party/pyftpdlib/demo/throttled_ftpd.py
@@ -0,0 +1,89 @@
+#!/usr/bin/env python
+# throttled_ftpd.py
+
+"""ftpd supporting bandwidth throttling capabilities for data transfer.
+"""
+
+import os
+import time
+import asyncore
+
+from pyftpdlib import ftpserver
+
+
+class ThrottledDTPHandler(ftpserver.DTPHandler):
+ """A DTPHandler which wraps sending and receiving in a data counter
+ and temporarily sleeps the channel so that you burst to no more than
+ x Kb/sec average.
+ """
+
+ # maximum number of bytes to transmit in a second (0 == no limit)
+ read_limit = 0
+ write_limit = 0
+
+ def __init__(self, sock_obj, cmd_channel):
+ ftpserver.DTPHandler.__init__(self, sock_obj, cmd_channel)
+ self._timenext = 0
+ self._datacount = 0
+ self._sleeping = False
+ self._throttler = None
+
+ def readable(self):
+ return not self._sleeping and ftpserver.DTPHandler.readable(self)
+
+ def writable(self):
+ return not self._sleeping and ftpserver.DTPHandler.writable(self)
+
+ def recv(self, buffer_size):
+ chunk = asyncore.dispatcher.recv(self, buffer_size)
+ if self.read_limit:
+ self.throttle_bandwidth(len(chunk), self.read_limit)
+ return chunk
+
+ def send(self, data):
+ num_sent = asyncore.dispatcher.send(self, data)
+ if self.write_limit:
+ self.throttle_bandwidth(num_sent, self.write_limit)
+ return num_sent
+
+ def throttle_bandwidth(self, len_chunk, max_speed):
+ """A method which counts data transmitted so that you burst to
+ no more than x Kb/sec average.
+ """
+ self._datacount += len_chunk
+ if self._datacount >= max_speed:
+ self._datacount = 0
+ now = time.time()
+ sleepfor = self._timenext - now
+ if sleepfor > 0:
+ # we've passed bandwidth limits
+ def unsleep():
+ self._sleeping = False
+ self._sleeping = True
+ self._throttler = ftpserver.CallLater(sleepfor * 2, unsleep)
+ self._timenext = now + 1
+
+ def close(self):
+ if self._throttler is not None and not self._throttler.cancelled:
+ self._throttler.cancel()
+ ftpserver.DTPHandler.close(self)
+
+
+if __name__ == '__main__':
+ authorizer = ftpserver.DummyAuthorizer()
+ authorizer.add_user('user', '12345', os.getcwd(), perm='elradfmw')
+ authorizer.add_anonymous(os.getcwd())
+
+ # use the modified DTPHandler class and set a speed limit for both
+ # sending and receiving
+ dtp_handler = ThrottledDTPHandler
+ dtp_handler.read_limit = 30072 # 30 Kb/sec (30 * 1024)
+ dtp_handler.write_limit = 30072 # 30 Kb/sec (30 * 1024)
+
+ ftp_handler = ftpserver.FTPHandler
+ ftp_handler.authorizer = authorizer
+ # have the ftp handler use the different dtp handler
+ ftp_handler.dtp_handler = dtp_handler
+
+ ftpd = ftpserver.FTPServer(('', 21), ftp_handler)
+ ftpd.serve_forever()
diff --git a/third_party/pyftpdlib/demo/unix_ftpd.py b/third_party/pyftpdlib/demo/unix_ftpd.py
new file mode 100644
index 0000000..6367b366
--- /dev/null
+++ b/third_party/pyftpdlib/demo/unix_ftpd.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python
+# unix_ftpd.py
+
+"""A ftpd using local unix account database to authenticate users
+(users must already exist).
+
+It also provides a mechanism to (temporarily) impersonate the system
+users every time they are going to perform filesystem operations.
+"""
+
+import os
+import pwd, spwd, crypt
+
+from pyftpdlib import ftpserver
+
+
+class UnixAuthorizer(ftpserver.DummyAuthorizer):
+
+ # the uid/gid the daemon runs under
+ PROCESS_UID = os.getuid()
+ PROCESS_GID = os.getgid()
+
+ def add_user(self, username, homedir=None, **kwargs):
+ """Add a "real" system user to the virtual users table.
+
+ If no home argument is specified the user's home directory will
+ be used.
+
+ The keyword arguments in kwargs are the same expected by the
+ original add_user method: "perm", "msg_login" and "msg_quit".
+ """
+ # get the list of all available users on the system and check
+ # if provided username exists
+ users = [entry.pw_name for entry in pwd.getpwall()]
+ if not username in users:
+ raise ftpserver.AuthorizerError('No such user "%s".' %username)
+ if not homedir:
+ homedir = pwd.getpwnam(username).pw_dir
+ ftpserver.DummyAuthorizer.add_user(self, username, '', homedir,**kwargs)
+
+ def add_anonymous(self, homedir=None, realuser="nobody", **kwargs):
+ """Add an anonymous user to the virtual users table.
+
+ If no homedir argument is specified the realuser's home
+ directory will possibly be determined and used.
+
+ realuser argument specifies the system user to use for managing
+ anonymous sessions. On many UNIX systems "nobody" is tipically
+ used but it may change (e.g. "ftp").
+ """
+ users = [entry.pw_name for entry in pwd.getpwall()]
+ if not realuser in users:
+ raise ftpserver.AuthorizerError('No such user "%s".' %realuser)
+ if not homedir:
+ homedir = pwd.getpwnam(realuser).pw_dir
+ ftpserver.DummyAuthorizer.add_anonymous(self, homedir, **kwargs)
+ self.anon_user = realuser
+
+ def validate_authentication(self, username, password):
+ if (username == "anonymous") and self.has_user('anonymous'):
+ username = self.anon_user
+ pw1 = spwd.getspnam(username).sp_pwd
+ pw2 = crypt.crypt(password, pw1)
+ return pw1 == pw2
+
+ def impersonate_user(self, username, password):
+ if (username == "anonymous") and self.has_user('anonymous'):
+ username = self.anon_user
+ uid = pwd.getpwnam(username).pw_uid
+ gid = pwd.getpwnam(username).pw_gid
+ os.setegid(gid)
+ os.seteuid(uid)
+
+ def terminate_impersonation(self):
+ os.setegid(self.PROCESS_GID)
+ os.seteuid(self.PROCESS_UID)
+
+
+if __name__ == "__main__":
+ authorizer = UnixAuthorizer()
+ # add a user (note: user must already exists)
+ authorizer.add_user('user', perm='elradfmw')
+ authorizer.add_anonymous(os.getcwd())
+ ftp_handler = ftpserver.FTPHandler
+ ftp_handler.authorizer = authorizer
+ address = ('', 21)
+ ftpd = ftpserver.FTPServer(address, ftp_handler)
+ ftpd.serve_forever()
diff --git a/third_party/pyftpdlib/demo/winnt_ftpd.py b/third_party/pyftpdlib/demo/winnt_ftpd.py
new file mode 100644
index 0000000..f50b4aa
--- /dev/null
+++ b/third_party/pyftpdlib/demo/winnt_ftpd.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python
+# winnt_ftpd.py
+
+"""A ftpd using local Windows NT account database to authenticate users
+(users must already exist).
+
+It also provides a mechanism to (temporarily) impersonate the system
+users every time they are going to perform filesystem operations.
+"""
+
+import os
+import win32security, win32net, pywintypes, win32con
+
+from pyftpdlib import ftpserver
+
+
+def get_profile_dir(username):
+ """Return the user's profile directory."""
+ import _winreg, win32api
+ sid = win32security.ConvertSidToStringSid(
+ win32security.LookupAccountName(None, username)[0])
+ try:
+ key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
+ r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"+"\\"+sid)
+ except WindowsError:
+ raise ftpserver.AuthorizerError("No profile directory defined for %s "
+ "user" %username)
+ value = _winreg.QueryValueEx(key, "ProfileImagePath")[0]
+ return win32api.ExpandEnvironmentStrings(value)
+
+
+class WinNtAuthorizer(ftpserver.DummyAuthorizer):
+
+ def add_user(self, username, homedir=None, **kwargs):
+ """Add a "real" system user to the virtual users table.
+
+ If no homedir argument is specified the user's profile
+ directory will possibly be determined and used.
+
+ The keyword arguments in kwargs are the same expected by the
+ original add_user method: "perm", "msg_login" and "msg_quit".
+ """
+ # get the list of all available users on the system and check
+ # if provided username exists
+ users = [entry['name'] for entry in win32net.NetUserEnum(None, 0)[0]]
+ if not username in users:
+ raise ftpserver.AuthorizerError('No such user "%s".' %username)
+ if not homedir:
+ homedir = get_profile_dir(username)
+ ftpserver.DummyAuthorizer.add_user(self, username, '', homedir,
+ **kwargs)
+
+ def add_anonymous(self, homedir=None, realuser="Guest",
+ password="", **kwargs):
+ """Add an anonymous user to the virtual users table.
+
+ If no homedir argument is specified the realuser's profile
+ directory will possibly be determined and used.
+
+ realuser and password arguments are the credentials to use for
+ managing anonymous sessions.
+ The same behaviour is followed in IIS where the Guest account
+ is used to do so (note: it must be enabled first).
+ """
+ users = [entry['name'] for entry in win32net.NetUserEnum(None, 0)[0]]
+ if not realuser in users:
+ raise ftpserver.AuthorizerError('No such user "%s".' %realuser)
+ if not homedir:
+ homedir = get_profile_dir(realuser)
+ # make sure provided credentials are valid, otherwise an exception
+ # will be thrown; to do so we actually impersonate the user
+ self.impersonate_user(realuser, password)
+ self.terminate_impersonation()
+ ftpserver.DummyAuthorizer.add_anonymous(self, homedir, **kwargs)
+ self.anon_user = realuser
+ self.anon_pwd = password
+
+ def validate_authentication(self, username, password):
+ if (username == "anonymous") and self.has_user('anonymous'):
+ username = self.anon_user
+ password = self.anon_pwd
+ try:
+ win32security.LogonUser(username, None, password,
+ win32con.LOGON32_LOGON_INTERACTIVE,
+ win32con.LOGON32_PROVIDER_DEFAULT)
+ return True
+ except pywintypes.error:
+ return False
+
+ def impersonate_user(self, username, password):
+ if (username == "anonymous") and self.has_user('anonymous'):
+ username = self.anon_user
+ password = self.anon_pwd
+ handler = win32security.LogonUser(username, None, password,
+ win32con.LOGON32_LOGON_INTERACTIVE,
+ win32con.LOGON32_PROVIDER_DEFAULT)
+ win32security.ImpersonateLoggedOnUser(handler)
+ handler.Close()
+
+ def terminate_impersonation(self):
+ win32security.RevertToSelf()
+
+
+if __name__ == "__main__":
+ authorizer = WinNtAuthorizer()
+ # add a user (note: user must already exists)
+ authorizer.add_user('user', perm='elradfmw')
+ # add an anonymous user using Guest account to handle the anonymous
+ # sessions (note: Guest must be enabled first)
+ authorizer.add_anonymous(os.getcwd())
+ ftp_handler = ftpserver.FTPHandler
+ ftp_handler.authorizer = authorizer
+ address = ('', 21)
+ ftpd = ftpserver.FTPServer(address, ftp_handler)
+ ftpd.serve_forever()
diff --git a/third_party/pyftpdlib/doc/adoptions.lnk.html b/third_party/pyftpdlib/doc/adoptions.lnk.html
new file mode 100644
index 0000000..ba28912
--- /dev/null
+++ b/third_party/pyftpdlib/doc/adoptions.lnk.html
@@ -0,0 +1,12 @@
+<html>
+<head>
+ <meta http-equiv="refresh" content="3; http://code.google.com/p/pyftpdlib/wiki/Adoptions">
+ <title>Redirecting to Adoptions List...</title>
+</head>
+
+<body>
+<p>Redirecting to: <a href="http://code.google.com/p/pyftpdlib/wiki/Adoptions">http://code.google.com/p/pyftpdlib/wiki/Adoptions</a><br></p>
+<p>You'll be redirected in 3 seconds...</p>
+
+</body>
+</html> \ No newline at end of file
diff --git a/third_party/pyftpdlib/doc/faq.html b/third_party/pyftpdlib/doc/faq.html
new file mode 100644
index 0000000..891089c
--- /dev/null
+++ b/third_party/pyftpdlib/doc/faq.html
@@ -0,0 +1,98 @@
+<!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">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<title>pyftpdlib FAQs</title>
+</head>
+
+<body>
+<div id="wikicontent">
+ <h1><a name="1.0_-_Introduction" id="1.0_-_Introduction">1.0 - Introduction</a></h1>
+ <h3><a name="1.1_-_What_is_pyftpdlib?" id="1.1_-_What_is_pyftpdlib?">1.1 - What is pyftpdlib?</a></h3>
+ <p><a name="1.1_-_What_is_pyftpdlib?" id="1.1_-_What_is_pyftpdlib?">pyftpdlib is a high-level library to easily write asynchronous portable FTP servers with </a><a href="http://www.python.org/" rel="nofollow">Python</a>. </p>
+ <h3><a name="1.2_-_What_is_Python?" id="1.2_-_What_is_Python?">1.2 - What is Python?</a></h3>
+ <p><a name="1.2_-_What_is_Python?" id="1.2_-_What_is_Python?">Python is an interpreted, interactive, object-oriented, easy-to-learn programming language. It is often compared to <em>Tcl, Perl, Scheme</em> or <em>Java</em>. </a></p>
+ <h3><a name="1.3_-_I'm_not_a_python_programmer._Can_I_use_it_anyway?" id="1.3_-_I'm_not_a_python_programmer._Can_I_use_it_anyway?">1.3 - I'm not a python programmer. Can I use it anyway?</a></h3>
+ <p><a name="1.3_-_I'm_not_a_python_programmer._Can_I_use_it_anyway?" id="1.3_-_I'm_not_a_python_programmer._Can_I_use_it_anyway?">Yes. pyftpdlib is a fully working FTP server implementation that can be run &quot;as is&quot;. For example, (after having installed a </a><a href="http://www.python.org/download/" rel="nofollow">Python interpreter</a>) you could run an anonymous ftp server from cmd-line by running: </p>
+ <pre>python -m pyftpdlib.ftpserver</pre>
+ <p>Customizing ftpd for basic tasks like adding users or deciding where log file should be placed is mostly simply editing variables. This is basically like learning how to edit a common unix ftpd.conf file and doesn't really require Python knowledge. Customizing ftpd more deeply requires a python script which imports pyftpdlib to be written separately. An example about how this could be done are the scripts contained in the <a href="http://code.google.com/p/pyftpdlib/source/browse/trunk/demo" rel="nofollow">demo directory</a>. </p>
+ <h3><a name="1.4_-_Documentation" id="1.4_-_Documentation">1.4 - Documentation</a></h3>
+ <p><a href="http://code.google.com/p/pyftpdlib/" rel="nofollow">http://code.google.com/p/pyftpdlib/</a> is the primary source for all information about the project including <a href="http://code.google.com/p/pyftpdlib/wiki/Install" rel="nofollow">Install instructions</a>, <a href="http://code.google.com/p/pyftpdlib/wiki/Tutorial" rel="nofollow">Tutorial</a>, <a href="http://code.google.com/p/pyftpdlib/wiki/RFCsCompliance" rel="nofollow">RFCs Compliance paper</a>, <a href="http://code.google.com/p/pyftpdlib/w/list" rel="nofollow">Wikis</a> and the <a href="http://code.google.com/p/pyftpdlib/issues/list" rel="nofollow">Bug Tracker</a>. </p>
+ <h3><a name="1.5_-_Mailing_lists" id="1.5_-_Mailing_lists">1.5 - Mailing lists</a></h3>
+ <p><a name="1.5_-_Mailing_lists" id="1.5_-_Mailing_lists">There are a number of mailing lists for pyftpdlib: </a></p>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Name</strong> </td>
+ <td><strong>E-mail</strong> </td>
+ <td><strong>Web Interface</strong> </td>
+ <td><strong>Description</strong> </td>
+ </tr>
+ <tr>
+ <td><a href="http://groups.google.com/group/pyftpdlib" rel="nofollow">pyftpdlib</a> </td>
+ <td> pyftpdlib@googlegroups.com </td>
+ <td><a href="http://groups.google.com/group/pyftpdlib/topics" rel="nofollow">topics</a> </td>
+ <td> This is intended for end user support. </td>
+ </tr>
+ <tr>
+ <td><a href="http://groups.google.com/group/pyftpdlib-commit" rel="nofollow">pyftpdlib-commit</a> </td>
+ <td> pyftpdlib-commits@googlegroups.com </td>
+ <td><a href="http://groups.google.com/group/pyftpdlib-commit/topics" rel="nofollow">topics</a> </td>
+ <td> This list receives all change notifications for code in the Subversion repository. Unless you're a pyftpdlib developer you will probably not be interested in it. </td>
+ </tr>
+ <tr>
+ <td><a href="http://groups.google.com/group/pyftpdlib-issues" rel="nofollow">pyftpdlib-issues</a> </td>
+ <td> pyftpdlib-issues@googlegroups.com </td>
+ <td><a href="http://groups.google.com/group/pyftpdlib-issues/topics" rel="nofollow">topics</a> </td>
+ <td> This list receives all change notifications from the <a href="http://code.google.com/p/pyftpdlib/issues/list" rel="nofollow">Bug Tracker</a>. Unless you are involved into pyftpdlib development you will probably not find this useful. </td>
+ </tr>
+ </tbody>
+ </table>
+ <h1></h1>
+ <h3><a name="1.6_-_Bug_reporting" id="1.6_-_Bug_reporting">1.6 - Bug reporting</a></h3>
+ <p><a name="1.6_-_Bug_reporting" id="1.6_-_Bug_reporting">Bug reports should be made via Google Code </a><a href="http://code.google.com/p/pyftpdlib/issues/list" rel="nofollow">Issue Tracker</a>. Patches should be attached to the appropriate bug and not mailed directly to the mailing lists or any given team member. </p>
+ <h1><a name="2.0_-_Installing_and_compatibility" id="2.0_-_Installing_and_compatibility">2.0 - Installing and compatibility</a></h1>
+ <h3><a name="2.1_-_How_do_I_install_pyftpdlib?" id="2.1_-_How_do_I_install_pyftpdlib?">2.1 - How do I install pyftpdlib?</a></h3>
+ <p><a name="2.1_-_How_do_I_install_pyftpdlib?" id="2.1_-_How_do_I_install_pyftpdlib?">If you are not new to Python you probably don't need that, otherwise follow the </a><a href="http://code.google.com/p/pyftpdlib/wiki/Install" rel="nofollow">instructions</a>. </p>
+ <h3><a name="2.2_-_Which_Python_versions_are_compatible?" id="2.2_-_Which_Python_versions_are_compatible?">2.2 - Which Python versions are compatible?</a></h3>
+ <p><a href="http://www.python.org/download/releases/2.3.6/" rel="nofollow">Python 2.3</a> and higher. </p>
+ <h3><a name="2.3_-_Which_one_is_recommended?" id="2.3_-_Which_one_is_recommended?">2.3 - Which one is recommended?</a></h3>
+ <p><a name="2.3_-_Which_one_is_recommended?" id="2.3_-_Which_one_is_recommended?">Python <strong>2.4</strong> or higher because of the newer collection.deque object which provides better performances for file transfers. </a></p>
+ <h3><a name="2.4_-_What_about_Python_3.x?" id="2.4_-_What_about_Python_3.x?">2.4 - What about Python 3.x?</a></h3>
+ <p><a name="2.4_-_What_about_Python_3.x?" id="2.4_-_What_about_Python_3.x?">Python 3.0 is still in beta version thus not yet covered. A porting of pyftpdlib to Python 3k is in plan, anyway. </a></p>
+ <h3><a name="2.5_-_On_which_platforms_can_pyftpdlib_be_used?" id="2.5_-_On_which_platforms_can_pyftpdlib_be_used?">2.5 - On which platforms can pyftpdlib be used?</a></h3>
+ <p><a name="2.5_-_On_which_platforms_can_pyftpdlib_be_used?" id="2.5_-_On_which_platforms_can_pyftpdlib_be_used?">pyftpdlib should work on any platform where <strong><em>select()</em></strong> or <strong><em>poll()</em></strong> system calls are available and on any Python implementation which refers to <strong>CPython 2.3</strong> or superior (e.g CPython 2.6 or PythonCE 2.5). The development team has mainly tested it under various <strong>Linux</strong>, <strong>Windows</strong>, <strong>OS X</strong> and <strong>FreeBSD</strong> systems. For FreeBSD is also available a </a><a href="http://www.freshports.org/ftp/py-pyftpdlib/" rel="nofollow">pre-compiled package</a> maintained by Li-Wen Hsu &lt;lwhsu@freebsd.org&gt;. Other Python implementation like <strong><a href="http://pythonce.sourceforge.net/" rel="nofollow">PythonCE</a></strong> are known to work with pyftpdlib and every new version is usually tested against it. pyftpdlib currently does not work on <strong><a href="http://www.jython.org/" rel="nofollow">Jython</a></strong> since the latest Jython release refers to CPython 2.2.x serie. </p>
+ <h1><a name="3.0_-_Usage" id="3.0_-_Usage">3.0 - Usage</a></h1>
+ <h3><a name="3.1_-_Why_do_I_get_socket.error_'Permission_denied'_er" id="3.1_-_Why_do_I_get_socket.error_'Permission_denied'_er">3.1 - Why do I get socket.error &quot;Permission denied&quot; error on ftpd starting?</a></h3>
+ <p><a name="3.1_-_Why_do_I_get_socket.error_'Permission_denied'_er" id="3.1_-_Why_do_I_get_socket.error_'Permission_denied'_er">Probably because you're on a unix system and you're trying to start ftpd as an unprivileged user. <em>ftpserver.py</em> binds on port 21 by default and only super-user account (e.g. root) could bind sockets on such ports. If you want to bind ftpd as non-privileged user you should set a port higher than 1024. </a></p>
+ <h3><a name="3.2_-_How_can_I_prevent_the_server_version_from_being_displayed?" id="3.2_-_How_can_I_prevent_the_server_version_from_being_displayed?">3.2 - How can I prevent the server version from being displayed?</a></h3>
+ <p><a name="3.2_-_How_can_I_prevent_the_server_version_from_being_displayed?" id="3.2_-_How_can_I_prevent_the_server_version_from_being_displayed?">Just override and modify banner attribute of FTPHandler class. </a></p>
+ <h3><a name="3.3_-_Can_control_upload/download_ratios?" id="3.3_-_Can_control_upload/download_ratios?">3.3 - Can control upload/download ratios?</a></h3>
+ <p><a name="3.3_-_Can_control_upload/download_ratios?" id="3.3_-_Can_control_upload/download_ratios?">Yes. </a><a href="http://pyftpdlib.googlecode.com/svn/trunk/demo/throttled_ftpd.py" rel="nofollow">throttled_ftpd.py</a> script included in the demo directory implements bandwidth throttling capabilities for both upload and download. </p>
+ <h3><a name="3.4_-_Are_there_ways_to_limit_connections?" id="3.4_-_Are_there_ways_to_limit_connections?">3.4 - Are there ways to limit connections?</a></h3>
+ <p><a name="3.4_-_Are_there_ways_to_limit_connections?" id="3.4_-_Are_there_ways_to_limit_connections?">FTPServer class comes with two overridable attributes defaulting to zero (no limit): max_cons, which sets a limit for maximum simultaneous connection to handle by ftpd and max_cons_per_ip which set a limit for connections from the same IP address. Overriding these variables is always recommended to avoid DoS attacks. </a></p>
+ <h3><a name="3.5_-_I'm_behind_a_NAT_/_gateway" id="3.5_-_I'm_behind_a_NAT_/_gateway">3.5 - I'm behind a NAT / gateway</a></h3>
+ <p><a name="3.5_-_I'm_behind_a_NAT_/_gateway" id="3.5_-_I'm_behind_a_NAT_/_gateway">When behind a NAT a ftp server needs to replace the IP local address displayed in PASV replies and instead use the public address of the NAT to allow client to connect. By overriding masquerade_address attribute of FTPHandler class you will force pyftpdlib to do such replacement. However, one big problem still exists. The passive FTP connections will use ports from 1024 and up, which means that you must forward all ports 1024-65535 from the NAT to the FTP server! And you have to allow many (possibly) dangerous ports in your firewalling rules! To resolve this, simply override passive_ports attribute of FTPHandler class to control what ports proftpd will use for its passive data transfers. Value expected by passive_ports attribute is a list of integers (e.g. range(60000, 65535)) indicating which ports will be used for initializing the passive data channel. </a></p>
+ <h3><a name="3.6.1_-_What_is_FXP?" id="3.6.1_-_What_is_FXP?">3.6.1 - What is FXP?</a></h3>
+ <p><a name="3.6.1_-_What_is_FXP?" id="3.6.1_-_What_is_FXP?">FXP is part of the name of a popular Windows FTP client: </a><a href="http://www.flashfxp.com" rel="nofollow">http://www.flashfxp.com</a>. This client has made the name &quot;FXP&quot; commonly used as a synonym for site-to-site FTP transfers, for transferring a file between two remote FTP servers without the transfer going through the client's host. Sometimes &quot;FXP&quot; is referred to as a protocol; in fact, it is not. The site-to-site transfer capability was deliberately designed into <a href="http://www.faqs.org/rfcs/rfc959.html" rel="nofollow">RFC-959</a>. More info can be found here: <a href="http://www.proftpd.org/docs/howto/FXP.html" rel="nofollow">http://www.proftpd.org/docs/howto/FXP.html</a>. </p>
+ <h3><a name="3.6.2_-_Does_pyftpdlib_support_FXP?" id="3.6.2_-_Does_pyftpdlib_support_FXP?">3.6.2 - Does pyftpdlib support FXP?</a></h3>
+ <p><a name="3.6.2_-_Does_pyftpdlib_support_FXP?" id="3.6.2_-_Does_pyftpdlib_support_FXP?">Yes. It is disabled by default for security reasons (see </a><a href="http://gim.org.pl/rfcs/rfc2577.html" rel="nofollow">RFC-2257</a> and <a href="http://www.cert.org/advisories/CA-1997-27.html" rel="nofollow">FTP bounce attack description</a>) but in case you want to enable it just set to True the permit_foreign_addresses attribute of FTPHandler class. </p>
+ <h1><a name="4.0_-_Implementation" id="4.0_-_Implementation">4.0 - Implementation</a></h1>
+ <h3><a name="4.1_-_Globbing_/_STAT_command_implementation" id="4.1_-_Globbing_/_STAT_command_implementation">4.1 - Globbing / STAT command implementation</a></h3>
+ <p><a name="4.1_-_Globbing_/_STAT_command_implementation" id="4.1_-_Globbing_/_STAT_command_implementation">Globbing is a common Unix shell mechanism for expanding wildcard patterns to match multiple filenames. When an argument is provided to the <strong>STAT</strong> command, ftpd should return directory listing over the command channel. </a><a href="http://www.faqs.org/rfcs/rfc959.html" rel="nofollow">RFC-959</a> does not explicitly mention globbing; this means that FTP servers are not required to support globbing in order to be compliant. However, many FTP servers do support globbing as a measure of convenience for FTP clients and users. In order to search for and match the given globbing expression, the code has to search (possibly) many directories, examine each contained filename, and build a list of matching files in memory. Since this operation can be quite intensive, both CPU- and memory-wise, pyftpdlib does not support globbing. </p>
+ <h3><a name="4.2_-_ASCII_transfers_/_SIZE_command_implementation" id="4.2_-_ASCII_transfers_/_SIZE_command_implementation">4.2 - ASCII transfers / SIZE command implementation</a></h3>
+ <p><a name="4.2_-_ASCII_transfers_/_SIZE_command_implementation" id="4.2_-_ASCII_transfers_/_SIZE_command_implementation">Properly handling the SIZE command when TYPE ASCII is used would require to scan the entire file to perform the ASCII translation logic (file.read().replace(os.linesep, '\r\n')) and then calculating the len of such data which may be different than the actual size of the file on the server. Considering that calculating such result could be very resource-intensive it could be easy for a malicious client to try a DoS attack, thus pyftpdlib do not perform the ASCII translation. However, clients in general should not be resuming downloads in ASCII mode. Resuming downloads in binary mode is the recommended way as specified in </a><a href="http://www.faqs.org/rfcs/rfc3659.html" rel="nofollow">RFC-3659</a>. </p>
+ <h3><a name="4.3.1_-_IPv6_support" id="4.3.1_-_IPv6_support">4.3.1 - IPv6 support</a></h3>
+ <p><a name="4.3.1_-_IPv6_support" id="4.3.1_-_IPv6_support">Starting from version 0.4.0 pyftpdlib <em>supports</em> IPv6 (</a><a href="http://www.faqs.org/rfcs/rfc2428.html" rel="nofollow">RFC-2428</a>). If you use IPv6 and want your FTP daemon to do so just pass a valid IPv6 address to the FTPServer class constructor. Example: </p>
+ <pre>&gt;&gt;&gt; from pyftpdlib import ftpserver<br />&gt;&gt;&gt; address = (&quot;::1&quot;, 21)  # listen on localhost, port 21<br />&gt;&gt;&gt; ftpd = ftpserver.FTPServer(address, ftpserver.FTPHandler)<br />&gt;&gt;&gt; ftpd.serve_forever()<br />Serving FTP on ::1:21</pre>
+ <h3><a name="4.3.2_-_How_do_I_install_IPv6_support_on_my_system?" id="4.3.2_-_How_do_I_install_IPv6_support_on_my_system?">4.3.2 - How do I install IPv6 support on my system?</a></h3>
+ <p><a name="4.3.2_-_How_do_I_install_IPv6_support_on_my_system?" id="4.3.2_-_How_do_I_install_IPv6_support_on_my_system?">If you want to install IPv6 support on Linux run &quot;modprobe ipv6&quot;, then &quot;ifconfig&quot;. This should display the loopback adapter, with the address &quot;::1&quot;. You should then be able to listen the server on that address, and connect to it. </a></p>
+ <p><a name="4.3.2_-_How_do_I_install_IPv6_support_on_my_system?" id="4.3.2_-_How_do_I_install_IPv6_support_on_my_system?">On Windows (XP SP2 and higher) run &quot;netsh int ipv6 install&quot;. Again, you should be able to use IPv6 loopback afterwards. </a></p>
+ <h3><a name="4.4_-_Can_pyftpdlib_be_integrated_with_'real'_users_ex" id="4.4_-_Can_pyftpdlib_be_integrated_with_'real'_users_ex">4.4 - Can pyftpdlib be integrated with &quot;real&quot; users existing on the system?</a></h3>
+ <p><a name="4.4_-_Can_pyftpdlib_be_integrated_with_'real'_users_ex" id="4.4_-_Can_pyftpdlib_be_integrated_with_'real'_users_ex">Yes. By using the proper system dependent authorizer pyftpdlib can look into the system account database to authenticate users. Starting from version 0.4.0 the DummyAuthorizer class provides two new methods: impersonate_user() and terminate_impersonation(). System dependent authorizers subclassing the dummy authorizer can assume the id of real users by overriding them as necessary. Every time the FTP server is going to access the filesystem (e.g. for creating or renaming a file) it will temporarily impersonate the currently logged on user, execute the filesystem call and then switch back to the user who originally started the server. Example UNIX and Windows FTP servers contained in the </a><a href="http://code.google.com/p/pyftpdlib/source/browse/#svn/trunk/demo" rel="nofollow">demo directory</a> implement both real user impersonation and authentication against the system users database. </p>
+ <h3><a name="4.5_-_SSL/TLS_support" id="4.5_-_SSL/TLS_support">4.5 - SSL/TLS support</a></h3>
+ <p><a name="4.5_-_SSL/TLS_support" id="4.5_-_SSL/TLS_support">SSL/TLS support including <em>AUTH, ADAT, PROT, PBSZ, CCC, MIC, CONF</em> and <em>ENC</em> commands is a feature defined in </a><a href="http://www.faqs.org/rfcs/rfc2228.html" rel="nofollow">RFC-2228</a>. There is no official support for SSL/TLS within the current code tree. The new Python 2.6 release finally grants full SSL support so we hope we'll be able to implement the feature. Contributors willing to to provide a patch are greatly appreciated. </p>
+ <p>&nbsp;</p>
+</div>
+</body>
+</html>
diff --git a/third_party/pyftpdlib/doc/index.html b/third_party/pyftpdlib/doc/index.html
new file mode 100644
index 0000000..210a20e
--- /dev/null
+++ b/third_party/pyftpdlib/doc/index.html
@@ -0,0 +1,158 @@
+<!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">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<title>pyftpdlib Home Page</title>
+</head>
+
+<body>
+<div id="wikicontent">
+ <div id="wikicontent2">
+ <div id="wikicontent3">
+ <h1><a id="Python_FTP_server_library_(pyftpdlib)">Python FTP server library (pyftpdlib)</a></h1>
+ <h2><a id="About">About</a></h2>
+ <p><a id="About">Python FTP server library provides a high-level portable interface to easily write asynchronous FTP servers with Python. Based on <strong>asyncore</strong> framework pyftpdlib is currently the most complete </a><a href="http://www.faqs.org/rfcs/rfc959.html" rel="nofollow">RFC-959</a> FTP server implementation available for <a href="http://www.python.org/" rel="nofollow">Python</a> programming language. </p>
+ <h2><a id="Features">Features</a></h2>
+ <ul>
+ <li><a id="Features">High portability: </a></li>
+ <ul>
+ <li><a id="Features">Entirely written in pure Python, no third party modules are used. It just should work on any system where <em>select( )</em> or <em>poll( )</em> are available. </a></li>
+ <li><a id="Features">Extremely flexible system of &quot;authorizers&quot; able to manage both &quot;virtual&quot; and &quot;real&quot; users on different platforms (<strong>Windows NT</strong>, <strong>UNIX</strong>, <strong>OSx</strong>). </a></li>
+ </ul>
+ <li><a id="Features">High performance: multiplexing I/O with various client connections within a single process / thread. </a></li>
+ <li><a id="Features">Compact: the entire library is distributed in a single file <em>(ftpserver.py).</em> </a></li>
+ <li><a id="Features">Support for recent FTP commands like <strong>MLSD</strong> and <strong>MLST</strong> defined in </a><a href="http://www.faqs.org/rfcs/rfc959.html" rel="nofollow">RFC-3659</a>. </li>
+ <li>Support for <strong><a href="http://www.proftpd.org/docs/howto/FXP.html" rel="nofollow">FXP</a></strong>, site-to-site transfers. </li>
+ <li>Support for <strong>IPv6</strong> (<a href="ftp://ftp.rfc-editor.org/in-notes/rfc2428.txt" rel="nofollow">RFC-2428</a>). </li>
+ <li>NAT/Firewall support with PASV (passive) mode connections. </li>
+ <li>Support for resumed transfers. </li>
+ <li>Per-user permissions configurability. </li>
+ <li>Maximum connections limit. </li>
+ <li>Per-source-IP limits. </li>
+ <li> Configurable idle timeouts for both control and data channels.</li>
+ </ul>
+ <h2><a id="Quick_start">Quick start</a></h2>
+ <pre><a id="Quick_start"> &gt;&gt;&gt; from pyftpdlib import ftpserver
+ &gt;&gt;&gt; authorizer = ftpserver.DummyAuthorizer()
+ &gt;&gt;&gt; authorizer.add_user(&quot;user&quot;, &quot;12345&quot;, &quot;/home/user&quot;, perm=&quot;elradfmw&quot;)
+ &gt;&gt;&gt; authorizer.add_anonymous(&quot;/home/nobody&quot;)
+ &gt;&gt;&gt; ftp_handler = ftpserver.FTPHandler
+ &gt;&gt;&gt; ftp_handler.authorizer = authorizer
+ &gt;&gt;&gt; address = (&quot;127.0.0.1&quot;, 21)
+ &gt;&gt;&gt; ftpd = ftpserver.FTPServer(address, ftp_handler)
+ &gt;&gt;&gt; ftpd.serve_forever()
+ Serving FTP on 127.0.0.1:21
+ []127.0.0.1:2503 connected.
+ 127.0.0.1:2503 ==&gt; 220 Ready.
+ 127.0.0.1:2503 &lt;== USER anonymous
+ 127.0.0.1:2503 ==&gt; 331 Username ok, send password.
+ 127.0.0.1:2503 &lt;== PASS ******
+ 127.0.0.1:2503 ==&gt; 230 Login successful.
+ [anonymous]@127.0.0.1:2503 User anonymous logged in.
+ 127.0.0.1:2503 &lt;== TYPE A
+ 127.0.0.1:2503 ==&gt; 200 Type set to: ASCII.
+ 127.0.0.1:2503 &lt;== PASV 127.0.0.1:2503 ==&gt;
+ 227 Entering passive mode (127,0,0,1,9,201).
+ 127.0.0.1:2503 &lt;== LIST
+ 127.0.0.1:2503 ==&gt; 150 File status okay. About to open data connection.
+ [anonymous]@127.0.0.1:2503 OK LIST &quot;/&quot;. Transfer starting.
+ 127.0.0.1:2503 ==&gt; 226 Transfer complete.
+ [anonymous]@127.0.0.1:2503 Transfer complete. 706 bytes transmitted.
+ 127.0.0.1:2503 &lt;== QUIT
+ 127.0.0.1:2503 ==&gt; 221 Goodbye. [anonymous]@127.0.0.1:2503 Disconnected.</a></pre>
+ <h2><a id="Documentation_and_related_links">Documentation and related links</a></h2>
+ <p><a id="Documentation_and_related_links">Primary documentation and related links include the following: </a></p>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Type</strong> </td>
+ <td><strong>Description</strong> </td>
+ </tr>
+ <tr>
+ <td><a href="http://code.google.com/p/pyftpdlib/wiki/Tutorial" rel="nofollow">Tutorial</a> </td>
+ <td> Tutorial containing API reference and example usages. </td>
+ </tr>
+ <tr>
+ <td><a href="http://code.google.com/p/pyftpdlib/wiki/FAQ" rel="nofollow">FAQ</a> </td>
+ <td> Frequently Asked Questions about pyftpdlib. </td>
+ </tr>
+ <tr>
+ <td><a href="http://code.google.com/p/pyftpdlib/wiki/Install" rel="nofollow">Install</a> </td>
+ <td> Instructions for installing pyftpdlib (for those really new to Python). </td>
+ </tr>
+ <tr>
+ <td><a href="http://code.google.com/p/pyftpdlib/wiki/RFCsCompliance" rel="nofollow">RFCs Compliance</a> </td>
+ <td> A paper showing pyftpdlib compliance against FTP protocol standard RFCs. </td>
+ </tr>
+ <tr>
+ <td><a href="http://code.google.com/p/pyftpdlib/wiki/ReleaseNotes05" rel="nofollow">Release Notes</a> </td>
+ <td> Release notes of the current pyftpdlib release. </td>
+ </tr>
+ <tr>
+ <td><a href="http://code.google.com/p/pyftpdlib/wiki/Roadmap" rel="nofollow">Roadmap</a> </td>
+ <td> A &quot;roadmap&quot; describing current and future project's changes. </td>
+ </tr>
+ <tr>
+ <td><a href="http://code.google.com/p/pyftpdlib/wiki/Adoptions" rel="nofollow">Adoptions List</a> </td>
+ <td> A list of softwares and systems using pyftpdlib. </td>
+ </tr>
+ <tr>
+ <td><a href="http://www.freshports.org/ftp/py-pyftpdlib/" rel="nofollow">FreeBSD port</a> </td>
+ <td> Porting of pyftpdlib on FreeBSD system (note: it is a separate project maintained by a different team). </td>
+ </tr>
+ </tbody>
+ </table>
+ <h2><a id="Timeline">Timeline</a></h2>
+ <ul>
+ <li><a name="Timeline" id="Timeline2">09-20-2008: version 0.5.0 released. </a></li>
+ <li><a name="Timeline" id="Timeline2">08-10-2008: pyftpdlib included in </a><a href="http://trac.manent-backup.com/" rel="nofollow">Manent</a></li>
+ <li><a>05-16-2008: version 0.4.0 released. </a></li>
+ <li><a id="Timeline">04-09-2008: pyftpdlib used as backend for </a><a href="http://arkadiusz-wahlig.blogspot.com/2008/04/hosting-files-on-google.html" rel="nofollow">gpftpd</a>, an FTP server for managing files hosted on <a href="http://pages.google.com" rel="nofollow">Google Pages</a>. </li>
+ <li>01-17-2008: version 0.3.0 released. </li>
+ <li>10-14-2007: pyftpdlib included in <a href="http://walco.n--tree.net/projects/aksy/wiki" rel="nofollow">Aksy</a>. </li>
+ <li>09-17-2007: version 0.2.0 released. </li>
+ <li>09-08-2007: pyftpdlib included as <a href="http://farmanager.com/" rel="nofollow">FarManager</a> <a href="http://enforum.farmanager.com/viewtopic.php?t=640" rel="nofollow">plug-in</a>. </li>
+ <li>03-06-2007: pyftpdlib <a href="http://www.freshports.org/ftp/py-pyftpdlib/" rel="nofollow">ported on FreeBSD</a> systems to make users can easily install on it. </li>
+ <li>03-07-2007: version 0.1.1 released. </li>
+ <li>02-26-2007: version 0.1.0 released. </li>
+ </ul>
+ <h2><a id="Contribute">Contribute</a></h2>
+ <p><a id="Contribute">If you want to help or just give us suggestions about the project and other related things, subscribe to the </a><a href="http://groups.google.com/group/pyftpdlib" rel="nofollow">discussion mailing list</a>. If you want to talk with project team members about pyftpdlib and other related things, feel free to contact us at the following addresses: </p>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Name</strong> </td>
+ <td><strong>Country</strong> </td>
+ <td><strong>E-mail</strong> </td>
+ <td><strong>Description</strong> </td>
+ </tr>
+ <tr>
+ <td> Giampaolo Rodola' </td>
+ <td> Italy </td>
+ <td> g.rodola at gmail dot com </td>
+ <td> Original pyftpdlib author and main maintainer. </td>
+ </tr>
+ <tr>
+ <td> Jay Loden </td>
+ <td> New Jersey (USA) </td>
+ <td> jloden at gmail dot com </td>
+ <td> OS X and Linux platform development/testing. </td>
+ </tr>
+ <tr>
+ <td> Li-Wen Hsu </td>
+ <td> Taiwan </td>
+ <td> lwhsu at freebsd dot org </td>
+ <td><a href="http://www.freshports.org/ftp/py-pyftpdlib/" rel="nofollow">FreeBSD port</a> maintainer. </td>
+ </tr>
+ </tbody>
+ </table>
+ <p>Feedbacks and suggestions are greatly appreciated as well as new testers and coders willing to join the development. </p>
+ <p>For any bug report, patch proposal or feature request, add an entry into the <a href="http://code.google.com/p/pyftpdlib/issues/list" rel="nofollow">Issue Tracker</a>. </p>
+ <p>In case you're using pyftpdlib into a software or website of yours, please update the pyftpdlib <a href="http://code.google.com/p/pyftpdlib/wiki/Adoptions" rel="nofollow">Adoptions List</a> by adding a comment in the Wiki. </p>
+ <p>Thank you. </p>
+ </div>
+ <p>&nbsp;</p>
+ </div>
+</div>
+</body>
+</html>
diff --git a/third_party/pyftpdlib/doc/install.html b/third_party/pyftpdlib/doc/install.html
new file mode 100644
index 0000000..50142d3
--- /dev/null
+++ b/third_party/pyftpdlib/doc/install.html
@@ -0,0 +1,34 @@
+<!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">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<title>pyftpdlib Install instructions</title>
+</head>
+
+<body>
+<div id="wikicontent">
+ <h1><a id="Requirements">Requirements</a></h1>
+ <p><a id="Requirements">Python 2.3 or higher (not Python 3.x). You can get the latest 2.x stable Python release from here: </a><a href="http://www.python.org/download/" rel="nofollow">http://www.python.org/download/</a>. </p>
+ <h1><a id="Manual_installation">Manual installation</a></h1>
+ <p><a id="Manual_installation">If you have downloaded a pyftpdlib package, follow the following steps: </a></p>
+ <p><a id="Manual_installation">Unpack it (Windows users could use 7Zip, WinRar or other similar program): </a></p>
+ <pre> <a id="Manual_installation">tar zxf pyftpdlib-0.3.0.tar.gz</a></pre>
+ <p><a id="Manual_installation">Change to the pyftpdlib directory: </a></p>
+ <pre> <a id="Manual_installation">cd pyftpdlib</a></pre>
+ <p><a id="Manual_installation">Run setup.py to install pyftpdlib. This step need to be run as root. </a></p>
+ <pre> <a id="Manual_installation">python setup.py install</a></pre>
+ <p><a id="Manual_installation">If you're on Windows just run: </a></p>
+ <pre> <a id="Manual_installation">setup.py install</a></pre>
+ <h1><a id="Using_easy_install">Using easy_instal</a><a>l</a></h1>
+ <p><a id="Using_easy_install">If you have </a><a href="http://peak.telecommunity.com/DevCenter/EasyInstall" rel="nofollow">easy_install</a> on your system, installing pyftpdlib is quite simple. Just run: </p>
+ <pre> python easy_install.py pyftpdlib<a href="index.html">index</a></pre>
+ <p>This will get the most updated pyftpdlib from the Python <a href="http://pypi.python.org/pypi" rel="nofollow">pypi repository</a>, unpack it and install it automatically. </p>
+ <p>Note: if you already have an old version of pyftpdlib installed, easy_install will not automatically download the latest version. You can ask for a particular version by running, for example: </p>
+ <pre> python easy_install.py pyftpdlib==0.3.0
+
+
+
+</pre>
+</div>
+</body>
+</html>
diff --git a/third_party/pyftpdlib/doc/release-notes.html b/third_party/pyftpdlib/doc/release-notes.html
new file mode 100644
index 0000000..b160b42
--- /dev/null
+++ b/third_party/pyftpdlib/doc/release-notes.html
@@ -0,0 +1,47 @@
+<!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">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<title>pyftpdlib Release Notes</title>
+</head>
+
+<body>
+<div id="wikicontent">
+ <h1><a name="Version:_0.5.0_-_Date:_2008-09-20" id="Version:_0.5.0_-_Date:_2008-09-20">Version: 0.5.0 - Date: 2008-09-20</a></h1>
+ <h2><a name="Major_enhancements" id="Major_enhancements">Major enhancements</a></h2>
+ <ul>
+ <li><a title="Implement idle-timeouts" href="http://code.google.com/p/pyftpdlib/issues/detail?id=72">Issue #72</a>: pyftpdlib now provides configurable idle timeouts to disconnect client after a long time of inactivity. </li>
+ <li><a title="pyftpdlib should impose a delay before replying for invalid credentials" href="http://code.google.com/p/pyftpdlib/issues/detail?id=73">Issue #73</a>: impose a delay before replying for invalid credentials to minimize the risk of brute force password guessing. </li>
+ <li><a title="Implement permissions overriding" href="http://code.google.com/p/pyftpdlib/issues/detail?id=74">Issue #74</a>: it is now possible to define permission exceptions for certain directories (e.g. creating a user which does not have write permission except for one sub-directory in FTP root). </li>
+ <li>Improved bandwidth throttling capabilities of <a href="http://code.google.com/p/pyftpdlib/source/browse/tags/release-0.5.0/demo/throttled_ftpd.py" rel="nofollow">demo/throttled_ftpd.py</a> script by having used the new CallLater class which drastically reduces the number of calls to time.time(). </li>
+ </ul>
+ <h2><a name="Bugfixes" id="Bugfixes">Bugfixes</a></h2>
+ <ul>
+ <li><a title="Some unit tests failing on dual core machines" href="http://code.google.com/p/pyftpdlib/issues/detail?id=62">Issue #62</a>: some unit tests were failing on dual core machines. </li>
+ <li><a title="Socket handles are leaked when a data transfer is in progress and user QUITs" href="http://code.google.com/p/pyftpdlib/issues/detail?id=71">Issue #71</a>: socket handles are leaked when a data transfer is in progress and user QUITs. </li>
+ <li><a title="Orphaned file is left behind in case STOU fails for insufficient user permissions" href="http://code.google.com/p/pyftpdlib/issues/detail?id=75">Issue #75</a>: orphaned file was left behind in case STOU failed for insufficient user permissions. </li>
+ <li><a title="Incorrect OOB data management on FreeBSD" href="http://code.google.com/p/pyftpdlib/issues/detail?id=77">Issue #77</a>: incorrect OOB data management on FreeBSD. </li>
+ </ul>
+ <h2><a name="API_changes_since_0.4.0" id="API_changes_since_0.4.0">API changes since 0.4.0</a></h2>
+ <ul>
+ <li><a name="API_changes_since_0.4.0" id="API_changes_since_0.4.0">FTPHandler, DTPHandler, PassiveDTP and ActiveDTP classes gained a new timeout class attribute. </a></li>
+ <li><a name="API_changes_since_0.4.0" id="API_changes_since_0.4.0">DummyAuthorizer class gained a new override_perm method. </a></li>
+ <li><a name="API_changes_since_0.4.0" id="API_changes_since_0.4.0">A new class called CallLater has been added. </a></li>
+ <li><a name="API_changes_since_0.4.0" id="API_changes_since_0.4.0">AbstractedFS.get_stat_dir method has been removed. </a></li>
+ </ul>
+ <h2><a name="Migration_notes" id="Migration_notes">Migration notes</a></h2>
+ <p><a name="Migration_notes" id="Migration_notes">Changes applied to the 0.5.0 trunk should be fully compatible with the previous 0.4.0 version. Your existing 0.4.0 based code will most likely work without need to be modified. The new features in this release are detailed below. </a></p>
+ <h3><a name="Idle_timeouts_and_new_class" id="Idle_timeouts_and_new_class">Idle timeouts and new CallLater</a> class</h3>
+ <p>The previous version suffered the problem of not having a mechanism to disconnect clients after a long time of inactivity. This posed the risk for the FTP server to be easily vulnerable to DoS attacks in which a lot of connected clients could clump system's resources and sockets. </p>
+ <p>0.5.0 version solved this problem by implementing a brand new polling loop which, other than serving the connected clients, also checks if it is the proper time for scheduled functions to be called (if any). Thanks to the new loop and the new CallLater class implementing <a href="http://code.google.com/p/pyftpdlib/issues/detail?id=72" rel="nofollow">timeouts</a> and <a href="http://code.google.com/p/pyftpdlib/issues/detail?id=73" rel="nofollow">delays to invalid credential replies</a> have been possible. </p>
+ <p>FTPHandler class gained a new timeout attribute defaulting to 300 seconds which is the maximum time of inactivity a remote client may spend before being disconnected. </p>
+ <p>Also DTPHandler class gained a new timeout attribute defaulting to 300 seconds which roughly is the maximum time the data transfers can stall for with no progress. </p>
+ <h3><a name="Permission_exceptions" id="Permission_exceptions">Permission exceptions</a></h3>
+ <p><a name="Permission_exceptions" id="Permission_exceptions">The DummyAuthorizer now gives the possibility to define permission exceptions for directories. For example, if you want to create a user which does not have write permission except for one sub-directory in FTP root, you can now do as follows: </a></p>
+ <pre><a name="Permission_exceptions" id="Permission_exceptions">&gt;&gt;&gt; from pyftpdlib import ftpserver<br />&gt;&gt;&gt; authorizer = ftpserver.DummyAuthorizer()<br />&gt;&gt;&gt; authorizer.add_user('user', 'password', '/home/ftp', perm='elr')<br />&gt;&gt;&gt; authorizer.override_perm('user', '/home/ftp/pub', 'elradfmw', recursive=True)</a>
+
+
+</pre>
+</div>
+</body>
+</html>
diff --git a/third_party/pyftpdlib/doc/rfcs-compliance.html b/third_party/pyftpdlib/doc/rfcs-compliance.html
new file mode 100644
index 0000000..56ba794
--- /dev/null
+++ b/third_party/pyftpdlib/doc/rfcs-compliance.html
@@ -0,0 +1,720 @@
+<!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">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<title>pyftpdlib RFCs compliance</title>
+</head>
+
+<body>
+<div id="wikicontent">
+ <h1><a id="Introduction">Introduction</a></h1>
+ <p><a id="Introduction2">This page lists current standard Internet RFCs that define the FTP protocol. </a></p>
+ <p><a id="Introduction2">pyftpdlib conforms to the FTP protocol standard as defined in </a><a href="http://www.ietf.org/rfc/rfc959.txt" rel="nofollow">RFC-959</a> and <a href="http://www.ietf.org/rfc/rfc1123.txt" rel="nofollow">RFC-1123</a> implementing all the fundamental commands and features described in them. It also implements some more recent features such as OPTS and FEAT commands defined in <a href="http://www.ietf.org/rfc/rfc2389.txt" rel="nofollow">RFC-2398</a>, IPv6 support as defined in <a href="ftp://ftp.rfc-editor.org/in-notes/rfc2428.txt" rel="nofollow">RFC-2428</a> and all the new commands defined in <a href="http://www.ietf.org/rfc/rfc3659.txt" rel="nofollow">RFC-3659</a>. </p>
+ <p>Future plans for pyftpdlib include the gradual implementation of other standards track RFCs. </p>
+ <p>Some of the features like ACCT, SMNT or OPTS commands will never be implemented deliberately. Other features described in more recent RFCs like the TLS/SSL support for securing FTP are taken in great consideration and should be implemented in future (Python 2.6 should grant a full SSL support). </p>
+ <h1><a href="http://www.ietf.org/rfc/rfc959.txt" rel="nofollow">RFC-959</a></h1>
+ <p>The base specification of the current File Transfer Protocol. </p>
+ <ul>
+ <li>Issued: October 1985 </li>
+ <li>Status: STANDARD </li>
+ <li>Obsoletes: <a href="http://www.ietf.org/rfc/rfc765.txt" rel="nofollow">RFC-765</a> </li>
+ <li>Updated by: <a href="http://www.ietf.org/rfc/rfc1123.txt" rel="nofollow">RFC-1123</a>, <a href="http://www.ietf.org/rfc/rfc2228.txt" rel="nofollow">RFC-2228</a>, <a href="http://www.ietf.org/rfc/rfc2640.txt" rel="nofollow">RFC-2640</a>, <a href="http://www.ietf.org/rfc/rfc2773.txt" rel="nofollow">RFC-2773</a> </li>
+ </ul>
+ <h2><a id="Commands">Commands</a></h2>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Command</strong> </td>
+ <td><strong>Requirement</strong> </td>
+ <td><strong>Implemented</strong> </td>
+ <td><strong>Milestone</strong> </td>
+ <td><strong>Description</strong> </td>
+ <td><strong>Notes</strong> </td>
+ </tr>
+ <tr>
+ <td> ABOR </td>
+ <td> MAY </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Abort data transfer. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> ACCT </td>
+ <td> MAY </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Specify account information. </td>
+ <td> It will never be implemented (useless). </td>
+ </tr>
+ <tr>
+ <td> ALLO </td>
+ <td> MAY </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Ask for server to allocate enough storage space. </td>
+ <td> Treated as a NOOP (no operation). </td>
+ </tr>
+ <tr>
+ <td> APPE </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Append data to an existing file. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> CDUP </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Go to parent directory. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> CWD </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Change current working directory. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> DELE </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Delete file. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> HELP </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Show help. </td>
+ <td> Accept also arguments. </td>
+ </tr>
+ <tr>
+ <td> LIST </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> List files. </td>
+ <td> Accept also bad arguments like &quot;-ls&quot;, &quot;-la&quot;, ... </td>
+ </tr>
+ <tr>
+ <td> MKD </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Create directory. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> MODE </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Set data transfer mode. </td>
+ <td>&quot;STREAM&quot; mode is supported, &quot;Block&quot; and &quot;Compressed&quot; aren't. </td>
+ </tr>
+ <tr>
+ <td> NLST </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> List files in a compact form. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> NOOP </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> NOOP (no operation), just do nothing. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> PASS </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Set user password. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> PASV </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Set server in passive connection mode. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> PORT </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Set server in active connection mode. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> PWD </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Get current working directory. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> QUIT </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Quit session. </td>
+ <td> If file transfer is in progress, the connection will remain open until it is finished. </td>
+ </tr>
+ <tr>
+ <td> REIN </td>
+ <td> MAY </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Reinitialize user's current session. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> REST </td>
+ <td> MAY </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Restart file position. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> RETR </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Retrieve a file (client's download). </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> RMD </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Remove directory. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> RNFR </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> File renaming (source) </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> RNTO </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> File renaming (destination) </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> SITE </td>
+ <td> MAY </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Site specific server services. </td>
+ <td> Will never be implemented (if needed it's up to administrator.) </td>
+ </tr>
+ <tr>
+ <td> SMNT </td>
+ <td> MAY </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Mount file-system structure. </td>
+ <td> Will never be implemented (too much system-dependent and almost never used). </td>
+ </tr>
+ <tr>
+ <td> STAT </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Server's status information / File LIST </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> STOR </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Store a file (client's upload). </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> STOU </td>
+ <td> MAY </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Store a file with a unique name. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> STRU </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Set file structure (obsolete). </td>
+ <td> Accept only 'F' (file) type structure by doing a NOOP (no operation). Other structure types (record and page) are obsoleted, system-dependent and thus not implemented. </td>
+ </tr>
+ <tr>
+ <td> SYST </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Get system type. </td>
+ <td> Always return &quot;UNIX Type: L8&quot; because of the LIST output provided. </td>
+ </tr>
+ <tr>
+ <td> TYPE </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Set current type (Binary/ASCII). </td>
+ <td> Accept only Binary and ASII TYPEs. Other TYPEs such as EBCDIC are obsoleted, system-dependent and thus not implemented. </td>
+ </tr>
+ <tr>
+ <td> USER </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Set user. </td>
+ <td> A new USER command could be entered at any point in order to change the access control flushing any user, password, and account information already supplied and beginning the login sequence again. </td>
+ </tr>
+ </tbody>
+ </table>
+ <h1></h1>
+ <h1><a href="http://www.ietf.org/rfc/rfc1123.txt" rel="nofollow">RFC-1123</a></h1>
+ <p>Extends and clarifies some aspects of <a href="http://www.ietf.org/rfc/rfc959.txt" rel="nofollow">RFC-959</a>. Introduces new response codes 554 and 555. </p>
+ <ul>
+ <li>Issued: October 1989 </li>
+ <li>Status: STANDARD </li>
+ </ul>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Feature</strong> </td>
+ <td><strong>Requirement</strong> </td>
+ <td><strong>Implemented</strong> </td>
+ <td><strong>Milestone</strong> </td>
+ <td><strong>Description</strong> </td>
+ <td><strong>Notes</strong> </td>
+ </tr>
+ <tr>
+ <td> TYPE L 8 as synonym of TYPE I </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.2.0 </td>
+ <td> TYPE L 8 command should be treated as synonym of TYPE I (&quot;IMAGE&quot; or binary type). </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> PASV is per-transfer </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> PASV must be used for a unique transfer. </td>
+ <td> If PASV is issued twice data-channel is restarted. </td>
+ </tr>
+ <tr>
+ <td> Implied type for LIST and NLST </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> The data returned by a LIST or NLST command SHOULD use an implied TYPE AN. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> STOU format output </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.2.0 </td>
+ <td> Defined the exact format output which STOU response must respect (&quot;125/150 FILE &lt;filename&gt;&quot;). </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> Avoid 250 response type on STOU </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.2.0 </td>
+ <td> The 250 positive response indicated in <a href="http://www.ietf.org/rfc/rfc959.txt" rel="nofollow">RFC-959</a> has been declared incorrect in <a href="http://www.ietf.org/rfc/rfc1123.txt" rel="nofollow">RFC-1123</a> which requires 125/150 instead. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> Handle &quot;Experimental&quot; directory cmds </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> The server should support XCUP, XCWD, XMKD, XPWD and XRMD obsoleted commands and treat them as synonyms for CDUP, CWD, MKD, LIST and RMD commands. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> Idle timeout </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.5.0</td>
+ <td> A Server-FTP process SHOULD have a configurable idle timeout of 5 minutes, which will terminate the process and close the control connection if the server is inactive (i.e., no command or data transfer in progress) for a long period of time. </td>
+ <td>&nbsp;</td>
+ </tr>
+ <tr>
+ <td> Concurrency of data and control </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Server-FTP should be able to process STAT or ABOR while a data transfer is in progress </td>
+ <td> Feature granted natively for ALL commands since we're in an asynchronous environment. </td>
+ </tr>
+ <tr>
+ <td> 554 response on wrong REST </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.2.0 </td>
+ <td> Return a 554 reply may for a command that follows a REST command. The reply indicates that the existing file at the Server-FTP cannot be repositioned as specified in the REST. </td>
+ <td></td>
+ </tr>
+ </tbody>
+ </table>
+ <h1></h1>
+ <h1><a href="http://www.ietf.org/rfc/rfc2228.txt" rel="nofollow">RFC-2228</a></h1>
+ <p>Specifies several security extensions to the base FTP protocol defined in <a href="http://www.ietf.org/rfc/rfc959.txt" rel="nofollow">RFC-959</a>. New commands: AUTH, ADAT, PROT, PBSZ, CCC, MIC, CONF, and ENC. New response codes: 232, 234, 235, 334, 335, 336, 431, 533, 534, 535, 536, 537, 631, 632, and 633. </p>
+ <ul>
+ <li>Issued: October 1997 </li>
+ <li>Status: PROPOSED STANDARD </li>
+ <li>Updates: <a href="http://www.ietf.org/rfc/rfc959.txt" rel="nofollow">RFC-959</a> </li>
+ </ul>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Command</strong> </td>
+ <td><strong>Requirement</strong> </td>
+ <td><strong>Implemented</strong> </td>
+ <td><strong>Milestone</strong> </td>
+ <td><strong>Description</strong> </td>
+ <td><strong>Notes</strong> </td>
+ </tr>
+ <tr>
+ <td> AUTH </td>
+ <td> SHOULD </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Authentication/Security Mechanism. </td>
+ <td> Waiting for Python 2.6 which should grant full SSL support. </td>
+ </tr>
+ <tr>
+ <td> CCC </td>
+ <td> SHOULD </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Clear Command Channel. </td>
+ <td> Waiting for Python 2.6 which should grant full SSL support. </td>
+ </tr>
+ <tr>
+ <td> CONF </td>
+ <td> SHOULD </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Confidentiality Protected Command. </td>
+ <td> Waiting for Python 2.6 which should grant full SSL support. </td>
+ </tr>
+ <tr>
+ <td> EENC </td>
+ <td> SHOULD </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Privacy Protected Command. </td>
+ <td> Waiting for Python 2.6 which should grant full SSL support. </td>
+ </tr>
+ <tr>
+ <td> MIC </td>
+ <td> SHOULD </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Integrity Protected Command. </td>
+ <td> Waiting for Python 2.6 which should grant full SSL support. </td>
+ </tr>
+ <tr>
+ <td> PBSZ </td>
+ <td> SHOULD </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Protection Buffer Size. </td>
+ <td> Waiting for Python 2.6 which should grant full SSL support. </td>
+ </tr>
+ <tr>
+ <td> PROT </td>
+ <td> SHOULD </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Data Channel Protection Level. </td>
+ <td> Waiting for Python 2.6 which should grant full SSL support. </td>
+ </tr>
+ </tbody>
+ </table>
+ <h1></h1>
+ <h1><a href="http://www.ietf.org/rfc/rfc2389.txt" rel="nofollow">RFC-2389</a></h1>
+ <p>Introduces the new FEAT and OPTS commands. </p>
+ <ul>
+ <li>Issued: August 1998 </li>
+ <li>Status: PROPOSED STANDARD </li>
+ </ul>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Command</strong> </td>
+ <td><strong>Requirement</strong> </td>
+ <td><strong>Implemented</strong> </td>
+ <td><strong>Milestone</strong> </td>
+ <td><strong>Description</strong> </td>
+ <td><strong>Notes</strong> </td>
+ </tr>
+ <tr>
+ <td> FEAT </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.3.0 </td>
+ <td> List new supported commands subsequent <a href="http://www.ietf.org/rfc/rfc959.txt" rel="nofollow">RFC-959</a> </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> OPTS </td>
+ <td> MAY </td>
+ <td> YES </td>
+ <td> 0.3.0 </td>
+ <td> Set options for certain commands. </td>
+ <td> MLST is the only command which could be used with OPTS. </td>
+ </tr>
+ </tbody>
+ </table>
+ <h1></h1>
+ <h1><a href="http://www.ietf.org/rfc/rfc2428.txt" rel="nofollow">RFC-2428</a></h1>
+ <p>Introduces the new commands EPRT and EPSV extending FTP to enable its use over various network protocols, and the new response codes 522 and 229. </p>
+ <ul>
+ <li>Issued: September 1998 </li>
+ <li>Status: PROPOSED STANDARD </li>
+ </ul>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Command</strong> </td>
+ <td><strong>Requirement</strong> </td>
+ <td><strong>Implemented</strong> </td>
+ <td><strong>Milestone</strong> </td>
+ <td><strong>Description</strong> </td>
+ <td><strong>Notes</strong> </td>
+ </tr>
+ <tr>
+ <td> EPRT </td>
+ <td> MAY </td>
+ <td> YES</td>
+ <td> 0.4.0</td>
+ <td> Set active data connection over IPv4 or IPv6 </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> EPSV </td>
+ <td> MAY </td>
+ <td> YES</td>
+ <td> 0.4.0 </td>
+ <td> Set passive data connection over IPv4 or IPv6 </td>
+ <td></td>
+ </tr>
+ </tbody>
+ </table>
+ <h1></h1>
+ <h1><a href="http://www.ietf.org/rfc/rfc2577.txt" rel="nofollow">RFC-2577</a></h1>
+ <p>Provides several configuration and implementation suggestions to mitigate some security concerns, including limiting failed password attempts and third-party &quot;proxy FTP&quot; transfers, which can be used in &quot;bounce attacks&quot;. </p>
+ <ul>
+ <li>Issued: May 1999 </li>
+ <li>Status: INFORMATIONAL </li>
+ </ul>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Feature</strong> </td>
+ <td><strong>Requirement</strong> </td>
+ <td><strong>Implemented</strong> </td>
+ <td><strong>Milestone</strong> </td>
+ <td><strong>Description</strong> </td>
+ <td><strong>Notes</strong> </td>
+ </tr>
+ <tr>
+ <td> FTP bounce protection </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.2.0 </td>
+ <td> Reject PORT if IP address specified in it does not match client IP address. Drop the incoming (PASV) data connection for the same reason. </td>
+ <td> Configurable. </td>
+ </tr>
+ <tr>
+ <td> Restrict PASV/PORT to non privileged ports </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.2.0 </td>
+ <td> Reject connections to privileged ports. </td>
+ <td> Configurable. </td>
+ </tr>
+ <tr>
+ <td> Brute force protection (1) </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Disconnect client after a certain number (3 or 5) of wrong authentications. </td>
+ <td> Configurable. </td>
+ </tr>
+ <tr>
+ <td> Brute force protection (2) </td>
+ <td> SHOULD </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Impose a 5 second delay before replying to an invalid &quot;PASS&quot; command to diminish the efficiency of a brute force attack. </td>
+ <td> Feature not implemented because asyncore does not provide such functionality natively. A switch to Twisted framework would solve this. </td>
+ </tr>
+ <tr>
+ <td> Per-source-IP limit </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.2.0 </td>
+ <td> Limit the total number of per-ip control connections to avoid parallel brute-force attack attempts. </td>
+ <td> Configurable. </td>
+ </tr>
+ <tr>
+ <td> Do not reject wrong usernames </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Always return 331 to the USER command to prevent client from determining valid usernames on the server. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> Port stealing protection </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.1.1 </td>
+ <td> Use random-assigned local ports for data connections. </td>
+ <td></td>
+ </tr>
+ </tbody>
+ </table>
+ <h1></h1>
+ <h1><a href="http://www.ietf.org/rfc/rfc2640.txt" rel="nofollow">RFC-2640</a></h1>
+ <p>Extends the FTP protocol to support multiple character sets, in addition to the original 7-bit ASCII. Introduces the new LANG command. </p>
+ <ul>
+ <li>Issued: July 1999 </li>
+ <li>Status: PROPOSED STANDARD </li>
+ <li>Updates: <a href="http://www.ietf.org/rfc/rfc959.txt" rel="nofollow">RFC-959</a> </li>
+ </ul>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Feature</strong> </td>
+ <td><strong>Requirement</strong> </td>
+ <td><strong>Implemented</strong> </td>
+ <td><strong>Milestone</strong> </td>
+ <td><strong>Description</strong> </td>
+ <td><strong>Notes</strong> </td>
+ </tr>
+ <tr>
+ <td> LANG command </td>
+ <td> MAY </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> Set current response's language. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> Support for UNICODE </td>
+ <td> SHOULD </td>
+ <td> NO </td>
+ <td> --- </td>
+ <td> For support of global compatibility it is rencommended that clients and servers use UTF-8 encoding when exchanging pathnames. </td>
+ <td></td>
+ </tr>
+ </tbody>
+ </table>
+ <h1></h1>
+ <h1><a href="http://www.ietf.org/rfc/rfc3659.txt" rel="nofollow">RFC-3659</a></h1>
+ <p>Four new commands are added: &quot;SIZE&quot;, &quot;MDTM&quot;, &quot;MLST&quot;, and &quot;MLSD&quot;. The existing command &quot;REST&quot; is modified. </p>
+ <ul>
+ <li>Issued: March 2007 </li>
+ <li>Status: PROPOSED STANDARD </li>
+ <li>Updates: <a href="http://www.ietf.org/rfc/rfc959.txt" rel="nofollow">RFC-959</a> </li>
+ </ul>
+ <table border="1">
+ <tbody>
+ <tr>
+ <td><strong>Feature</strong> </td>
+ <td><strong>Requirement</strong> </td>
+ <td><strong>Implemented</strong> </td>
+ <td><strong>Milestone</strong> </td>
+ <td><strong>Description</strong> </td>
+ <td><strong>Notes</strong> </td>
+ </tr>
+ <tr>
+ <td> MDTM command </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Get file's last modification time </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> MLSD command </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.3.0 </td>
+ <td> Get directory list in a standardized form. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> MLST command </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.3.0 </td>
+ <td> Get file information in a standardized form. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> SIZE command </td>
+ <td> MUST </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Get file size. </td>
+ <td> In case of ASCII TYPE it does not perform the ASCII conversion to avoid DoS conditions (see FAQs for more details). </td>
+ </tr>
+ <tr>
+ <td> TVSF mechanism </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.1.0 </td>
+ <td> Provide a file system naming conventions modeled loosely upon those of the unix file system supporting relative and absolute path names. </td>
+ <td></td>
+ </tr>
+ <tr>
+ <td> Minimum required set of MLST facts </td>
+ <td> SHOULD </td>
+ <td> YES </td>
+ <td> 0.3.0 </td>
+ <td> If conceivably possible, support at least the type, perm, size, unique, and modify MLSX command facts. </td>
+ <td></td>
+ </tr>
+ </tbody>
+ </table>
+ <p>&nbsp;</p>
+ <p>&nbsp;</p>
+</div>
+</body>
+</html>
diff --git a/third_party/pyftpdlib/doc/roadmap.lnk.html b/third_party/pyftpdlib/doc/roadmap.lnk.html
new file mode 100644
index 0000000..28ebee9
--- /dev/null
+++ b/third_party/pyftpdlib/doc/roadmap.lnk.html
@@ -0,0 +1,12 @@
+<html>
+<head>
+ <meta http-equiv="refresh" content="3; http://code.google.com/p/pyftpdlib/wiki/Roadmap">
+ <title>Redirecting to Roadmap...</title>
+</head>
+
+<body>
+<p>Redirecting to: <a href="http://code.google.com/p/pyftpdlib/wiki/Roadmap">http://code.google.com/p/pyftpdlib/wiki/Roadmap</a><br></p>
+<p>You'll be redirected in 3 seconds...</p>
+
+</body>
+</html>
diff --git a/third_party/pyftpdlib/doc/tutorial.html b/third_party/pyftpdlib/doc/tutorial.html
new file mode 100644
index 0000000..9842bd4
--- /dev/null
+++ b/third_party/pyftpdlib/doc/tutorial.html
@@ -0,0 +1,329 @@
+<!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">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<title>pyftpdlib Tutorial</title>
+</head>
+
+<body>
+<div id="wikicontent">
+ <h1><a name="1.0_-_Introduction" id="1.0_-_Introduction">1.0 - Introduction</a></h1>
+ <p><a name="1.0_-_Introduction" id="1.0_-_Introduction">pyftpdlib implements the server side of the FTP protocol as defined in </a><a href="http://www.faqs.org/rfcs/rfc959.html" rel="nofollow">RFC-959</a>. pyftpdlib consist of a single file, <strong>ftpserver.py</strong>, which contains a hierarchy of classes, functions and variables which implement the backend functionality for the ftpd. This document is intended to serve as a simple <strong>API reference</strong> of most important classes and functions. Also included is an introduction to <strong>customization</strong> through the use of some example scripts. </p>
+ <p>If you have written a customized configuration you think could be useful to the community feel free to share it by adding a comment at the end of this document. </p>
+ <h1><a name="2.0_-_API_reference" id="2.0_-_API_reference">2.0 - API reference</a></h1>
+ <p><a name="2.0_-_API_reference" id="2.0_-_API_reference">function ftpserver.<strong>log(</strong><em>msg</em><strong>)</strong> </a></p>
+ <blockquote><a name="2.0_-_API_reference" id="2.0_-_API_reference">Log messages intended for the end user. </a></blockquote>
+ <hr />
+ <a name="2.0_-_API_reference" id="2.0_-_API_reference">function ftpserver.<strong>logline(</strong><em>msg</em><strong>)</strong> </a>
+ <blockquote><a name="2.0_-_API_reference" id="2.0_-_API_reference">Log commands and responses passing through the command channel. </a></blockquote>
+ <hr />
+ <a name="2.0_-_API_reference" id="2.0_-_API_reference">function ftpserver.<strong>logerror(</strong><em>msg</em><strong>)</strong> </a>
+ <blockquote><a name="2.0_-_API_reference" id="2.0_-_API_reference">Log traceback outputs occurring in case of errors. </a></blockquote>
+ <hr />
+ <a name="2.0_-_API_reference" id="2.0_-_API_reference">class ftpserver.<strong>AuthorizerError</strong></a><strong><a href="http://code.google.com/p/pyftpdlib/w/edit/AuthorizerError">?</a>()</strong>
+ <blockquote>Base class for authorizers exceptions. </blockquote>
+ <hr />
+ class ftpserver.<strong>DummyAuthorizer<a href="http://code.google.com/p/pyftpdlib/w/edit/DummyAuthorizer">?</a>()</strong>
+ <blockquote>Basic &quot;dummy&quot; authorizer class, suitable for subclassing to create your own custom authorizers. An &quot;authorizer&quot; is a class handling authentications and permissions of the FTP server. It is used inside FTPHandler class for verifying user's password, getting users home directory, checking user permissions when a filesystem read/write event occurs and changing user before accessing the filesystem. DummyAuthorizer is the base authorizer, providing a platform independent interface for managing &quot;virtual&quot; FTP users. Typically the first thing you have to do is create an instance of this class and start adding ftp users: </blockquote>
+ <pre>&gt;&gt;&gt; from pyftpdlib import ftpserver<br />&gt;&gt;&gt; authorizer = ftpserver.DummyAuthorizer()<br />&gt;&gt;&gt; authorizer.add_user('user', 'password', '/home/user', perm='elradfmw')<br />&gt;&gt;&gt; authorizer.add_anonymous('/home/nobody')</pre>
+ <ul>
+ <li><strong>add_user(</strong><em>username</em>, <em>password</em>, <em>homedir</em><strong>[</strong>, <em>perm=&quot;elr&quot;</em><strong>[</strong>, <em>msg_login=&quot;Login successful.&quot;</em><strong>[</strong>, <em>msg_quit=&quot;Goodbye.&quot;</em><strong>]</strong><strong>]</strong><strong>])</strong> </li>
+ <ul>
+ <li>Add a user to the virtual users table. AuthorizerError exceptions raised on error conditions such as insufficient permissions or duplicate usernames. Optional perm argument is a set of letters referencing the user's permissions (see the permission table shown below). Optional msg_login and msg_quit arguments can be specified to provide customized response strings when user log-in and quit. The perm argument of the add_user() method refers to user's permissions. Every letter is used to indicate that the access rights the current FTP user has over the following specific actions are granted. </li>
+ </ul>
+ </ul>
+ <blockquote>Read permissions:
+ <ul>
+ <li><strong>&quot;e&quot;</strong> = change directory (CWD command) </li>
+ <li><strong>&quot;l&quot;</strong> = list files (LIST, NLST, MLSD commands) </li>
+ <li><strong>&quot;r&quot;</strong> = retrieve file from the server (RETR command) </li>
+ </ul>
+ Write permissions
+ <ul>
+ <li><strong>&quot;a&quot;</strong> = append data to an existing file (APPE command) </li>
+ <li><strong>&quot;d&quot;</strong> = delete file or directory (DELE, RMD commands) </li>
+ <li><strong>&quot;f&quot;</strong> = rename file or directory (RNFR, RNTO commands) </li>
+ <li><strong>&quot;m&quot;</strong> = create directory (MKD command) </li>
+ <li><strong>&quot;w&quot;</strong> = store a file to the server (STOR, STOU commands) </li>
+ </ul>
+ </blockquote>
+ <ul>
+ <li><strong>add_anonymous(</strong><em>homedir</em><strong>[</strong>, **<em>kwargs</em><strong>])</strong> </li>
+ <ul>
+ <li>Add an anonymous user to the virtual users table. AuthorizerError exception raised on error conditions such as insufficient permissions, missing home directory, or duplicate anonymous users. The keyword arguments in kwargs are the same expected by add_user() method: perm, msg_login and msg_quit. The optional <em>perm</em> keyword argument is a string defaulting to &quot;elr&quot; referencing &quot;read-only&quot; anonymous user's permission. Using a &quot;write&quot; value results in a RuntimeWarning. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>override_perm(</strong><em>directory</em>, <em>perm</em><strong>[</strong>, <em>recursive=False</em><strong>])</strong> </li>
+ <ul>
+ <li>Override permissions for a given directory. <em><strong>New in 0.5.0</strong></em> </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>validate_authentication(</strong><em>username</em>, <em>password</em><strong>)</strong> </li>
+ <ul>
+ <li>Return True if the supplied username and password match the stored credentials. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>impersonate_user(</strong><em>username</em>, <em>password</em><strong>)</strong> </li>
+ <ul>
+ <li>Impersonate another user (noop). It is always called before accessing the filesystem. By default it does nothing. The subclass overriding this method is expected to provide a mechanism to change the current user. <em><strong>New in 0.4.0</strong></em> </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>terminate_impersonation(</strong><em>username</em>, <em>password</em><strong>)</strong> </li>
+ <ul>
+ <li>Terminate impersonation (noop). It is always called after having accessed the filesystem. By default it does nothing. The subclass overriding this method is expected to provide a mechanism to switch back to the original user. <em><strong>New in 0.4.0</strong></em> </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>remove_user(</strong><em>username</em><strong>)</strong> </li>
+ <ul>
+ <li>Remove a user from the virtual user table. </li>
+ </ul>
+ </ul>
+ <hr />
+ <p>class ftpserver.<strong>FTPHandler(</strong><em>conn, server</em><strong>)</strong> </p>
+ <blockquote>This class implements the FTP server Protocol Interpreter (see <a href="http://www.faqs.org/rfcs/rfc959.html" rel="nofollow">RFC-959</a>), handling commands received from the client on the control channel by calling the command's corresponding method (e.g. for received command &quot;MKD pathname&quot;, ftp_MKD() method is called with pathname as the argument). All relevant session information are stored in instance variables. </blockquote>
+ <blockquote>conn is the underlying socket object instance of the newly established connection, server is the FTPServer class instance. Basic usage simply requires creating an instance of FTPHandler class and specify which authorizer instance it will going to use: </blockquote>
+ <pre>&gt;&gt;&gt; ftp_handler = ftpserver.FTPHandler<br />&gt;&gt;&gt; ftp_handler.authorizer = authorizer</pre>
+ <blockquote>All relevant session information is stored in class attributes reproduced below and can be modified before instantiating this class: </blockquote>
+ <ul>
+ <li><strong>timeout</strong> </li>
+ <ul>
+ <li>The timeout which is the maximum time a remote client may spend between FTP commands. If the timeout triggers, the remote client will be kicked off (defaults to 300 seconds). <em><strong>New in 5.0</strong></em> </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>banner</strong> </li>
+ <ul>
+ <li>String sent when client connects (default &quot;pyftpdlib %s ready.&quot; %__ver__). </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>max_login_attempts</strong> </li>
+ <ul>
+ <li>Maximum number of wrong authentications before disconnecting (default 3). </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>permit_foreign_addresses</strong> </li>
+ <ul>
+ <li>Wether enable <a href="http://www.proftpd.org/docs/howto/FXP.html" rel="nofollow">FXP</a> feature (default False). </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>permit_privileged_ports</strong> </li>
+ <ul>
+ <li>Set to True if you want to permit active connections (PORT) over privileged ports (not recommended, default False). </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>masquerade_address</strong> </li>
+ <ul>
+ <li>The &quot;masqueraded&quot; IP address to provide along PASV reply when pyftpdlib is running behind a NAT or other types of gateways. When configured pyftpdlib will hide its local address and instead use the public address of your NAT (default None). </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>passive_ports</strong> </li>
+ <ul>
+ <li>What ports ftpd will use for its passive data transfers. Value expected is a list of integers (e.g. range(60000, 65535)). When configured pyftpdlib will no longer use kernel-assigned random ports (default None). </li>
+ </ul>
+ </ul>
+ <hr />
+ <p>class ftpserver.<strong>DTPHandler(</strong><em>sock_obj, cmd_channel</em><strong>)</strong> </p>
+ <blockquote>This class handles the server-data-transfer-process (server-DTP, see <a href="http://www.faqs.org/rfcs/rfc959.html" rel="nofollow">RFC-959</a>) managing all transfer operations regarding the data channel. </blockquote>
+ <blockquote>sock_obj is the underlying socket object instance of the newly established connection, cmd_channel is the FTPHandler class instance. Unless you want to add extra functionalities like bandwidth throttling you shouldn't be interested in putting hands on this class. </blockquote>
+ <ul>
+ <li><strong>timeout</strong> </li>
+ <ul>
+ <li>The timeout which roughly is the maximum time we permit data transfers to stall for with no progress. If the timeout triggers, the remote client will be kicked off. <em><strong>New in 5.0</strong></em> </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>cmd_channel</strong> </li>
+ <ul>
+ <li>The command channel class instance. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>file_obj</strong> </li>
+ <ul>
+ <li>The file transferred (if any). </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>receive</strong> </li>
+ <ul>
+ <li>True if channel is used for receiving data. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>transfer_finished</strong> </li>
+ <ul>
+ <li>True if transfer completed successfully. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>get_transmitted_bytes()</strong> </li>
+ <ul>
+ <li>Return the number of transmitted bytes. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>transfer_in_progress()</strong> </li>
+ <ul>
+ <li>Return True if a transfer is in progress. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>enable_receiving(</strong><em>type</em><strong>)</strong> </li>
+ <ul>
+ <li>Enable receiving of data over the channel. Depending on the type currently in use it creates an appropriate wrapper for the incoming data. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>push(</strong><em>data</em><strong>)</strong> </li>
+ <ul>
+ <li>Push a bufferable <em>data</em> object (e.g. a string) onto the deque and initiate send. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>push_with_producer(</strong><em>producer</em><strong>)</strong> </li>
+ <ul>
+ <li>Push data using a producer and initiate send. </li>
+ </ul>
+ </ul>
+ <hr />
+ <p>class ftpserver.<strong>FTPServer(</strong><em>address, handler</em><strong>)</strong> </p>
+ <blockquote>This class is an asyncore.dispatcher subclass. It creates a FTP socket listening on address (a tuple containing the ip:port pair), dispatching the requests to a &quot;handler&quot; (typically FTPHandler class object). It is typically used for starting asyncore polling loop: </blockquote>
+ <pre>&gt;&gt;&gt; address = ('127.0.0.1', 21)<br />&gt;&gt;&gt; ftpd = ftpserver.FTPServer(address, ftp_handler)<br />&gt;&gt;&gt; ftpd.serve_forever()</pre>
+ <ul>
+ <li><strong>max_cons</strong> </li>
+ <ul>
+ <li>Number of maximum simultaneous connections accepted (default 0 == <em>no limit</em>). </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>max_cons_per_ip</strong> </li>
+ <ul>
+ <li>Number of maximum connections accepted for the same IP address (default 0 == <em>no limit</em>). </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>serve_forever([</strong><em>timeout=1</em><strong>[</strong>, <em>use_poll=False</em><strong>[</strong>, <em>map=None</em><strong>[</strong>, <em>count=None</em><strong>]]])</strong> </li>
+ <ul>
+ <li>A wrap around asyncore.loop(); starts the asyncore polling loop including running the scheduler. The arguments are the same expected by original asyncore.loop() function. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>close()</strong> </li>
+ <ul>
+ <li>Stop serving without disconnecting currently connected clients. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>close_all([</strong><em>map=None</em><strong>[</strong>, <em>ignore_all=False</em><strong>]])</strong> </li>
+ <ul>
+ <li>Stop serving disconnecting also the currently connected clients. The map parameter is a dictionary whose items are the channels to close. If map is omitted, the default asyncore.socket_map is used. Having ignore_all parameter set to False results in raising exception in case of unexpected errors. </li>
+ </ul>
+ </ul>
+ <hr />
+ <p>class ftpserver.<strong>AbstractedFS()</strong> </p>
+ <blockquote>A class used to interact with the file system, providing a high level, cross-platform interface compatible with both Windows and UNIX style filesystems. It provides some utility methods to operate on pathnames and the wraps around the common calls to interact with the filesystem (e.g. open(), os.mkdir(), os.listdir(), etc...). These latter ones are not reproduced below (see the source instead). </blockquote>
+ <ul>
+ <li><strong>root</strong> </li>
+ <ul>
+ <li>User's home directory (&quot;real&quot;). </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>cwd</strong> </li>
+ <ul>
+ <li>User's current working directory (&quot;virtual&quot;). </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>ftpnorm(</strong><em>ftppath</em><strong>)</strong> </li>
+ <ul>
+ <li>Normalize a &quot;virtual&quot; ftp pathname depending on the current working directory (e.g. having &quot;/foo&quot; as current working directory &quot;x&quot; becomes &quot;/foo/x&quot;). <em><strong>New in 3.0</strong></em> </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>ftp2fs(</strong><em>ftppath</em><strong>)</strong> </li>
+ <ul>
+ <li>Translate a &quot;virtual&quot; ftp pathname into equivalent absolute &quot;real&quot; filesystem pathname (e.g. having &quot;/home/user&quot; as root directory &quot;x&quot; becomes &quot;/home/user/x&quot;). <em><strong>New in 3.0</strong></em> </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>fs2ftp(</strong><em>fspath</em><strong>)</strong> </li>
+ <ul>
+ <li>Translate a &quot;real&quot; filesystem pathname into equivalent absolute &quot;virtual&quot; ftp pathname depending on the user's root directory (e.g. having &quot;/home/user&quot; as root directory &quot;/home/user/x&quot; becomes &quot;/x&quot;. <em><strong>New in 3.0</strong></em> </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>validpath(</strong><em>path</em><strong>)</strong> </li>
+ <ul>
+ <li>Check whether the path belongs to user's home directory. Expected argument is a &quot;real&quot; filesystem path. If path is a symbolic link it is resolved to check its real destination. Pathnames escaping from user's root directory are considered not valid (return False). </li>
+ </ul>
+ </ul>
+ <hr />
+ <p>class ftpserver.<strong>CallLater<a href="http://code.google.com/p/pyftpdlib/w/edit/CallLater">?</a>(</strong><em>seconds</em>, <em>target</em> <strong>[</strong>, *<em>args</em> <strong>[</strong>, **<em>kwargs</em><strong>]])</strong> </p>
+ <blockquote>Calls a function at a later time. It can be used to asynchronously schedule a call within the polling loop without blocking it. The instance returned is an object that can be used to cancel or reschedule the call. <em><strong>New in 0.5.0</strong></em> </blockquote>
+ <ul>
+ <li><strong>cancelled</strong> </li>
+ <ul>
+ <li>Whether the call has been cancelled. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>reset()</strong> </li>
+ <ul>
+ <li>Reschedule the call resetting the current countdown. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>delay(</strong><em>seconds</em><strong>)</strong> </li>
+ <ul>
+ <li>Reschedule the call for a later time. </li>
+ </ul>
+ </ul>
+ <ul>
+ <li><strong>cancel()</strong> </li>
+ <ul>
+ <li>Unschedule the call. </li>
+ </ul>
+ </ul>
+ <h1></h1>
+ <h1><a name="3.0_-_Customizing_your_FTP_server" id="3.0_-_Customizing_your_FTP_server">3.0 - Customizing your FTP server</a></h1>
+ <p><a name="3.0_-_Customizing_your_FTP_server" id="3.0_-_Customizing_your_FTP_server">Below is a set of example scripts showing some of the possible customizations that can be done with pyftpdlib. Some of them are included in demo directory of pyftpdlib source distribution. </a></p>
+ <h3><a name="3.1_-_Building_a_Base_FTP_server" id="3.1_-_Building_a_Base_FTP_server">3.1 - Building a Base FTP server</a></h3>
+ <p><a name="3.1_-_Building_a_Base_FTP_server" id="3.1_-_Building_a_Base_FTP_server">The script below is a basic configuration, and it's probably the best starting point for understanding how things work. It uses the base DummyAuthorizer for adding a bunch of &quot;virtual&quot; users. </a></p>
+ <p><a name="3.1_-_Building_a_Base_FTP_server" id="3.1_-_Building_a_Base_FTP_server">It also sets a limit for connections by overriding FTPServer.max_cons and FTPServer.max_cons_per_ip attributes which are intended to set limits for maximum connections to handle simultaneously and maximum connections from the same IP address. Overriding these variables is always a good idea (they default to 0, or &quot;no limit&quot;) since they are a good workaround for avoiding DoS attacks. </a></p>
+ <pre><a name="3.1_-_Building_a_Base_FTP_server" id="3.1_-_Building_a_Base_FTP_server">#!/usr/bin/env python<br /># basic_ftpd.py<br /><br />&quot;&quot;&quot;A basic FTP server which uses a DummyAuthorizer for managing 'virtual<br />users', setting a limit for incoming connections.<br />&quot;&quot;&quot;<br /><br />import os<br /><br />from pyftpdlib import ftpserver<br /><br /><br />if __name__ == &quot;__main__&quot;:<br /><br />    # Instantiate a dummy authorizer for managing 'virtual' users<br />    authorizer = ftpserver.DummyAuthorizer()<br /><br />    # Define a new user having full r/w permissions and a read-only<br />    # anonymous user<br />    authorizer.add_user('user', '12345', os.getcwd(), perm='elradfmw')<br />    authorizer.add_anonymous(os.getcwd())<br /><br />    # Instantiate FTP handler class<br />    ftp_handler = ftpserver.FTPHandler<br />    ftp_handler.authorizer = authorizer<br /><br />    # Define a customized banner (string returned when client connects)<br />    ftp_handler.banner = &quot;pyftpdlib %s based ftpd ready.&quot; %ftpserver.__ver__<br /><br />    # Specify a masquerade address and the range of ports to use for<br />    # passive connections.  Decomment in case you're behind a NAT.<br />    #ftp_handler.masquerade_address = '151.25.42.11'<br />    #ftp_handler.passive_ports = range(60000, 65535)<br /><br />    # Instantiate FTP server class and listen to 0.0.0.0:21<br />    address = ('', 21)<br />    ftpd = ftpserver.FTPServer(address, ftp_handler)<br /><br />    # set a limit for connections<br />    ftpd.max_cons = 256<br />    ftpd.max_cons_per_ip = 5<br /><br />    # start ftp server<br />    ftpd.serve_forever()</a></pre>
+ <h3><a name="3.2_-_Logging_management" id="3.2_-_Logging_management">3.2 - Logging management</a></h3>
+ <p><a name="3.2_-_Logging_management" id="3.2_-_Logging_management">As mentioned, ftpserver.py comes with 3 different functions intended for a separate logging system: log(), logline() and logerror(). Let's suppose you don't want to print FTPd messages on screen but you want to write them into different files: <em>&quot;/var/log/ftpd.log&quot;</em> will be main log file, <em>&quot;/var/log/ftpd.lines.log&quot;</em> the one where you'll want to store commands and responses passing through the control connection. </a></p>
+ <p><a name="3.2_-_Logging_management" id="3.2_-_Logging_management">Here's one method this could be implemented: </a></p>
+ <pre><a name="3.2_-_Logging_management" id="3.2_-_Logging_management">#!/usr/bin/env python<br /># logging_management.py<br /><br />import os<br />import time<br /><br />from pyftpdlib import ftpserver<br /><br />now = lambda: time.strftime(&quot;[%Y-%b-%d %H:%M:%S]&quot;)<br /><br />def standard_logger(msg):<br />    f1.write(&quot;%s %s\n&quot; %(now(), msg))<br /><br />def line_logger(msg):<br />    f2.write(&quot;%s %s\n&quot; %(now(), msg))<br /><br />if __name__ == &quot;__main__&quot;:<br />    f1 = open('ftpd.log', 'a')<br />    f2 = open('ftpd.lines.log', 'a')<br />    ftpserver.log = standard_logger<br />    ftpserver.logline = line_logger<br /><br />    authorizer = ftpserver.DummyAuthorizer()<br />    authorizer.add_anonymous(os.getcwd())<br />    ftp_handler = ftpserver.FTPHandler<br />    ftp_handler.authorizer = authorizer<br />    address = ('', 21)<br />    ftpd = ftpserver.FTPServer(address, ftp_handler)<br />    ftpd.serve_forever()</a></pre>
+ <h3><a name="3.3_-_Storing_passwords_as_hash_digests" id="3.3_-_Storing_passwords_as_hash_digests">3.3 - Storing passwords as hash digests</a></h3>
+ <p><a name="3.3_-_Storing_passwords_as_hash_digests" id="3.3_-_Storing_passwords_as_hash_digests">Using FTP server library with the default DummyAuthorizer means that password will be stored in clear-text. An end-user ftpd using the default dummy authorizer would typically require a configuration file for authenticating users and their passwords but storing clear-text passwords is of course undesirable. </a></p>
+ <p><a name="3.3_-_Storing_passwords_as_hash_digests" id="3.3_-_Storing_passwords_as_hash_digests">The most common way to do things in such case would be first creating new users and then storing their usernames + passwords as hash digests into a file or wherever you find it convenient. </a></p>
+ <p><a name="3.3_-_Storing_passwords_as_hash_digests" id="3.3_-_Storing_passwords_as_hash_digests">The example below shows how to easily create an encrypted account storage system by storing passwords as one-way hashes by using md5 algorithm. This could be easily done by using the <strong>md5</strong> module included with Python stdlib and by sub-classing the original DummyAuthorizer class overriding its validate_authentication() method: </a></p>
+ <pre><a name="3.3_-_Storing_passwords_as_hash_digests" id="3.3_-_Storing_passwords_as_hash_digests">#!/usr/bin/env python<br /># md5_ftpd.py<br /><br />&quot;&quot;&quot;A basic ftpd storing passwords as hash digests (platform independent).<br />&quot;&quot;&quot;<br /><br />import md5<br />import os<br /><br />from pyftpdlib import ftpserver<br /><br /><br />class DummyMD5Authorizer(ftpserver.DummyAuthorizer):<br /><br />    def validate_authentication(self, username, password):<br />        hash = md5.new(password).hexdigest()<br />        return self.user_table[username]['pwd'] == hash<br /><br />if __name__ == &quot;__main__&quot;:<br />    # get a hash digest from a clear-text password<br />    hash = md5.new('12345').hexdigest()<br />    authorizer = DummyMD5Authorizer()<br />    authorizer.add_user('user', hash, os.getcwd(), perm='elradfmw')<br />    authorizer.add_anonymous(os.getcwd())<br />    ftp_handler = ftpserver.FTPHandler<br />    ftp_handler.authorizer = authorizer<br />    address = ('', 21)<br />    ftpd = ftpserver.FTPServer(address, ftp_handler)<br />    ftpd.serve_forever()</a></pre>
+ <h3><a name="3.4_-_Unix_FTP_Server" id="3.4_-_Unix_FTP_Server">3.4 - Unix FTP Server</a></h3>
+ <p><a name="3.4_-_Unix_FTP_Server" id="3.4_-_Unix_FTP_Server">If you're running a Unix system you may want to configure your ftpd to include support for &quot;real&quot; users existing on the system. </a></p>
+ <p><a name="3.4_-_Unix_FTP_Server" id="3.4_-_Unix_FTP_Server">The example below shows how to use </a><a href="http://docs.python.org/lib/module-pwd.html" rel="nofollow">pwd</a> and <a href="http://docs.python.org/lib/module-spwd.html" rel="nofollow">spwd</a> modules available in <em>Python 2.5</em> or greater (UNIX systems only) to interact with UNIX user account and shadow passwords database and also to automatically get the user's home directory. </p>
+ <p>impersonate_user() and terminate_impersonation() methods of the dummy authorizer are overridden to provide the proper mechanism to reflect the current logged-in user every time he's going to access the filesystem. </p>
+ <p>Note that the users you're going to add through the add_user method must already exist on the system. </p>
+ <pre>#!/usr/bin/env python<br /># unix_ftpd.py<br /><br />&quot;&quot;&quot;A ftpd using local unix account database to authenticate users<br />(users must already exist).<br /><br />It also provides a mechanism to (temporarily) impersonate the system<br />users every time they are going to perform filesystem operations.<br />&quot;&quot;&quot;<br /><br />import os<br />import pwd, spwd, crypt<br /><br />from pyftpdlib import ftpserver<br /><br /><br />class UnixAuthorizer(ftpserver.DummyAuthorizer):<br /><br />    # the uid/gid the daemon runs under<br />    PROCESS_UID = os.getuid()<br />    PROCESS_GID = os.getgid()<br /><br />    def add_user(self, username, homedir=None, **kwargs):<br />        &quot;&quot;&quot;Add a &quot;real&quot; system user to the virtual users table.<br /><br />        If no home argument is specified the user's home directory will<br />        be used.<br /><br />        The keyword arguments in kwargs are the same expected by the<br />        original add_user method: &quot;perm&quot;, &quot;msg_login&quot; and &quot;msg_quit&quot;.<br />        &quot;&quot;&quot;<br />        # get the list of all available users on the system and check<br />        # if provided username exists<br />        users = [entry.pw_name for entry in pwd.getpwall()]<br />        if not username in users:<br />            raise ftpserver.AuthorizerError('No such user &quot;%s&quot;.' %username)<br />        if not homedir:<br />            homedir = pwd.getpwnam(username).pw_dir<br />        ftpserver.DummyAuthorizer.add_user(self, username, '', homedir,**kwargs)<br /><br />    def add_anonymous(self, homedir=None, realuser=&quot;nobody&quot;, **kwargs):<br />        &quot;&quot;&quot;Add an anonymous user to the virtual users table.<br /><br />        If no homedir argument is specified the realuser's home<br />        directory will possibly be determined and used.<br /><br />        realuser argument specifies the system user to use for managing<br />        anonymous sessions.  On many UNIX systems &quot;nobody&quot; is tipically<br />        used but it may change (e.g. &quot;ftp&quot;).<br />        &quot;&quot;&quot;<br />        users = [entry.pw_name for entry in pwd.getpwall()]<br />        if not realuser in users:<br />            raise ftpserver.AuthorizerError('No such user &quot;%s&quot;.' %realuser)<br />        if not homedir:<br />            homedir = pwd.getpwnam(realuser).pw_dir<br />        ftpserver.DummyAuthorizer.add_anonymous(self, homedir, **kwargs)<br />        self.anon_user = realuser<br /><br />    def validate_authentication(self, username, password):<br />        if (username == &quot;anonymous&quot;) and self.has_user('anonymous'):<br />            username = self.anon_user<br /><br />        pw1 = spwd.getspnam(username).sp_pwd<br />        pw2 = crypt.crypt(password, pw1)<br />        return pw1 == pw2<br /><br />    def impersonate_user(self, username, password):<br />        if (username == &quot;anonymous&quot;) and self.has_user('anonymous'):<br />            username = self.anon_user<br />        uid = pwd.getpwnam(username).pw_uid<br />        gid = pwd.getpwnam(username).pw_gid<br />        os.setegid(gid)<br />        os.seteuid(uid)<br /><br />    def terminate_impersonation(self):<br />        os.setegid(self.PROCESS_GID)<br />        os.seteuid(self.PROCESS_UID)<br /><br /><br />if __name__ == &quot;__main__&quot;:<br />    authorizer = UnixAuthorizer()<br />    # add a user (note: user must already exists)<br />    authorizer.add_user('user', perm='elradfmw')<br />    authorizer.add_anonymous(os.getcwd())<br />    ftp_handler = ftpserver.FTPHandler<br />    ftp_handler.authorizer = authorizer<br />    address = ('', 21)<br />    ftpd = ftpserver.FTPServer(address, ftp_handler)<br />    ftpd.serve_forever()</pre>
+ <h3><a name="3.5_-_Windows_NT_FTP_Server" id="3.5_-_Windows_NT_FTP_Server">3.5 - Windows NT FTP Server</a></h3>
+ <p><a name="3.5_-_Windows_NT_FTP_Server" id="3.5_-_Windows_NT_FTP_Server">The following code shows how to implement a basic authorizer for a Windows NT workstation to authenticate against existing Windows user accounts. This code uses Mark Hammond's </a><a href="http://starship.python.net/crew/mhammond/win32/" rel="nofollow">pywin32</a> extension which is required to be installed previously. </p>
+ <p>Note that, as for UNIX authorizer, the users you're going to add through the add_user method must already exist on the system. </p>
+ <pre>#!/usr/bin/env python<br /># winnt_ftpd.py<br /><br />&quot;&quot;&quot;A ftpd using local Windows NT account database to authenticate users<br />(users must already exist).<br /><br />It also provides a mechanism to (temporarily) impersonate the system<br />users every time they are going to perform filesystem operations.<br />&quot;&quot;&quot;<br /><br />import os<br />import win32security, win32net, pywintypes, win32con<br /><br />from pyftpdlib import ftpserver<br /><br /><br />def get_profile_dir(username):<br />    &quot;&quot;&quot;Return the user's profile directory.&quot;&quot;&quot;<br />    import _winreg, win32api<br />    sid = win32security.ConvertSidToStringSid(<br />            win32security.LookupAccountName(None, username)[0])<br />    try:<br />        key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,<br />          r&quot;SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList&quot;+&quot;\\&quot;+sid)<br />    except WindowsError:<br />        raise ftpserver.AuthorizerError(&quot;No profile directory defined for %s &quot;<br />                                        &quot;user&quot; %username)<br />    value = _winreg.QueryValueEx(key, &quot;ProfileImagePath&quot;)[0]<br />    return win32api.ExpandEnvironmentStrings(value)<br /><br /><br />class WinNtAuthorizer(ftpserver.DummyAuthorizer):<br /><br />    def add_user(self, username, homedir=None, **kwargs):<br />        &quot;&quot;&quot;Add a &quot;real&quot; system user to the virtual users table.<br /><br />        If no homedir argument is specified the user's profile<br />        directory will possibly be determined and used.<br /><br />        The keyword arguments in kwargs are the same expected by the<br />        original add_user method: &quot;perm&quot;, &quot;msg_login&quot; and &quot;msg_quit&quot;.<br />        &quot;&quot;&quot;<br />        # get the list of all available users on the system and check<br />        # if provided username exists<br />        users = [entry['name'] for entry in win32net.NetUserEnum(None, 0)[0]]<br />        if not username in users:<br />            raise ftpserver.AuthorizerError('No such user &quot;%s&quot;.' %username)<br />        if not homedir:<br />            homedir = get_profile_dir(username)<br />        ftpserver.DummyAuthorizer.add_user(self, username, '', homedir,<br />                                           **kwargs)<br /><br />    def add_anonymous(self, homedir=None, realuser=&quot;Guest&quot;,<br />                      password=&quot;&quot;, **kwargs):<br />        &quot;&quot;&quot;Add an anonymous user to the virtual users table.<br /><br />        If no homedir argument is specified the realuser's profile<br />        directory will possibly be determined and used.<br /><br />        realuser and password arguments are the credentials to use for<br />        managing anonymous sessions.<br />        The same behaviour is followed in IIS where the Guest account<br />        is used to do so (note: it must be enabled first).<br />        &quot;&quot;&quot;<br />        users = [entry['name'] for entry in win32net.NetUserEnum(None, 0)[0]]<br />        if not realuser in users:<br />            raise ftpserver.AuthorizerError('No such user &quot;%s&quot;.' %realuser)<br />        if not homedir:<br />            homedir = get_profile_dir(realuser)<br />        # make sure provided credentials are valid, otherwise an exception<br />        # will be thrown; to do so we actually try to impersonate the user<br />        self.impersonate_user(realuser, password)<br />        self.terminate_impersonation()<br />        ftpserver.DummyAuthorizer.add_anonymous(self, homedir, **kwargs)<br />        self.anon_user = realuser<br />        self.anon_pwd = password<br /><br />    def validate_authentication(self, username, password):<br />        if (username == &quot;anonymous&quot;) and self.has_user('anonymous'):<br />            username = self.anon_user<br />            password = self.anon_pwd<br />        try:<br />            win32security.LogonUser(username, None, password,<br />                win32con.LOGON32_LOGON_INTERACTIVE,<br />                win32con.LOGON32_PROVIDER_DEFAULT)<br />            return True<br />        except pywintypes.error:<br />            return False<br /><br />    def impersonate_user(self, username, password):<br />        if (username == &quot;anonymous&quot;) and self.has_user('anonymous'):<br />            username = self.anon_user<br />            password = self.anon_pwd<br />        handler = win32security.LogonUser(username, None, password,<br />                      win32con.LOGON32_LOGON_INTERACTIVE,<br />                      win32con.LOGON32_PROVIDER_DEFAULT)<br />        win32security.ImpersonateLoggedOnUser(handler)<br />        handler.Close()<br /><br />    def terminate_impersonation(self):<br />        win32security.RevertToSelf()<br /><br /><br />if __name__ == &quot;__main__&quot;:<br />    authorizer = WinNtAuthorizer()<br />    # add a user (note: user must already exists)<br />    authorizer.add_user('user', perm='elradfmw')<br />    # add an anonymous user using Guest account to handle the anonymous<br />    # sessions (note: Guest must be enabled first)<br />    authorizer.add_anonymous(os.getcwd())<br />    ftp_handler = ftpserver.FTPHandler<br />    ftp_handler.authorizer = authorizer<br />    address = ('', 21)<br />    ftpd = ftpserver.FTPServer(address, ftp_handler)<br />    ftpd.serve_forever()
+
+
+</pre>
+</div>
+</body>
+</html>
diff --git a/third_party/pyftpdlib/pyftpdlib/ftpserver.py b/third_party/pyftpdlib/pyftpdlib/ftpserver.py
new file mode 100644
index 0000000..d273f84
--- /dev/null
+++ b/third_party/pyftpdlib/pyftpdlib/ftpserver.py
@@ -0,0 +1,3127 @@
+#!/usr/bin/env python
+# ftpserver.py
+#
+# pyftpdlib is released under the MIT license, reproduced below:
+# ======================================================================
+# Copyright (C) 2007 Giampaolo Rodola' <g.rodola@gmail.com>
+#
+# 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, and that the name of
+# Giampaolo Rodola' not be used in advertising or publicity pertaining to
+# distribution of the software without specific, written prior
+# permission.
+#
+# Giampaolo Rodola' DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
+# NO EVENT Giampaolo Rodola' BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+# ======================================================================
+
+
+"""pyftpdlib: RFC-959 asynchronous FTP server.
+
+pyftpdlib implements a fully functioning asynchronous FTP server as
+defined in RFC-959. A hierarchy of classes outlined below implement
+the backend functionality for the FTPd:
+
+ [FTPServer] - the base class for the backend.
+
+ [FTPHandler] - a class representing the server-protocol-interpreter
+ (server-PI, see RFC-959). Each time a new connection occurs
+ FTPServer will create a new FTPHandler instance to handle the
+ current PI session.
+
+ [ActiveDTP], [PassiveDTP] - base classes for active/passive-DTP
+ backends.
+
+ [DTPHandler] - this class handles processing of data transfer
+ operations (server-DTP, see RFC-959).
+
+ [DummyAuthorizer] - an "authorizer" is a class handling FTPd
+ authentications and permissions. It is used inside FTPHandler class
+ to verify user passwords, to get user's home directory and to get
+ permissions when a filesystem read/write occurs. "DummyAuthorizer"
+ is the base authorizer class providing a platform independent
+ interface for managing virtual users.
+
+ [AbstractedFS] - class used to interact with the file system,
+ providing a high level, cross-platform interface compatible
+ with both Windows and UNIX style filesystems.
+
+ [CallLater] - calls a function at a later time whithin the polling
+ loop asynchronously.
+
+ [AuthorizerError] - base class for authorizers exceptions.
+
+
+pyftpdlib also provides 3 different logging streams through 3 functions
+which can be overridden to allow for custom logging.
+
+ [log] - the main logger that logs the most important messages for
+ the end user regarding the FTPd.
+
+ [logline] - this function is used to log commands and responses
+ passing through the control FTP channel.
+
+ [logerror] - log traceback outputs occurring in case of errors.
+
+
+Usage example:
+
+>>> from pyftpdlib import ftpserver
+>>> authorizer = ftpserver.DummyAuthorizer()
+>>> authorizer.add_user('user', 'password', '/home/user', perm='elradfmw')
+>>> authorizer.add_anonymous('/home/nobody')
+>>> ftp_handler = ftpserver.FTPHandler
+>>> ftp_handler.authorizer = authorizer
+>>> address = ("127.0.0.1", 21)
+>>> ftpd = ftpserver.FTPServer(address, ftp_handler)
+>>> ftpd.serve_forever()
+Serving FTP on 127.0.0.1:21
+[]127.0.0.1:2503 connected.
+127.0.0.1:2503 ==> 220 Ready.
+127.0.0.1:2503 <== USER anonymous
+127.0.0.1:2503 ==> 331 Username ok, send password.
+127.0.0.1:2503 <== PASS ******
+127.0.0.1:2503 ==> 230 Login successful.
+[anonymous]@127.0.0.1:2503 User anonymous logged in.
+127.0.0.1:2503 <== TYPE A
+127.0.0.1:2503 ==> 200 Type set to: ASCII.
+127.0.0.1:2503 <== PASV
+127.0.0.1:2503 ==> 227 Entering passive mode (127,0,0,1,9,201).
+127.0.0.1:2503 <== LIST
+127.0.0.1:2503 ==> 150 File status okay. About to open data connection.
+[anonymous]@127.0.0.1:2503 OK LIST "/". Transfer starting.
+127.0.0.1:2503 ==> 226 Transfer complete.
+[anonymous]@127.0.0.1:2503 Transfer complete. 706 bytes transmitted.
+127.0.0.1:2503 <== QUIT
+127.0.0.1:2503 ==> 221 Goodbye.
+[anonymous]@127.0.0.1:2503 Disconnected.
+"""
+
+
+import asyncore
+import asynchat
+import socket
+import os
+import sys
+import traceback
+import errno
+import time
+import glob
+import tempfile
+import warnings
+import random
+import stat
+import heapq
+from tarfile import filemode
+
+try:
+ import pwd
+ import grp
+except ImportError:
+ pwd = grp = None
+
+
+__all__ = ['proto_cmds', 'Error', 'log', 'logline', 'logerror', 'DummyAuthorizer',
+ 'AuthorizerError', 'FTPHandler', 'FTPServer', 'PassiveDTP',
+ 'ActiveDTP', 'DTPHandler', 'FileProducer', 'BufferedIteratorProducer',
+ 'AbstractedFS', 'CallLater']
+
+
+__pname__ = 'Python FTP server library (pyftpdlib)'
+__ver__ = '0.5.0'
+__date__ = '2008-09-20'
+__author__ = "Giampaolo Rodola' <g.rodola@gmail.com>"
+__web__ = 'http://code.google.com/p/pyftpdlib/'
+
+
+proto_cmds = {
+ # cmd : (perm, auth, arg, path, help)
+ 'ABOR': (None, True, False, False, 'Syntax: ABOR (abort transfer).'),
+ 'ALLO': (None, True, True, False, 'Syntax: ALLO <SP> bytes (obsolete; allocate storage).'),
+ 'APPE': ('a', True, True, True, 'Syntax: APPE <SP> file-name (append data to an existent file).'),
+ 'CDUP': ('e', True, False, True, 'Syntax: CDUP (go to parent directory).'),
+ 'CWD' : ('e', True, None, True, 'Syntax: CWD [<SP> dir-name] (change current working directory).'),
+ 'DELE': ('d', True, True, True, 'Syntax: DELE <SP> file-name (delete file).'),
+ 'EPRT': (None, True, True, False, 'Syntax: EPRT <SP> |proto|ip|port| (set server in extended active mode).'),
+ 'EPSV': (None, True, None, False, 'Syntax: EPSV [<SP> proto/"ALL"] (set server in extended passive mode).'),
+ 'FEAT': (None, False, False, False, 'Syntax: FEAT (list all new features supported).'),
+ 'HELP': (None, False, None, False, 'Syntax: HELP [<SP> cmd] (show help).'),
+ 'LIST': ('l', True, None, True, 'Syntax: LIST [<SP> path-name] (list files).'),
+ 'MDTM': (None, True, True, True, 'Syntax: MDTM [<SP> file-name] (get last modification time).'),
+ 'MLSD': ('l', True, None, True, 'Syntax: MLSD [<SP> dir-name] (list files in a machine-processable form)'),
+ 'MLST': (None, True, None, True, 'Syntax: MLST [<SP> path-name] (show a path in a machine-processable form)'),
+ 'MODE': (None, True, True, False, 'Syntax: MODE <SP> mode (obsolete; set data transfer mode).'),
+ 'MKD' : ('m', True, True, True, 'Syntax: MDK <SP> dir-name (create directory).'),
+ 'NLST': ('l', True, None, True, 'Syntax: NLST [<SP> path-name] (list files in a compact form).'),
+ 'NOOP': (None, False, False, False, 'Syntax: NOOP (just do nothing).'),
+ 'OPTS': (None, True, True, False, 'Syntax: OPTS <SP> ftp-command [<SP> option] (specify options for FTP commands)'),
+ 'PASS': (None, False, True, False, 'Syntax: PASS <SP> user-name (set user password).'),
+ 'PASV': (None, True, False, False, 'Syntax: PASV (set server in passive mode).'),
+ 'PORT': (None, True, True, False, 'Syntax: PORT <sp> h1,h2,h3,h4,p1,p2 (set server in active mode).'),
+ 'PWD' : (None, True, False, False, 'Syntax: PWD (get current working directory).'),
+ 'QUIT': (None, False, False, False, 'Syntax: QUIT (quit current session).'),
+ 'REIN': (None, True, False, False, 'Syntax: REIN (reinitialize / flush account).'),
+ 'REST': (None, True, True, False, 'Syntax: REST <SP> marker (restart file position).'),
+ 'RETR': ('r', True, True, True, 'Syntax: RETR <SP> file-name (retrieve a file).'),
+ 'RMD' : ('d', True, True, True, 'Syntax: RMD <SP> dir-name (remove directory).'),
+ 'RNFR': ('f', True, True, True, 'Syntax: RNFR <SP> file-name (file renaming (source name)).'),
+ 'RNTO': (None, True, True, True, 'Syntax: RNTO <SP> file-name (file renaming (destination name)).'),
+ 'SIZE': (None, True, True, True, 'Syntax: HELP <SP> file-name (get file size).'),
+ 'STAT': ('l', False, None, True, 'Syntax: STAT [<SP> path name] (status information [list files]).'),
+ 'STOR': ('w', True, True, True, 'Syntax: STOR <SP> file-name (store a file).'),
+ 'STOU': ('w', True, None, True, 'Syntax: STOU [<SP> file-name] (store a file with a unique name).'),
+ 'STRU': (None, True, True, False, 'Syntax: STRU <SP> type (obsolete; set file structure).'),
+ 'SYST': (None, False, False, False, 'Syntax: SYST (get operating system type).'),
+ 'TYPE': (None, True, True, False, 'Syntax: TYPE <SP> [A | I] (set transfer type).'),
+ 'USER': (None, False, True, False, 'Syntax: USER <SP> user-name (set username).'),
+ 'XCUP': ('e', True, False, True, 'Syntax: XCUP (obsolete; go to parent directory).'),
+ 'XCWD': ('e', True, None, True, 'Syntax: XCWD [<SP> dir-name] (obsolete; change current directory).'),
+ 'XMKD': ('m', True, True, True, 'Syntax: XMDK <SP> dir-name (obsolete; create directory).'),
+ 'XPWD': (None, True, False, False, 'Syntax: XPWD (obsolete; get current dir).'),
+ 'XRMD': ('d', True, True, True, 'Syntax: XRMD <SP> dir-name (obsolete; remove directory).'),
+ }
+
+class _CommandProperty:
+ def __init__(self, perm, auth_needed, arg_needed, check_path, help):
+ self.perm = perm
+ self.auth_needed = auth_needed
+ self.arg_needed = arg_needed
+ self.check_path = check_path
+ self.help = help
+
+for cmd, properties in proto_cmds.iteritems():
+ proto_cmds[cmd] = _CommandProperty(*properties)
+del cmd, properties
+
+
+# hack around format_exc function of traceback module to grant
+# backward compatibility with python < 2.4
+if not hasattr(traceback, 'format_exc'):
+ try:
+ import cStringIO as StringIO
+ except ImportError:
+ import StringIO
+
+ def _format_exc():
+ f = StringIO.StringIO()
+ traceback.print_exc(file=f)
+ data = f.getvalue()
+ f.close()
+ return data
+
+ traceback.format_exc = _format_exc
+
+
+def _strerror(err):
+ """A wrap around os.strerror() which may be not available on all
+ platforms (e.g. pythonCE).
+
+ - (instance) err: an EnvironmentError or derived class instance.
+ """
+ if hasattr(os, 'strerror'):
+ return os.strerror(err.errno)
+ else:
+ return err.strerror
+
+# the heap used for the scheduled tasks
+_tasks = []
+
+def _scheduler():
+ """Run the scheduled functions due to expire soonest (if any)."""
+ now = time.time()
+ while _tasks and now >= _tasks[0].timeout:
+ call = heapq.heappop(_tasks)
+ if call.repush:
+ heapq.heappush(_tasks, call)
+ call.repush = False
+ continue
+ try:
+ call.call()
+ finally:
+ if not call.cancelled:
+ call.cancel()
+
+
+class CallLater:
+ """Calls a function at a later time.
+
+ It can be used to asynchronously schedule a call within the polling
+ loop without blocking it. The instance returned is an object that
+ can be used to cancel or reschedule the call.
+ """
+
+ def __init__(self, seconds, target, *args, **kwargs):
+ """
+ - (int) seconds: the number of seconds to wait
+ - (obj) target: the callable object to call later
+ - args: the arguments to call it with
+ - kwargs: the keyword arguments to call it with
+ """
+ assert callable(target), "%s is not callable" %target
+ assert sys.maxint >= seconds >= 0, "%s is not greater than or equal " \
+ "to 0 seconds" % (seconds)
+ self.__delay = seconds
+ self.__target = target
+ self.__args = args
+ self.__kwargs = kwargs
+ # seconds from the epoch at which to call the function
+ self.timeout = time.time() + self.__delay
+ self.repush = False
+ self.cancelled = False
+ heapq.heappush(_tasks, self)
+
+ def __le__(self, other):
+ return self.timeout <= other.timeout
+
+ def call(self):
+ """Call this scheduled function."""
+ assert not self.cancelled, "Already cancelled"
+ self.__target(*self.__args, **self.__kwargs)
+
+ def reset(self):
+ """Reschedule this call resetting the current countdown."""
+ assert not self.cancelled, "Already cancelled"
+ self.timeout = time.time() + self.__delay
+ self.repush = True
+
+ def delay(self, seconds):
+ """Reschedule this call for a later time."""
+ assert not self.cancelled, "Already cancelled."
+ assert sys.maxint >= seconds >= 0, "%s is not greater than or equal " \
+ "to 0 seconds" %(seconds)
+ self.__delay = seconds
+ newtime = time.time() + self.__delay
+ if newtime > self.timeout:
+ self.timeout = newtime
+ self.repush = True
+ else:
+ # XXX - slow, can be improved
+ self.timeout = newtime
+ heapq.heapify(_tasks)
+
+ def cancel(self):
+ """Unschedule this call."""
+ assert not self.cancelled, "Already cancelled"
+ self.cancelled = True
+ del self.__target, self.__args, self.__kwargs
+ if self in _tasks:
+ pos = _tasks.index(self)
+ if pos == 0:
+ heapq.heappop(_tasks)
+ elif pos == len(_tasks) - 1:
+ _tasks.pop(pos)
+ else:
+ _tasks[pos] = _tasks.pop()
+ heapq._siftup(_tasks, pos)
+
+
+# --- library defined exceptions
+
+class Error(Exception):
+ """Base class for module exceptions."""
+
+class AuthorizerError(Error):
+ """Base class for authorizer exceptions."""
+
+
+# --- loggers
+
+def log(msg):
+ """Log messages intended for the end user."""
+ print msg
+
+def logline(msg):
+ """Log commands and responses passing through the command channel."""
+ print msg
+
+def logerror(msg):
+ """Log traceback outputs occurring in case of errors."""
+ sys.stderr.write(str(msg) + '\n')
+ sys.stderr.flush()
+
+
+# --- authorizers
+
+class DummyAuthorizer:
+ """Basic "dummy" authorizer class, suitable for subclassing to
+ create your own custom authorizers.
+
+ An "authorizer" is a class handling authentications and permissions
+ of the FTP server. It is used inside FTPHandler class for verifying
+ user's password, getting users home directory, checking user
+ permissions when a file read/write event occurs and changing user
+ before accessing the filesystem.
+
+ DummyAuthorizer is the base authorizer, providing a platform
+ independent interface for managing "virtual" FTP users. System
+ dependent authorizers can by written by subclassing this base
+ class and overriding appropriate methods as necessary.
+ """
+
+ read_perms = "elr"
+ write_perms = "adfmw"
+
+ def __init__(self):
+ self.user_table = {}
+
+ def add_user(self, username, password, homedir, perm='elr',
+ msg_login="Login successful.", msg_quit="Goodbye."):
+ """Add a user to the virtual users table.
+
+ AuthorizerError exceptions raised on error conditions such as
+ invalid permissions, missing home directory or duplicate usernames.
+
+ Optional perm argument is a string referencing the user's
+ permissions explained below:
+
+ Read permissions:
+ - "e" = change directory (CWD command)
+ - "l" = list files (LIST, NLST, MLSD commands)
+ - "r" = retrieve file from the server (RETR command)
+
+ Write permissions:
+ - "a" = append data to an existing file (APPE command)
+ - "d" = delete file or directory (DELE, RMD commands)
+ - "f" = rename file or directory (RNFR, RNTO commands)
+ - "m" = create directory (MKD command)
+ - "w" = store a file to the server (STOR, STOU commands)
+
+ Optional msg_login and msg_quit arguments can be specified to
+ provide customized response strings when user log-in and quit.
+ """
+ if self.has_user(username):
+ raise AuthorizerError('User "%s" already exists' %username)
+ if not os.path.isdir(homedir):
+ raise AuthorizerError('No such directory: "%s"' %homedir)
+ homedir = os.path.realpath(homedir)
+ self._check_permissions(username, perm)
+ dic = {'pwd': str(password),
+ 'home': homedir,
+ 'perm': perm,
+ 'operms': {},
+ 'msg_login': str(msg_login),
+ 'msg_quit': str(msg_quit)
+ }
+ self.user_table[username] = dic
+
+ def add_anonymous(self, homedir, **kwargs):
+ """Add an anonymous user to the virtual users table.
+
+ AuthorizerError exception raised on error conditions such as
+ invalid permissions, missing home directory, or duplicate
+ anonymous users.
+
+ The keyword arguments in kwargs are the same expected by
+ add_user method: "perm", "msg_login" and "msg_quit".
+
+ The optional "perm" keyword argument is a string defaulting to
+ "elr" referencing "read-only" anonymous user's permissions.
+
+ Using write permission values ("adfmw") results in a
+ RuntimeWarning.
+ """
+ DummyAuthorizer.add_user(self, 'anonymous', '', homedir, **kwargs)
+
+ def remove_user(self, username):
+ """Remove a user from the virtual users table."""
+ del self.user_table[username]
+
+ def override_perm(self, username, directory, perm, recursive=False):
+ """Override permissions for a given directory."""
+ self._check_permissions(username, perm)
+ if not os.path.isdir(directory):
+ raise AuthorizerError('No such directory: "%s"' %directory)
+ directory = os.path.normcase(os.path.realpath(directory))
+ home = os.path.normcase(self.get_home_dir(username))
+ if directory == home:
+ raise AuthorizerError("Can't override home directory permissions")
+ if not self._issubpath(directory, home):
+ raise AuthorizerError("Path escapes user home directory")
+ self.user_table[username]['operms'][directory] = perm, recursive
+
+ def validate_authentication(self, username, password):
+ """Return True if the supplied username and password match the
+ stored credentials."""
+ return self.user_table[username]['pwd'] == password
+
+ def impersonate_user(self, username, password):
+ """Impersonate another user (noop).
+
+ It is always called before accessing the filesystem.
+ By default it does nothing. The subclass overriding this
+ method is expected to provide a mechanism to change the
+ current user.
+ """
+
+ def terminate_impersonation(self):
+ """Terminate impersonation (noop).
+
+ It is always called after having accessed the filesystem.
+ By default it does nothing. The subclass overriding this
+ method is expected to provide a mechanism to switch back
+ to the original user.
+ """
+
+ def has_user(self, username):
+ """Whether the username exists in the virtual users table."""
+ return username in self.user_table
+
+ def has_perm(self, username, perm, path=None):
+ """Whether the user has permission over path (an absolute
+ pathname of a file or a directory).
+
+ Expected perm argument is one of the following letters:
+ "elradfmw".
+ """
+ if path is None:
+ return perm in self.user_table[username]['perm']
+
+ path = os.path.normcase(path)
+ for dir in self.user_table[username]['operms'].keys():
+ operm, recursive = self.user_table[username]['operms'][dir]
+ if self._issubpath(path, dir):
+ if recursive:
+ return perm in operm
+ if (path == dir) or (os.path.dirname(path) == dir \
+ and not os.path.isdir(path)):
+ return perm in operm
+
+ return perm in self.user_table[username]['perm']
+
+ def get_perms(self, username):
+ """Return current user permissions."""
+ return self.user_table[username]['perm']
+
+ def get_home_dir(self, username):
+ """Return the user's home directory."""
+ return self.user_table[username]['home']
+
+ def get_msg_login(self, username):
+ """Return the user's login message."""
+ return self.user_table[username]['msg_login']
+
+ def get_msg_quit(self, username):
+ """Return the user's quitting message."""
+ return self.user_table[username]['msg_quit']
+
+ def _check_permissions(self, username, perm):
+ warned = 0
+ for p in perm:
+ if p not in 'elradfmw':
+ raise AuthorizerError('No such permission "%s"' %p)
+ if (username == 'anonymous') and (p in "adfmw") and not warned:
+ warnings.warn("Write permissions assigned to anonymous user.",
+ RuntimeWarning)
+ warned = 1
+
+ def _issubpath(self, a, b):
+ """Return True if a is a sub-path of b or if the paths are equal."""
+ p1 = a.rstrip(os.sep).split(os.sep)
+ p2 = b.rstrip(os.sep).split(os.sep)
+ return p1[:len(p2)] == p2
+
+
+
+# --- DTP classes
+
+class PassiveDTP(asyncore.dispatcher):
+ """This class is an asyncore.disptacher subclass. It creates a
+ socket listening on a local port, dispatching the resultant
+ connection to DTPHandler.
+
+ - (int) timeout: the timeout for a remote client to establish
+ connection with the listening socket. Defaults to 30 seconds.
+ """
+ timeout = 30
+
+ def __init__(self, cmd_channel, extmode=False):
+ """Initialize the passive data server.
+
+ - (instance) cmd_channel: the command channel class instance.
+ - (bool) extmode: wheter use extended passive mode response type.
+ """
+ asyncore.dispatcher.__init__(self)
+ self.cmd_channel = cmd_channel
+ if self.timeout:
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+ else:
+ self.idler = None
+
+ ip = self.cmd_channel.getsockname()[0]
+ self.create_socket(self.cmd_channel.af, socket.SOCK_STREAM)
+
+ if self.cmd_channel.passive_ports is None:
+ # By using 0 as port number value we let kernel choose a
+ # free unprivileged random port.
+ self.bind((ip, 0))
+ else:
+ ports = list(self.cmd_channel.passive_ports)
+ while ports:
+ port = ports.pop(random.randint(0, len(ports) -1))
+ try:
+ self.bind((ip, port))
+ except socket.error, why:
+ if why[0] == errno.EADDRINUSE: # port already in use
+ if ports:
+ continue
+ # If cannot use one of the ports in the configured
+ # range we'll use a kernel-assigned port, and log
+ # a message reporting the issue.
+ # By using 0 as port number value we let kernel
+ # choose a free unprivileged random port.
+ else:
+ self.bind((ip, 0))
+ self.cmd_channel.log(
+ "Can't find a valid passive port in the "
+ "configured range. A random kernel-assigned "
+ "port will be used."
+ )
+ else:
+ raise
+ else:
+ break
+ self.listen(5)
+ port = self.socket.getsockname()[1]
+ if not extmode:
+ if self.cmd_channel.masquerade_address:
+ ip = self.cmd_channel.masquerade_address
+ # The format of 227 response in not standardized.
+ # This is the most expected:
+ self.cmd_channel.respond('227 Entering passive mode (%s,%d,%d).' %(
+ ip.replace('.', ','), port / 256, port % 256))
+ else:
+ self.cmd_channel.respond('229 Entering extended passive mode '
+ '(|||%d|).' %port)
+
+ # --- connection / overridden
+
+ def handle_accept(self):
+ """Called when remote client initiates a connection."""
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+ sock, addr = self.accept()
+
+ # Check the origin of data connection. If not expressively
+ # configured we drop the incoming data connection if remote
+ # IP address does not match the client's IP address.
+ if (self.cmd_channel.remote_ip != addr[0]):
+ if not self.cmd_channel.permit_foreign_addresses:
+ try:
+ sock.close()
+ except socket.error:
+ pass
+ msg = 'Rejected data connection from foreign address %s:%s.' \
+ %(addr[0], addr[1])
+ self.cmd_channel.respond("425 %s" %msg)
+ self.cmd_channel.log(msg)
+ # do not close listening socket: it couldn't be client's blame
+ return
+ else:
+ # site-to-site FTP allowed
+ msg = 'Established data connection with foreign address %s:%s.'\
+ %(addr[0], addr[1])
+ self.cmd_channel.log(msg)
+ # Immediately close the current channel (we accept only one
+ # connection at time) and avoid running out of max connections
+ # limit.
+ self.close()
+ # delegate such connection to DTP handler
+ handler = self.cmd_channel.dtp_handler(sock, self.cmd_channel)
+ self.cmd_channel.data_channel = handler
+ self.cmd_channel.on_dtp_connection()
+
+ def handle_timeout(self):
+ self.cmd_channel.respond("421 Passive data channel timed out.")
+ self.close()
+
+ def writable(self):
+ return 0
+
+ def handle_error(self):
+ """Called to handle any uncaught exceptions."""
+ try:
+ raise
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ raise
+ logerror(traceback.format_exc())
+ self.close()
+
+ def close(self):
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+ asyncore.dispatcher.close(self)
+
+
+class ActiveDTP(asyncore.dispatcher):
+ """This class is an asyncore.disptacher subclass. It creates a
+ socket resulting from the connection to a remote user-port,
+ dispatching it to DTPHandler.
+
+ - (int) timeout: the timeout for us to establish connection with
+ the client's listening data socket.
+ """
+ timeout = 30
+
+ def __init__(self, ip, port, cmd_channel):
+ """Initialize the active data channel attemping to connect
+ to remote data socket.
+
+ - (str) ip: the remote IP address.
+ - (int) port: the remote port.
+ - (instance) cmd_channel: the command channel class instance.
+ """
+ asyncore.dispatcher.__init__(self)
+ self.cmd_channel = cmd_channel
+ if self.timeout:
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+ else:
+ self.idler = None
+ self.create_socket(self.cmd_channel.af, socket.SOCK_STREAM)
+ try:
+ self.connect((ip, port))
+ except socket.gaierror:
+ self.cmd_channel.respond("425 Can't connect to specified address.")
+ self.close()
+
+ # --- connection / overridden
+
+ def handle_write(self):
+ # NOOP, overridden to prevent unhandled write event msg to
+ # be printed on Python < 2.6
+ pass
+
+ def handle_connect(self):
+ """Called when connection is established."""
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+ self.cmd_channel.respond('200 Active data connection established.')
+ # delegate such connection to DTP handler
+ handler = self.cmd_channel.dtp_handler(self.socket, self.cmd_channel)
+ self.cmd_channel.data_channel = handler
+ self.cmd_channel.on_dtp_connection()
+ #self.close() # <-- (done automatically)
+
+ def handle_timeout(self):
+ self.cmd_channel.respond("421 Active data channel timed out.")
+ self.close()
+
+ def handle_expt(self):
+ self.cmd_channel.respond("425 Can't connect to specified address.")
+ self.close()
+
+ def handle_error(self):
+ """Called to handle any uncaught exceptions."""
+ try:
+ raise
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ raise
+ except socket.error:
+ pass
+ except:
+ logerror(traceback.format_exc())
+ self.cmd_channel.respond("425 Can't connect to specified address.")
+ self.close()
+
+ def close(self):
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+ asyncore.dispatcher.close(self)
+
+
+try:
+ from collections import deque
+except ImportError:
+ # backward compatibility with Python < 2.4 by replacing deque with a list
+ class deque(list):
+ def appendleft(self, obj):
+ list.insert(self, 0, obj)
+
+
+class DTPHandler(asyncore.dispatcher):
+ """Class handling server-data-transfer-process (server-DTP, see
+ RFC-959) managing data-transfer operations involving sending
+ and receiving data.
+
+ Instance attributes defined in this class, initialized when
+ channel is opened:
+
+ - (int) timeout: the timeout which roughly is the maximum time we
+ permit data transfers to stall for with no progress. If the
+ timeout triggers, the remote client will be kicked off.
+
+ - (instance) cmd_channel: the command channel class instance.
+ - (file) file_obj: the file transferred (if any).
+ - (bool) receive: True if channel is used for receiving data.
+ - (bool) transfer_finished: True if transfer completed successfully.
+ - (int) tot_bytes_sent: the total bytes sent.
+ - (int) tot_bytes_received: the total bytes received.
+
+ DTPHandler implementation note:
+
+ When a producer is consumed and close_when_done() has been called
+ previously, refill_buffer() erroneously calls close() instead of
+ handle_close() - (see: http://bugs.python.org/issue1740572)
+
+ To avoid this problem DTPHandler is implemented as a subclass of
+ asyncore.dispatcher instead of asynchat.async_chat.
+ This implementation follows the same approach that asynchat module
+ should use in Python 2.6.
+
+ The most important change in the implementation is related to
+ producer_fifo, which is a pure deque object instead of a
+ producer_fifo instance.
+
+ Since we don't want to break backward compatibily with older python
+ versions (deque has been introduced in Python 2.4), if deque is not
+ available we use a list instead.
+ """
+
+ timeout = 300
+ ac_in_buffer_size = 8192
+ ac_out_buffer_size = 8192
+
+ def __init__(self, sock_obj, cmd_channel):
+ """Initialize the command channel.
+
+ - (instance) sock_obj: the socket object instance of the newly
+ established connection.
+ - (instance) cmd_channel: the command channel class instance.
+ """
+ asyncore.dispatcher.__init__(self, sock_obj)
+ # we toss the use of the asynchat's "simple producer" and
+ # replace it with a pure deque, which the original fifo
+ # was a wrapping of
+ self.producer_fifo = deque()
+
+ self.cmd_channel = cmd_channel
+ self.file_obj = None
+ self.receive = False
+ self.transfer_finished = False
+ self.tot_bytes_sent = 0
+ self.tot_bytes_received = 0
+ self.data_wrapper = lambda x: x
+ self._lastdata = 0
+ self._closed = False
+ if self.timeout:
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+ else:
+ self.idler = None
+
+ # --- utility methods
+
+ def enable_receiving(self, type):
+ """Enable receiving of data over the channel. Depending on the
+ TYPE currently in use it creates an appropriate wrapper for the
+ incoming data.
+
+ - (str) type: current transfer type, 'a' (ASCII) or 'i' (binary).
+ """
+ if type == 'a':
+ self.data_wrapper = lambda x: x.replace('\r\n', os.linesep)
+ elif type == 'i':
+ self.data_wrapper = lambda x: x
+ else:
+ raise TypeError, "Unsupported type"
+ self.receive = True
+
+ def get_transmitted_bytes(self):
+ "Return the number of transmitted bytes."
+ return self.tot_bytes_sent + self.tot_bytes_received
+
+ def transfer_in_progress(self):
+ "Return True if a transfer is in progress, else False."
+ return self.get_transmitted_bytes() != 0
+
+ # --- connection
+
+ def handle_read(self):
+ """Called when there is data waiting to be read."""
+ try:
+ chunk = self.recv(self.ac_in_buffer_size)
+ except socket.error:
+ self.handle_error()
+ else:
+ self.tot_bytes_received += len(chunk)
+ if not chunk:
+ self.transfer_finished = True
+ #self.close() # <-- asyncore.recv() already do that...
+ return
+ # while we're writing on the file an exception could occur
+ # in case that filesystem gets full; if this happens we
+ # let handle_error() method handle this exception, providing
+ # a detailed error message.
+ self.file_obj.write(self.data_wrapper(chunk))
+
+ def handle_write(self):
+ """Called when data is ready to be written, initiates send."""
+ self.initiate_send()
+
+ def push(self, data):
+ """Push data onto the deque and initiate send."""
+ sabs = self.ac_out_buffer_size
+ if len(data) > sabs:
+ for i in xrange(0, len(data), sabs):
+ self.producer_fifo.append(data[i:i+sabs])
+ else:
+ self.producer_fifo.append(data)
+ self.initiate_send()
+
+ def push_with_producer(self, producer):
+ """Push data using a producer and initiate send."""
+ self.producer_fifo.append(producer)
+ self.initiate_send()
+
+ def readable(self):
+ """Predicate for inclusion in the readable for select()."""
+ return self.receive
+
+ def writable(self):
+ """Predicate for inclusion in the writable for select()."""
+ return self.producer_fifo or (not self.connected)
+
+ def close_when_done(self):
+ """Automatically close this channel once the outgoing queue is empty."""
+ self.producer_fifo.append(None)
+
+ def initiate_send(self):
+ """Attempt to send data in fifo order."""
+ while self.producer_fifo and self.connected:
+ first = self.producer_fifo[0]
+ # handle empty string/buffer or None entry
+ if not first:
+ del self.producer_fifo[0]
+ if first is None:
+ self.transfer_finished = True
+ self.handle_close()
+ return
+
+ # handle classic producer behavior
+ obs = self.ac_out_buffer_size
+ try:
+ data = buffer(first, 0, obs)
+ except TypeError:
+ data = first.more()
+ if data:
+ self.producer_fifo.appendleft(data)
+ else:
+ del self.producer_fifo[0]
+ continue
+
+ # send the data
+ try:
+ num_sent = self.send(data)
+ except socket.error:
+ self.handle_error()
+ return
+
+ if num_sent:
+ self.tot_bytes_sent += num_sent
+ if num_sent < len(data) or obs < len(first):
+ self.producer_fifo[0] = first[num_sent:]
+ else:
+ del self.producer_fifo[0]
+ # we tried to send some actual data
+ return
+
+ def handle_timeout(self):
+ """Called cyclically to check if data trasfer is stalling with
+ no progress in which case the client is kicked off.
+ """
+ if self.get_transmitted_bytes() > self._lastdata:
+ self._lastdata = self.get_transmitted_bytes()
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+ else:
+ msg = "Data connection timed out."
+ self.cmd_channel.log(msg)
+ self.cmd_channel.respond("421 " + msg)
+ self.cmd_channel.close_when_done()
+ self.close()
+
+ def handle_expt(self):
+ """Called on "exceptional" data events."""
+ self.cmd_channel.respond("426 Connection error; transfer aborted.")
+ self.close()
+
+ def handle_error(self):
+ """Called when an exception is raised and not otherwise handled."""
+ try:
+ raise
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ raise
+ except socket.error, err:
+ # fix around asyncore bug (http://bugs.python.org/issue1736101)
+ if err[0] in (errno.ECONNRESET, errno.ENOTCONN, errno.ESHUTDOWN, \
+ errno.ECONNABORTED):
+ self.handle_close()
+ return
+ else:
+ error = str(err[1])
+ # an error could occur in case we fail reading / writing
+ # from / to file (e.g. file system gets full)
+ except EnvironmentError, err:
+ error = _strerror(err)
+ except:
+ # some other exception occurred; we don't want to provide
+ # confidential error messages
+ logerror(traceback.format_exc())
+ error = "Internal error"
+ self.cmd_channel.respond("426 %s; transfer aborted." %error)
+ self.close()
+
+ def handle_close(self):
+ """Called when the socket is closed."""
+ # If we used channel for receiving we assume that transfer is
+ # finished when client close connection , if we used channel
+ # for sending we have to check that all data has been sent
+ # (responding with 226) or not (responding with 426).
+ if self.receive:
+ self.transfer_finished = True
+ action = 'received'
+ else:
+ action = 'sent'
+ if self.transfer_finished:
+ self.cmd_channel.respond("226 Transfer complete.")
+ if self.file_obj:
+ fname = self.cmd_channel.fs.fs2ftp(self.file_obj.name)
+ self.cmd_channel.log('"%s" %s.' %(fname, action))
+ else:
+ tot_bytes = self.get_transmitted_bytes()
+ msg = "Transfer aborted; %d bytes transmitted." %tot_bytes
+ self.cmd_channel.respond("426 " + msg)
+ self.cmd_channel.log(msg)
+ self.close()
+
+ def close(self):
+ """Close the data channel, first attempting to close any remaining
+ file handles."""
+ if not self._closed:
+ self._closed = True
+ if self.file_obj is not None and not self.file_obj.closed:
+ self.file_obj.close()
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+ asyncore.dispatcher.close(self)
+ self.cmd_channel.on_dtp_close()
+
+
+# --- producers
+
+class FileProducer:
+ """Producer wrapper for file[-like] objects."""
+
+ buffer_size = 65536
+
+ def __init__(self, file, type):
+ """Initialize the producer with a data_wrapper appropriate to TYPE.
+
+ - (file) file: the file[-like] object.
+ - (str) type: the current TYPE, 'a' (ASCII) or 'i' (binary).
+ """
+ self.done = False
+ self.file = file
+ if type == 'a':
+ self.data_wrapper = lambda x: x.replace(os.linesep, '\r\n')
+ elif type == 'i':
+ self.data_wrapper = lambda x: x
+ else:
+ raise TypeError, "Unsupported type"
+
+ def more(self):
+ """Attempt a chunk of data of size self.buffer_size."""
+ if self.done:
+ return ''
+ data = self.data_wrapper(self.file.read(self.buffer_size))
+ if not data:
+ self.done = True
+ if not self.file.closed:
+ self.file.close()
+ return data
+
+
+class BufferedIteratorProducer:
+ """Producer for iterator objects with buffer capabilities."""
+ # how many times iterator.next() will be called before
+ # returning some data
+ loops = 20
+
+ def __init__(self, iterator):
+ self.iterator = iterator
+
+ def more(self):
+ """Attempt a chunk of data from iterator by calling
+ its next() method different times.
+ """
+ buffer = []
+ for x in xrange(self.loops):
+ try:
+ buffer.append(self.iterator.next())
+ except StopIteration:
+ break
+ return ''.join(buffer)
+
+
+# --- filesystem
+
+class AbstractedFS:
+ """A class used to interact with the file system, providing a high
+ level, cross-platform interface compatible with both Windows and
+ UNIX style filesystems.
+
+ It provides some utility methods and some wraps around operations
+ involved in file creation and file system operations like moving
+ files or removing directories.
+
+ Instance attributes:
+ - (str) root: the user home directory.
+ - (str) cwd: the current working directory.
+ - (str) rnfr: source file to be renamed.
+ """
+
+ def __init__(self):
+ self.root = None
+ self.cwd = '/'
+ self.rnfr = None
+
+ # --- Pathname / conversion utilities
+
+ def ftpnorm(self, ftppath):
+ """Normalize a "virtual" ftp pathname (tipically the raw string
+ coming from client) depending on the current working directory.
+
+ Example (having "/foo" as current working directory):
+ 'x' -> '/foo/x'
+
+ Note: directory separators are system independent ("/").
+ Pathname returned is always absolutized.
+ """
+ if os.path.isabs(ftppath):
+ p = os.path.normpath(ftppath)
+ else:
+ p = os.path.normpath(os.path.join(self.cwd, ftppath))
+ # normalize string in a standard web-path notation having '/'
+ # as separator.
+ p = p.replace("\\", "/")
+ # os.path.normpath supports UNC paths (e.g. "//a/b/c") but we
+ # don't need them. In case we get an UNC path we collapse
+ # redundant separators appearing at the beginning of the string
+ while p[:2] == '//':
+ p = p[1:]
+ # Anti path traversal: don't trust user input, in the event
+ # that self.cwd is not absolute, return "/" as a safety measure.
+ # This is for extra protection, maybe not really necessary.
+ if not os.path.isabs(p):
+ p = "/"
+ return p
+
+ def ftp2fs(self, ftppath):
+ """Translate a "virtual" ftp pathname (tipically the raw string
+ coming from client) into equivalent absolute "real" filesystem
+ pathname.
+
+ Example (having "/home/user" as root directory):
+ 'x' -> '/home/user/x'
+
+ Note: directory separators are system dependent.
+ """
+ # as far as I know, it should always be path traversal safe...
+ if os.path.normpath(self.root) == os.sep:
+ return os.path.normpath(self.ftpnorm(ftppath))
+ else:
+ p = self.ftpnorm(ftppath)[1:]
+ return os.path.normpath(os.path.join(self.root, p))
+
+ def fs2ftp(self, fspath):
+ """Translate a "real" filesystem pathname into equivalent
+ absolute "virtual" ftp pathname depending on the user's
+ root directory.
+
+ Example (having "/home/user" as root directory):
+ '/home/user/x' -> '/x'
+
+ As for ftpnorm, directory separators are system independent
+ ("/") and pathname returned is always absolutized.
+
+ On invalid pathnames escaping from user's root directory
+ (e.g. "/home" when root is "/home/user") always return "/".
+ """
+ if os.path.isabs(fspath):
+ p = os.path.normpath(fspath)
+ else:
+ p = os.path.normpath(os.path.join(self.root, fspath))
+ if not self.validpath(p):
+ return '/'
+ p = p.replace(os.sep, "/")
+ p = p[len(self.root):]
+ if not p.startswith('/'):
+ p = '/' + p
+ return p
+
+ # alias for backward compatibility with 0.2.0
+ normalize = ftpnorm
+ translate = ftp2fs
+
+ def validpath(self, path):
+ """Check whether the path belongs to user's home directory.
+ Expected argument is a "real" filesystem pathname.
+
+ If path is a symbolic link it is resolved to check its real
+ destination.
+
+ Pathnames escaping from user's root directory are considered
+ not valid.
+ """
+ root = self.realpath(self.root)
+ path = self.realpath(path)
+ if not self.root.endswith(os.sep):
+ root = self.root + os.sep
+ if not path.endswith(os.sep):
+ path = path + os.sep
+ if path[0:len(root)] == root:
+ return True
+ return False
+
+ # --- Wrapper methods around open() and tempfile.mkstemp
+
+ def open(self, filename, mode):
+ """Open a file returning its handler."""
+ return open(filename, mode)
+
+ def mkstemp(self, suffix='', prefix='', dir=None, mode='wb'):
+ """A wrap around tempfile.mkstemp creating a file with a unique
+ name. Unlike mkstemp it returns an object with a file-like
+ interface.
+ """
+ class FileWrapper:
+ def __init__(self, fd, name):
+ self.file = fd
+ self.name = name
+ def __getattr__(self, attr):
+ return getattr(self.file, attr)
+
+ text = not 'b' in mode
+ # max number of tries to find out a unique file name
+ tempfile.TMP_MAX = 50
+ fd, name = tempfile.mkstemp(suffix, prefix, dir, text=text)
+ file = os.fdopen(fd, mode)
+ return FileWrapper(file, name)
+
+ # --- Wrapper methods around os.*
+
+ def chdir(self, path):
+ """Change the current directory."""
+ # temporarily join the specified directory to see if we have
+ # permissions to do so
+ basedir = os.getcwd()
+ try:
+ os.chdir(path)
+ except os.error:
+ raise
+ else:
+ os.chdir(basedir)
+ self.cwd = self.fs2ftp(path)
+
+ def mkdir(self, path):
+ """Create the specified directory."""
+ os.mkdir(path)
+
+ def listdir(self, path):
+ """List the content of a directory."""
+ return os.listdir(path)
+
+ def rmdir(self, path):
+ """Remove the specified directory."""
+ os.rmdir(path)
+
+ def remove(self, path):
+ """Remove the specified file."""
+ os.remove(path)
+
+ def rename(self, src, dst):
+ """Rename the specified src file to the dst filename."""
+ os.rename(src, dst)
+
+ def stat(self, path):
+ """Perform a stat() system call on the given path."""
+ return os.stat(path)
+
+ def lstat(self, path):
+ """Like stat but does not follow symbolic links."""
+ return os.lstat(path)
+
+ if not hasattr(os, 'lstat'):
+ lstat = stat
+
+ # --- Wrapper methods around os.path.*
+
+ def isfile(self, path):
+ """Return True if path is a file."""
+ return os.path.isfile(path)
+
+ def islink(self, path):
+ """Return True if path is a symbolic link."""
+ return os.path.islink(path)
+
+ def isdir(self, path):
+ """Return True if path is a directory."""
+ return os.path.isdir(path)
+
+ def getsize(self, path):
+ """Return the size of the specified file in bytes."""
+ return os.path.getsize(path)
+
+ def getmtime(self, path):
+ """Return the last modified time as a number of seconds since
+ the epoch."""
+ return os.path.getmtime(path)
+
+ def realpath(self, path):
+ """Return the canonical version of path eliminating any
+ symbolic links encountered in the path (if they are
+ supported by the operating system).
+ """
+ return os.path.realpath(path)
+
+ def lexists(self, path):
+ """Return True if path refers to an existing path, including
+ a broken or circular symbolic link.
+ """
+ if hasattr(os.path, 'lexists'):
+ return os.path.lexists(path)
+ # grant backward compatibility with python 2.3
+ elif hasattr(os, 'lstat'):
+ try:
+ os.lstat(path)
+ except os.error:
+ return False
+ return True
+ # fallback
+ else:
+ return os.path.exists(path)
+
+ exists = lexists # alias for backward compatibility with 0.2.0
+
+ # --- Listing utilities
+
+ # note: the following operations are no more blocking
+
+ def get_list_dir(self, path):
+ """"Return an iterator object that yields a directory listing
+ in a form suitable for LIST command.
+ """
+ if self.isdir(path):
+ listing = self.listdir(path)
+ listing.sort()
+ return self.format_list(path, listing)
+ # if path is a file or a symlink we return information about it
+ else:
+ basedir, filename = os.path.split(path)
+ self.lstat(path) # raise exc in case of problems
+ return self.format_list(basedir, [filename])
+
+ def format_list(self, basedir, listing, ignore_err=True):
+ """Return an iterator object that yields the entries of given
+ directory emulating the "/bin/ls -lA" UNIX command output.
+
+ - (str) basedir: the absolute dirname.
+ - (list) listing: the names of the entries in basedir
+ - (bool) ignore_err: when False raise exception if os.lstat()
+ call fails.
+
+ On platforms which do not support the pwd and grp modules (such
+ as Windows), ownership is printed as "owner" and "group" as a
+ default, and number of hard links is always "1". On UNIX
+ systems, the actual owner, group, and number of links are
+ printed.
+
+ This is how output appears to client:
+
+ -rw-rw-rw- 1 owner group 7045120 Sep 02 3:47 music.mp3
+ drwxrwxrwx 1 owner group 0 Aug 31 18:50 e-books
+ -rw-rw-rw- 1 owner group 380 Sep 02 3:40 module.py
+ """
+ for basename in listing:
+ file = os.path.join(basedir, basename)
+ try:
+ st = self.lstat(file)
+ except os.error:
+ if ignore_err:
+ continue
+ raise
+ perms = filemode(st.st_mode) # permissions
+ nlinks = st.st_nlink # number of links to inode
+ if not nlinks: # non-posix system, let's use a bogus value
+ nlinks = 1
+ size = st.st_size # file size
+ if pwd and grp:
+ # get user and group name, else just use the raw uid/gid
+ try:
+ uname = pwd.getpwuid(st.st_uid).pw_name
+ except KeyError:
+ uname = st.st_uid
+ try:
+ gname = grp.getgrgid(st.st_gid).gr_name
+ except KeyError:
+ gname = st.st_gid
+ else:
+ # on non-posix systems the only chance we use default
+ # bogus values for owner and group
+ uname = "owner"
+ gname = "group"
+ # stat.st_mtime could fail (-1) if last mtime is too old
+ # in which case we return the local time as last mtime
+ try:
+ mtime = time.strftime("%b %d %H:%M", time.localtime(st.st_mtime))
+ except ValueError:
+ mtime = time.strftime("%b %d %H:%M")
+ # if the file is a symlink, resolve it, e.g. "symlink -> realfile"
+ if stat.S_ISLNK(st.st_mode) and hasattr(os, 'readlink'):
+ basename = basename + " -> " + os.readlink(file)
+
+ # formatting is matched with proftpd ls output
+ yield "%s %3s %-8s %-8s %8s %s %s\r\n" %(perms, nlinks, uname, gname,
+ size, mtime, basename)
+
+ def format_mlsx(self, basedir, listing, perms, facts, ignore_err=True):
+ """Return an iterator object that yields the entries of a given
+ directory or of a single file in a form suitable with MLSD and
+ MLST commands.
+
+ Every entry includes a list of "facts" referring the listed
+ element. See RFC-3659, chapter 7, to see what every single
+ fact stands for.
+
+ - (str) basedir: the absolute dirname.
+ - (list) listing: the names of the entries in basedir
+ - (str) perms: the string referencing the user permissions.
+ - (str) facts: the list of "facts" to be returned.
+ - (bool) ignore_err: when False raise exception if os.stat()
+ call fails.
+
+ Note that "facts" returned may change depending on the platform
+ and on what user specified by using the OPTS command.
+
+ This is how output could appear to the client issuing
+ a MLSD request:
+
+ type=file;size=156;perm=r;modify=20071029155301;unique=801cd2; music.mp3
+ type=dir;size=0;perm=el;modify=20071127230206;unique=801e33; ebooks
+ type=file;size=211;perm=r;modify=20071103093626;unique=801e32; module.py
+ """
+ permdir = ''.join([x for x in perms if x not in 'arw'])
+ permfile = ''.join([x for x in perms if x not in 'celmp'])
+ if ('w' in perms) or ('a' in perms) or ('f' in perms):
+ permdir += 'c'
+ if 'd' in perms:
+ permdir += 'p'
+ type = size = perm = modify = create = unique = mode = uid = gid = ""
+ for basename in listing:
+ file = os.path.join(basedir, basename)
+ try:
+ st = self.stat(file)
+ except OSError:
+ if ignore_err:
+ continue
+ raise
+ # type + perm
+ if stat.S_ISDIR(st.st_mode):
+ if 'type' in facts:
+ if basename == '.':
+ type = 'type=cdir;'
+ elif basename == '..':
+ type = 'type=pdir;'
+ else:
+ type = 'type=dir;'
+ if 'perm' in facts:
+ perm = 'perm=%s;' %permdir
+ else:
+ if 'type' in facts:
+ type = 'type=file;'
+ if 'perm' in facts:
+ perm = 'perm=%s;' %permfile
+ if 'size' in facts:
+ size = 'size=%s;' %st.st_size # file size
+ # last modification time
+ if 'modify' in facts:
+ try:
+ modify = 'modify=%s;' %time.strftime("%Y%m%d%H%M%S",
+ time.localtime(st.st_mtime))
+ except ValueError:
+ # stat.st_mtime could fail (-1) if last mtime is too old
+ modify = ""
+ if 'create' in facts:
+ # on Windows we can provide also the creation time
+ try:
+ create = 'create=%s;' %time.strftime("%Y%m%d%H%M%S",
+ time.localtime(st.st_ctime))
+ except ValueError:
+ create = ""
+ # UNIX only
+ if 'unix.mode' in facts:
+ mode = 'unix.mode=%s;' %oct(st.st_mode & 0777)
+ if 'unix.uid' in facts:
+ uid = 'unix.uid=%s;' %st.st_uid
+ if 'unix.gid' in facts:
+ gid = 'unix.gid=%s;' %st.st_gid
+ # We provide unique fact (see RFC-3659, chapter 7.5.2) on
+ # posix platforms only; we get it by mixing st_dev and
+ # st_ino values which should be enough for granting an
+ # uniqueness for the file listed.
+ # The same approach is used by pure-ftpd.
+ # Implementors who want to provide unique fact on other
+ # platforms should use some platform-specific method (e.g.
+ # on Windows NTFS filesystems MTF records could be used).
+ if 'unique' in facts:
+ unique = "unique=%x%x;" %(st.st_dev, st.st_ino)
+
+ yield "%s%s%s%s%s%s%s%s%s %s\r\n" %(type, size, perm, modify, create,
+ mode, uid, gid, unique, basename)
+
+
+# --- FTP
+
+class FTPHandler(asynchat.async_chat):
+ """Implements the FTP server Protocol Interpreter (see RFC-959),
+ handling commands received from the client on the control channel.
+
+ All relevant session information is stored in class attributes
+ reproduced below and can be modified before instantiating this
+ class.
+
+ - (int) timeout:
+ The timeout which is the maximum time a remote client may spend
+ between FTP commands. If the timeout triggers, the remote client
+ will be kicked off. Defaults to 300 seconds.
+
+ - (str) banner: the string sent when client connects.
+
+ - (int) max_login_attempts:
+ the maximum number of wrong authentications before disconnecting
+ the client (default 3).
+
+ - (bool)permit_foreign_addresses:
+ FTP site-to-site transfer feature: also referenced as "FXP" it
+ permits for transferring a file between two remote FTP servers
+ without the transfer going through the client's host (not
+ recommended for security reasons as described in RFC-2577).
+ Having this attribute set to False means that all data
+ connections from/to remote IP addresses which do not match the
+ client's IP address will be dropped (defualt False).
+
+ - (bool) permit_privileged_ports:
+ set to True if you want to permit active data connections (PORT)
+ over privileged ports (not recommended, defaulting to False).
+
+ - (str) masquerade_address:
+ the "masqueraded" IP address to provide along PASV reply when
+ pyftpdlib is running behind a NAT or other types of gateways.
+ When configured pyftpdlib will hide its local address and
+ instead use the public address of your NAT (default None).
+
+ - (list) passive_ports:
+ what ports ftpd will use for its passive data transfers.
+ Value expected is a list of integers (e.g. range(60000, 65535)).
+ When configured pyftpdlib will no longer use kernel-assigned
+ random ports (default None).
+
+
+ All relevant instance attributes initialized when client connects
+ are reproduced below. You may be interested in them in case you
+ want to subclass the original FTPHandler.
+
+ - (bool) authenticated: True if client authenticated himself.
+ - (str) username: the name of the connected user (if any).
+ - (int) attempted_logins: number of currently attempted logins.
+ - (str) current_type: the current transfer type (default "a")
+ - (int) af: the address family (IPv4/IPv6)
+ - (instance) server: the FTPServer class instance.
+ - (instance) data_server: the data server instance (if any).
+ - (instance) data_channel: the data channel instance (if any).
+ """
+ # these are overridable defaults
+
+ # default classes
+ authorizer = DummyAuthorizer()
+ active_dtp = ActiveDTP
+ passive_dtp = PassiveDTP
+ dtp_handler = DTPHandler
+ abstracted_fs = AbstractedFS
+
+ # session attributes (explained in the docstring)
+ timeout = 300
+ banner = "pyftpdlib %s ready." %__ver__
+ max_login_attempts = 3
+ permit_foreign_addresses = False
+ permit_privileged_ports = False
+ masquerade_address = None
+ passive_ports = None
+
+ def __init__(self, conn, server):
+ """Initialize the command channel.
+
+ - (instance) conn: the socket object instance of the newly
+ established connection.
+ - (instance) server: the ftp server class instance.
+ """
+ asynchat.async_chat.__init__(self, conn)
+ self.set_terminator("\r\n")
+ # try to handle urgent data inline
+ try:
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_OOBINLINE, 1)
+ except socket.error:
+ pass
+
+ # public session attributes
+ self.server = server
+ self.remote_ip, self.remote_port = self.socket.getpeername()[:2]
+ self.fs = self.abstracted_fs()
+ self.authenticated = False
+ self.username = ""
+ self.password = ""
+ self.attempted_logins = 0
+ self.current_type = 'a'
+ self.restart_position = 0
+ self.quit_pending = False
+ self.sleeping = False
+ self.data_server = None
+ self.data_channel = None
+ if self.timeout:
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+ else:
+ self.idler = None
+ if hasattr(self.socket, 'family'):
+ self.af = self.socket.family
+ else: # python < 2.5
+ ip, port = self.socket.getsockname()[:2]
+ self.af = socket.getaddrinfo(ip, port, socket.AF_UNSPEC,
+ socket.SOCK_STREAM)[0][0]
+
+ # private session attributes
+ self._in_buffer = []
+ self._in_buffer_len = 0
+ self._epsvall = False
+ self._in_dtp_queue = None
+ self._out_dtp_queue = None
+ self._closed = False
+ self._current_facts = ['type', 'perm', 'size', 'modify']
+ if os.name == 'posix':
+ self._current_facts.append('unique')
+ self._available_facts = self._current_facts[:]
+ if pwd and grp:
+ self._available_facts += ['unix.mode', 'unix.uid', 'unix.gid']
+ if os.name == 'nt':
+ self._available_facts.append('create')
+
+ def handle(self):
+ """Return a 220 'Ready' response to the client over the command
+ channel.
+ """
+ if len(self.banner) <= 75:
+ self.respond("220 %s" %str(self.banner))
+ else:
+ self.push('220-%s\r\n' %str(self.banner))
+ self.respond('220 ')
+
+ def handle_max_cons(self):
+ """Called when limit for maximum number of connections is reached."""
+ msg = "Too many connections. Service temporary unavailable."
+ self.respond("421 %s" %msg)
+ self.log(msg)
+ # If self.push is used, data could not be sent immediately in
+ # which case a new "loop" will occur exposing us to the risk of
+ # accepting new connections. Since this could cause asyncore to
+ # run out of fds (...and exposes the server to DoS attacks), we
+ # immediately close the channel by using close() instead of
+ # close_when_done(). If data has not been sent yet client will
+ # be silently disconnected.
+ self.close()
+
+ def handle_max_cons_per_ip(self):
+ """Called when too many clients are connected from the same IP."""
+ msg = "Too many connections from the same IP address."
+ self.respond("421 %s" %msg)
+ self.log(msg)
+ self.close_when_done()
+
+ def handle_timeout(self):
+ """Called when client does not send any command within the time
+ specified in <timeout> attribute."""
+ msg = "Control connection timed out."
+ self.log(msg)
+ self.respond("421 " + msg)
+ self.close_when_done()
+
+ # --- asyncore / asynchat overridden methods
+
+ def readable(self):
+ # if there's a quit pending we stop reading data from socket
+ return not self.sleeping
+
+ def collect_incoming_data(self, data):
+ """Read incoming data and append to the input buffer."""
+ self._in_buffer.append(data)
+ self._in_buffer_len += len(data)
+ # Flush buffer if it gets too long (possible DoS attacks).
+ # RFC-959 specifies that a 500 response could be given in
+ # such cases
+ buflimit = 2048
+ if self._in_buffer_len > buflimit:
+ self.respond('500 Command too long.')
+ self.log('Command received exceeded buffer limit of %s.' %(buflimit))
+ self._in_buffer = []
+ self._in_buffer_len = 0
+
+ def found_terminator(self):
+ r"""Called when the incoming data stream matches the \r\n
+ terminator.
+
+ Depending on the command received it calls the command's
+ corresponding method (e.g. for received command "MKD pathname",
+ ftp_MKD() method is called with "pathname" as the argument).
+ """
+ if self.idler and not self.idler.cancelled:
+ self.idler.reset()
+
+ line = ''.join(self._in_buffer)
+ self._in_buffer = []
+ self._in_buffer_len = 0
+
+ cmd = line.split(' ')[0].upper()
+ space = line.find(' ')
+ if space != -1:
+ arg = line[space + 1:]
+ else:
+ arg = ""
+
+ if cmd != 'PASS':
+ self.logline("<== %s" %line)
+ else:
+ self.logline("<== %s %s" %(line.split(' ')[0], '*' * 6))
+
+ # Recognize those commands having "special semantics". They
+ # may be sent as OOB data but since many ftp clients does
+ # not follow the procedure from the RFC to send Telnet IP
+ # and Synch first, we check the last 4 characters only.
+ if not cmd in proto_cmds:
+ if cmd[-4:] in ('ABOR', 'STAT', 'QUIT'):
+ cmd = cmd[-4:]
+ else:
+ self.respond('500 Command "%s" not understood.' %cmd)
+ return
+
+ if not arg and proto_cmds[cmd].arg_needed is True:
+ self.respond("501 Syntax error: command needs an argument.")
+ return
+ if arg and proto_cmds[cmd].arg_needed is False:
+ self.respond("501 Syntax error: command does not accept arguments.")
+ return
+
+ if not self.authenticated:
+ if proto_cmds[cmd].auth_needed or (cmd == 'STAT' and arg):
+ self.respond("530 Log in with USER and PASS first.")
+ else:
+ method = getattr(self, 'ftp_' + cmd)
+ method(arg) # call the proper ftp_* method
+ else:
+ if cmd == 'STAT' and not arg:
+ self.ftp_STAT('')
+ return
+
+ # for file-system related commands check whether real path
+ # destination is valid
+ if proto_cmds[cmd].check_path and cmd != 'STOU':
+ if cmd in ('CWD', 'XCWD'):
+ arg = self.fs.ftp2fs(arg or '/')
+ elif cmd in ('CDUP', 'XCUP'):
+ arg = self.fs.ftp2fs('..')
+ elif cmd == 'LIST':
+ if arg.lower() in ('-a', '-l', '-al', '-la'):
+ arg = self.fs.ftp2fs(self.fs.cwd)
+ else:
+ arg = self.fs.ftp2fs(arg or self.fs.cwd)
+ elif cmd == 'STAT':
+ if glob.has_magic(arg):
+ self.respond('550 Globbing not supported.')
+ return
+ arg = self.fs.ftp2fs(arg or self.fs.cwd)
+ else: # LIST, NLST, MLSD, MLST
+ arg = self.fs.ftp2fs(arg or self.fs.cwd)
+
+ if not self.fs.validpath(arg):
+ line = self.fs.fs2ftp(arg)
+ err = '"%s" points to a path which is outside ' \
+ "the user's root directory" %line
+ self.respond("550 %s." %err)
+ self.log('FAIL %s "%s". %s.' %(cmd, line, err))
+ return
+
+ # check permission
+ perm = proto_cmds[cmd].perm
+ if perm is not None and cmd != 'STOU':
+ if not self.authorizer.has_perm(self.username, perm, arg):
+ self.log('FAIL %s "%s". Not enough privileges.' \
+ %(cmd, self.fs.fs2ftp(arg)))
+ self.respond("550 Can't %s. Not enough privileges." %cmd)
+ return
+
+ # call the proper ftp_* method
+ method = getattr(self, 'ftp_' + cmd)
+ method(arg)
+
+ def handle_expt(self):
+ """Called when there is out of band (OOB) data to be read.
+ This could happen in case of such clients strictly following
+ the RFC-959 directives of sending Telnet IP and Synch as OOB
+ data before issuing ABOR, STAT and QUIT commands.
+ It should never be called since the SO_OOBINLINE option is
+ enabled except on some systems like FreeBSD where it doesn't
+ seem to have effect.
+ """
+ if hasattr(socket, 'MSG_OOB'):
+ try:
+ data = self.socket.recv(1024, socket.MSG_OOB)
+ except socket.error, why:
+ if why[0] == errno.EINVAL:
+ return
+ else:
+ self._in_buffer.append(data)
+ return
+ self.log("Can't handle OOB data.")
+ self.close()
+
+ def handle_error(self):
+ try:
+ raise
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ raise
+ except socket.error, err:
+ # fix around asyncore bug (http://bugs.python.org/issue1736101)
+ if err[0] in (errno.ECONNRESET, errno.ENOTCONN, errno.ESHUTDOWN, \
+ errno.ECONNABORTED):
+ self.handle_close()
+ return
+ else:
+ logerror(traceback.format_exc())
+ except:
+ logerror(traceback.format_exc())
+ self.close()
+
+ def handle_close(self):
+ self.close()
+
+ def close(self):
+ """Close the current channel disconnecting the client."""
+ if not self._closed:
+ self._closed = True
+ if self.data_server is not None:
+ self.data_server.close()
+ del self.data_server
+
+ if self.data_channel is not None:
+ self.data_channel.close()
+ del self.data_channel
+
+ del self._out_dtp_queue
+ del self._in_dtp_queue
+
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+
+ # remove client IP address from ip map
+ self.server.ip_map.remove(self.remote_ip)
+ asynchat.async_chat.close(self)
+ self.log("Disconnected.")
+
+ # --- callbacks
+
+ def on_dtp_connection(self):
+ """Called every time data channel connects (either active or
+ passive).
+
+ Incoming and outgoing queues are checked for pending data.
+ If outbound data is pending, it is pushed into the data channel.
+ If awaiting inbound data, the data channel is enabled for
+ receiving.
+ """
+ if self.data_server is not None:
+ self.data_server.close()
+ self.data_server = None
+
+ # stop the idle timer as long as the data transfer is not finished
+ if self.idler and not self.idler.cancelled:
+ self.idler.cancel()
+
+ # check for data to send
+ if self._out_dtp_queue is not None:
+ data, isproducer, file = self._out_dtp_queue
+ if file:
+ self.data_channel.file_obj = file
+ if not isproducer:
+ self.data_channel.push(data)
+ else:
+ self.data_channel.push_with_producer(data)
+ if self.data_channel is not None:
+ self.data_channel.close_when_done()
+ self._out_dtp_queue = None
+
+ # check for data to receive
+ elif self._in_dtp_queue is not None:
+ self.data_channel.file_obj = self._in_dtp_queue
+ self.data_channel.enable_receiving(self.current_type)
+ self._in_dtp_queue = None
+
+ def on_dtp_close(self):
+ """Called every time the data channel is closed."""
+ self.data_channel = None
+ if self.quit_pending:
+ self.close_when_done()
+ elif self.timeout:
+ # data transfer finished, restart the idle timer
+ self.idler = CallLater(self.timeout, self.handle_timeout)
+
+ # --- utility
+
+ def respond(self, resp):
+ """Send a response to the client using the command channel."""
+ self.push(resp + '\r\n')
+ self.logline('==> %s' % resp)
+
+ def push_dtp_data(self, data, isproducer=False, file=None):
+ """Pushes data into the data channel.
+
+ It is usually called for those commands requiring some data to
+ be sent over the data channel (e.g. RETR).
+ If data channel does not exist yet, it queues the data to send
+ later; data will then be pushed into data channel when
+ on_dtp_connection() will be called.
+
+ - (str/classobj) data: the data to send which may be a string
+ or a producer object).
+ - (bool) isproducer: whether treat data as a producer.
+ - (file) file: the file[-like] object to send (if any).
+ """
+ if self.data_channel is not None:
+ self.respond("125 Data connection already open. Transfer starting.")
+ if file:
+ self.data_channel.file_obj = file
+ if not isproducer:
+ self.data_channel.push(data)
+ else:
+ self.data_channel.push_with_producer(data)
+ if self.data_channel is not None:
+ self.data_channel.close_when_done()
+ else:
+ self.respond("150 File status okay. About to open data connection.")
+ self._out_dtp_queue = (data, isproducer, file)
+
+ def log(self, msg):
+ """Log a message, including additional identifying session data."""
+ log("[%s]@%s:%s %s" %(self.username, self.remote_ip,
+ self.remote_port, msg))
+
+ def logline(self, msg):
+ """Log a line including additional indentifying session data."""
+ logline("%s:%s %s" %(self.remote_ip, self.remote_port, msg))
+
+ def flush_account(self):
+ """Flush account information by clearing attributes that need
+ to be reset on a REIN or new USER command.
+ """
+ if self.data_channel is not None:
+ if not self.data_channel.transfer_in_progress():
+ self.data_channel.close()
+ self.data_channel = None
+ if self.data_server is not None:
+ self.data_server.close()
+ self.data_server = None
+
+ self.fs.rnfr = None
+ self.authenticated = False
+ self.username = ""
+ self.password = ""
+ self.attempted_logins = 0
+ self.current_type = 'a'
+ self.restart_position = 0
+ self.quit_pending = False
+ self.sleeping = False
+ self._in_dtp_queue = None
+ self._out_dtp_queue = None
+
+ def run_as_current_user(self, function, *args, **kwargs):
+ """Execute a function impersonating the current logged-in user."""
+ self.authorizer.impersonate_user(self.username, self.password)
+ try:
+ return function(*args, **kwargs)
+ finally:
+ self.authorizer.terminate_impersonation()
+
+ # --- connection
+
+ def _make_eport(self, ip, port):
+ """Establish an active data channel with remote client which
+ issued a PORT or EPRT command.
+ """
+ # FTP bounce attacks protection: according to RFC-2577 it's
+ # recommended to reject PORT if IP address specified in it
+ # does not match client IP address.
+ if not self.permit_foreign_addresses and ip != self.remote_ip:
+ self.log("Rejected data connection to foreign address %s:%s."
+ %(ip, port))
+ self.respond("501 Can't connect to a foreign address.")
+ return
+
+ # ...another RFC-2577 recommendation is rejecting connections
+ # to privileged ports (< 1024) for security reasons.
+ if not self.permit_privileged_ports and port < 1024:
+ self.log('PORT against the privileged port "%s" refused.' %port)
+ self.respond("501 Can't connect over a privileged port.")
+ return
+
+ # close existent DTP-server instance, if any.
+ if self.data_server is not None:
+ self.data_server.close()
+ self.data_server = None
+ if self.data_channel is not None:
+ self.data_channel.close()
+ self.data_channel = None
+
+ # make sure we are not hitting the max connections limit
+ if self.server.max_cons and len(self._map) >= self.server.max_cons:
+ msg = "Too many connections. Can't open data channel."
+ self.respond("425 %s" %msg)
+ self.log(msg)
+ return
+
+ # open data channel
+ self.active_dtp(ip, port, self)
+
+ def _make_epasv(self, extmode=False):
+ """Initialize a passive data channel with remote client which
+ issued a PASV or EPSV command.
+ If extmode argument is False we assume that client issued EPSV in
+ which case extended passive mode will be used (see RFC-2428).
+ """
+ # close existing DTP-server instance, if any
+ if self.data_server is not None:
+ self.data_server.close()
+ self.data_server = None
+
+ if self.data_channel is not None:
+ self.data_channel.close()
+ self.data_channel = None
+
+ # make sure we are not hitting the max connections limit
+ if self.server.max_cons and len(self._map) >= self.server.max_cons:
+ msg = "Too many connections. Can't open data channel."
+ self.respond("425 %s" %msg)
+ self.log(msg)
+ return
+
+ # open data channel
+ self.data_server = self.passive_dtp(self, extmode)
+
+ def ftp_PORT(self, line):
+ """Start an active data channel by using IPv4."""
+ if self._epsvall:
+ self.respond("501 PORT not allowed after EPSV ALL.")
+ return
+ if self.af != socket.AF_INET:
+ self.respond("425 You cannot use PORT on IPv6 connections. "
+ "Use EPRT instead.")
+ return
+ # Parse PORT request for getting IP and PORT.
+ # Request comes in as:
+ # > h1,h2,h3,h4,p1,p2
+ # ...where the client's IP address is h1.h2.h3.h4 and the TCP
+ # port number is (p1 * 256) + p2.
+ try:
+ addr = map(int, line.split(','))
+ assert len(addr) == 6
+ for x in addr[:4]:
+ assert 0 <= x <= 255
+ ip = '%d.%d.%d.%d' %tuple(addr[:4])
+ port = (addr[4] * 256) + addr[5]
+ assert 0 <= port <= 65535
+ except (AssertionError, ValueError, OverflowError):
+ self.respond("501 Invalid PORT format.")
+ return
+ self._make_eport(ip, port)
+
+ def ftp_EPRT(self, line):
+ """Start an active data channel by choosing the network protocol
+ to use (IPv4/IPv6) as defined in RFC-2428.
+ """
+ if self._epsvall:
+ self.respond("501 EPRT not allowed after EPSV ALL.")
+ return
+ # Parse EPRT request for getting protocol, IP and PORT.
+ # Request comes in as:
+ # # <d>proto<d>ip<d>port<d>
+ # ...where <d> is an arbitrary delimiter character (usually "|") and
+ # <proto> is the network protocol to use (1 for IPv4, 2 for IPv6).
+ try:
+ af, ip, port = line.split(line[0])[1:-1]
+ port = int(port)
+ assert 0 <= port <= 65535
+ except (AssertionError, ValueError, IndexError, OverflowError):
+ self.respond("501 Invalid EPRT format.")
+ return
+
+ if af == "1":
+ if self.af != socket.AF_INET:
+ self.respond('522 Network protocol not supported (use 2).')
+ else:
+ try:
+ octs = map(int, ip.split('.'))
+ assert len(octs) == 4
+ for x in octs:
+ assert 0 <= x <= 255
+ except (AssertionError, ValueError, OverflowError):
+ self.respond("501 Invalid EPRT format.")
+ else:
+ self._make_eport(ip, port)
+ elif af == "2":
+ if self.af == socket.AF_INET:
+ self.respond('522 Network protocol not supported (use 1).')
+ else:
+ self._make_eport(ip, port)
+ else:
+ if self.af == socket.AF_INET:
+ self.respond('501 Unknown network protocol (use 1).')
+ else:
+ self.respond('501 Unknown network protocol (use 2).')
+
+ def ftp_PASV(self, line):
+ """Start a passive data channel by using IPv4."""
+ if self._epsvall:
+ self.respond("501 PASV not allowed after EPSV ALL.")
+ return
+ if self.af != socket.AF_INET:
+ self.respond("425 You cannot use PASV on IPv6 connections. "
+ "Use EPSV instead.")
+ else:
+ self._make_epasv(extmode=False)
+
+ def ftp_EPSV(self, line):
+ """Start a passive data channel by using IPv4 or IPv6 as defined
+ in RFC-2428.
+ """
+ # RFC-2428 specifies that if an optional parameter is given,
+ # we have to determine the address family from that otherwise
+ # use the same address family used on the control connection.
+ # In such a scenario a client may use IPv4 on the control channel
+ # and choose to use IPv6 for the data channel.
+ # But how could we use IPv6 on the data channel without knowing
+ # which IPv6 address to use for binding the socket?
+ # Unfortunately RFC-2428 does not provide satisfing information
+ # on how to do that. The assumption is that we don't have any way
+ # to know wich address to use, hence we just use the same address
+ # family used on the control connection.
+ if not line:
+ self._make_epasv(extmode=True)
+ elif line == "1":
+ if self.af != socket.AF_INET:
+ self.respond('522 Network protocol not supported (use 2).')
+ else:
+ self._make_epasv(extmode=True)
+ elif line == "2":
+ if self.af == socket.AF_INET:
+ self.respond('522 Network protocol not supported (use 1).')
+ else:
+ self._make_epasv(extmode=True)
+ elif line.lower() == 'all':
+ self._epsvall = True
+ self.respond('220 Other commands other than EPSV are now disabled.')
+ else:
+ if self.af == socket.AF_INET:
+ self.respond('501 Unknown network protocol (use 1).')
+ else:
+ self.respond('501 Unknown network protocol (use 2).')
+
+ def ftp_QUIT(self, line):
+ """Quit the current session disconnecting the client."""
+ if self.authenticated:
+ msg_quit = self.authorizer.get_msg_quit(self.username)
+ else:
+ msg_quit = "Goodbye."
+ if len(msg_quit) <= 75:
+ self.respond("221 %s" %msg_quit)
+ else:
+ self.push("221-%s\r\n" %msg_quit)
+ self.respond("221 ")
+
+ # From RFC-959:
+ # If file transfer is in progress, the connection will remain
+ # open for result response and the server will then close it.
+ # We also stop responding to any further command.
+ if self.data_channel:
+ self.quit_pending = True
+ self.sleeping = True
+ else:
+ self.close_when_done()
+
+ # --- data transferring
+
+ def ftp_LIST(self, path):
+ """Return a list of files in the specified directory to the
+ client.
+ """
+ # - If no argument, fall back on cwd as default.
+ # - Some older FTP clients erroneously issue /bin/ls-like LIST
+ # formats in which case we fall back on cwd as default.
+ line = self.fs.fs2ftp(path)
+ try:
+ iterator = self.run_as_current_user(self.fs.get_list_dir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL LIST "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK LIST "%s". Transfer starting.' %line)
+ producer = BufferedIteratorProducer(iterator)
+ self.push_dtp_data(producer, isproducer=True)
+
+ def ftp_NLST(self, path):
+ """Return a list of files in the specified directory in a
+ compact form to the client.
+ """
+ line = self.fs.fs2ftp(path)
+ try:
+ if self.fs.isdir(path):
+ listing = self.run_as_current_user(self.fs.listdir, path)
+ else:
+ # if path is a file we just list its name
+ self.fs.lstat(path) # raise exc in case of problems
+ listing = [os.path.basename(path)]
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL NLST "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ data = ''
+ if listing:
+ listing.sort()
+ data = '\r\n'.join(listing) + '\r\n'
+ self.log('OK NLST "%s". Transfer starting.' %line)
+ self.push_dtp_data(data)
+
+ # --- MLST and MLSD commands
+
+ # The MLST and MLSD commands are intended to standardize the file and
+ # directory information returned by the server-FTP process. These
+ # commands differ from the LIST command in that the format of the
+ # replies is strictly defined although extensible.
+
+ def ftp_MLST(self, path):
+ """Return information about a pathname in a machine-processable
+ form as defined in RFC-3659.
+ """
+ line = self.fs.fs2ftp(path)
+ basedir, basename = os.path.split(path)
+ perms = self.authorizer.get_perms(self.username)
+ try:
+ iterator = self.run_as_current_user(self.fs.format_mlsx, basedir,
+ [basename], perms, self._current_facts, ignore_err=False)
+ data = ''.join(iterator)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL MLST "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ # since TVFS is supported (see RFC-3659 chapter 6), a fully
+ # qualified pathname should be returned
+ data = data.split(' ')[0] + ' %s\r\n' %line
+ # response is expected on the command channel
+ self.push('250-Listing "%s":\r\n' %line)
+ # the fact set must be preceded by a space
+ self.push(' ' + data)
+ self.respond('250 End MLST.')
+
+ def ftp_MLSD(self, path):
+ """Return contents of a directory in a machine-processable form
+ as defined in RFC-3659.
+ """
+ line = self.fs.fs2ftp(path)
+ # RFC-3659 requires 501 response code if path is not a directory
+ if not self.fs.isdir(path):
+ err = 'No such directory'
+ self.log('FAIL MLSD "%s". %s.' %(line, err))
+ self.respond("501 %s." %err)
+ return
+ try:
+ listing = self.run_as_current_user(self.fs.listdir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL MLSD "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ perms = self.authorizer.get_perms(self.username)
+ iterator = self.fs.format_mlsx(path, listing, perms,
+ self._current_facts)
+ producer = BufferedIteratorProducer(iterator)
+ self.log('OK MLSD "%s". Transfer starting.' %line)
+ self.push_dtp_data(producer, isproducer=True)
+
+ def ftp_RETR(self, file):
+ """Retrieve the specified file (transfer from the server to the
+ client)
+ """
+ line = self.fs.fs2ftp(file)
+ try:
+ fd = self.run_as_current_user(self.fs.open, file, 'rb')
+ except IOError, err:
+ why = _strerror(err)
+ self.log('FAIL RETR "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ return
+
+ if self.restart_position:
+ # Make sure that the requested offset is valid (within the
+ # size of the file being resumed).
+ # According to RFC-1123 a 554 reply may result in case that
+ # the existing file cannot be repositioned as specified in
+ # the REST.
+ ok = 0
+ try:
+ assert not self.restart_position > self.fs.getsize(file)
+ fd.seek(self.restart_position)
+ ok = 1
+ except AssertionError:
+ why = "Invalid REST parameter"
+ except IOError, err:
+ why = _strerror(err)
+ self.restart_position = 0
+ if not ok:
+ self.respond('554 %s' %why)
+ self.log('FAIL RETR "%s". %s.' %(line, why))
+ return
+ self.log('OK RETR "%s". Download starting.' %line)
+ producer = FileProducer(fd, self.current_type)
+ self.push_dtp_data(producer, isproducer=True, file=fd)
+
+ def ftp_STOR(self, file, mode='w'):
+ """Store a file (transfer from the client to the server)."""
+ # A resume could occur in case of APPE or REST commands.
+ # In that case we have to open file object in different ways:
+ # STOR: mode = 'w'
+ # APPE: mode = 'a'
+ # REST: mode = 'r+' (to permit seeking on file object)
+ if 'a' in mode:
+ cmd = 'APPE'
+ else:
+ cmd = 'STOR'
+ line = self.fs.fs2ftp(file)
+ if self.restart_position:
+ mode = 'r+'
+ try:
+ fd = self.run_as_current_user(self.fs.open, file, mode + 'b')
+ except IOError, err:
+ why = _strerror(err)
+ self.log('FAIL %s "%s". %s.' %(cmd, line, why))
+ self.respond('550 %s.' %why)
+ return
+
+ if self.restart_position:
+ # Make sure that the requested offset is valid (within the
+ # size of the file being resumed).
+ # According to RFC-1123 a 554 reply may result in case
+ # that the existing file cannot be repositioned as
+ # specified in the REST.
+ ok = 0
+ try:
+ assert not self.restart_position > self.fs.getsize(file)
+ fd.seek(self.restart_position)
+ ok = 1
+ except AssertionError:
+ why = "Invalid REST parameter"
+ except IOError, err:
+ why = _strerror(err)
+ self.restart_position = 0
+ if not ok:
+ self.respond('554 %s' %why)
+ self.log('FAIL %s "%s". %s.' %(cmd, line, why))
+ return
+
+ self.log('OK %s "%s". Upload starting.' %(cmd, line))
+ if self.data_channel is not None:
+ self.respond("125 Data connection already open. Transfer starting.")
+ self.data_channel.file_obj = fd
+ self.data_channel.enable_receiving(self.current_type)
+ else:
+ self.respond("150 File status okay. About to open data connection.")
+ self._in_dtp_queue = fd
+
+
+ def ftp_STOU(self, line):
+ """Store a file on the server with a unique name."""
+ # Note 1: RFC-959 prohibited STOU parameters, but this
+ # prohibition is obsolete.
+ # Note 2: 250 response wanted by RFC-959 has been declared
+ # incorrect in RFC-1123 that wants 125/150 instead.
+ # Note 3: RFC-1123 also provided an exact output format
+ # defined to be as follow:
+ # > 125 FILE: pppp
+ # ...where pppp represents the unique path name of the
+ # file that will be written.
+
+ # watch for STOU preceded by REST, which makes no sense.
+ if self.restart_position:
+ self.respond("450 Can't STOU while REST request is pending.")
+ return
+
+ if line:
+ basedir, prefix = os.path.split(self.fs.ftp2fs(line))
+ prefix = prefix + '.'
+ else:
+ basedir = self.fs.ftp2fs(self.fs.cwd)
+ prefix = 'ftpd.'
+ try:
+ fd = self.run_as_current_user(self.fs.mkstemp, prefix=prefix,
+ dir=basedir)
+ except IOError, err:
+ # hitted the max number of tries to find out file with
+ # unique name
+ if err.errno == errno.EEXIST:
+ why = 'No usable unique file name found'
+ # something else happened
+ else:
+ why = _strerror(err)
+ self.respond("450 %s." %why)
+ self.log('FAIL STOU "%s". %s.' %(self.fs.ftpnorm(line), why))
+ return
+
+ if not self.authorizer.has_perm(self.username, 'w', fd.name):
+ try:
+ fd.close()
+ self.run_as_current_user(self.fs.remove, fd.name)
+ except os.error:
+ pass
+ self.log('FAIL STOU "%s". Not enough privileges'
+ %self.fs.ftpnorm(line))
+ self.respond("550 Can't STOU: not enough privileges.")
+ return
+
+ # now just acts like STOR except that restarting isn't allowed
+ filename = os.path.basename(fd.name)
+ self.log('OK STOU "%s". Upload starting.' %filename)
+ if self.data_channel is not None:
+ self.respond("125 FILE: %s" %filename)
+ self.data_channel.file_obj = fd
+ self.data_channel.enable_receiving(self.current_type)
+ else:
+ self.respond("150 FILE: %s" %filename)
+ self._in_dtp_queue = fd
+
+
+ def ftp_APPE(self, file):
+ """Append data to an existing file on the server."""
+ # watch for APPE preceded by REST, which makes no sense.
+ if self.restart_position:
+ self.respond("550 Can't APPE while REST request is pending.")
+ else:
+ self.ftp_STOR(file, mode='a')
+
+ def ftp_REST(self, line):
+ """Restart a file transfer from a previous mark."""
+ try:
+ marker = int(line)
+ if marker < 0:
+ raise ValueError
+ except (ValueError, OverflowError):
+ self.respond("501 Invalid parameter.")
+ else:
+ self.respond("350 Restarting at position %s. " \
+ "Now use RETR/STOR for resuming." %marker)
+ self.log("OK REST %s." %marker)
+ self.restart_position = marker
+
+ def ftp_ABOR(self, line):
+ """Abort the current data transfer."""
+
+ # ABOR received while no data channel exists
+ if (self.data_server is None) and (self.data_channel is None):
+ resp = "225 No transfer to abort."
+ else:
+ # a PASV was received but connection wasn't made yet
+ if self.data_server is not None:
+ self.data_server.close()
+ self.data_server = None
+ resp = "225 ABOR command successful; data channel closed."
+
+ # If a data transfer is in progress the server must first
+ # close the data connection, returning a 426 reply to
+ # indicate that the transfer terminated abnormally, then it
+ # must send a 226 reply, indicating that the abort command
+ # was successfully processed.
+ # If no data has been transmitted we just respond with 225
+ # indicating that no transfer was in progress.
+ if self.data_channel is not None:
+ if self.data_channel.transfer_in_progress():
+ self.data_channel.close()
+ self.data_channel = None
+ self.respond("426 Connection closed; transfer aborted.")
+ self.log("OK ABOR. Transfer aborted, data channel closed.")
+ resp = "226 ABOR command successful."
+ else:
+ self.data_channel.close()
+ self.data_channel = None
+ self.log("OK ABOR. Data channel closed.")
+ resp = "225 ABOR command successful; data channel closed."
+ self.respond(resp)
+
+
+ # --- authentication
+
+ def ftp_USER(self, line):
+ """Set the username for the current session."""
+ # we always treat anonymous user as lower-case string.
+ if line.lower() == "anonymous":
+ line = "anonymous"
+
+ # RFC-959 specifies a 530 response to the USER command if the
+ # username is not valid. If the username is valid is required
+ # ftpd returns a 331 response instead. In order to prevent a
+ # malicious client from determining valid usernames on a server,
+ # it is suggested by RFC-2577 that a server always return 331 to
+ # the USER command and then reject the combination of username
+ # and password for an invalid username when PASS is provided later.
+ if not self.authenticated:
+ self.respond('331 Username ok, send password.')
+ else:
+ # a new USER command could be entered at any point in order
+ # to change the access control flushing any user, password,
+ # and account information already supplied and beginning the
+ # login sequence again.
+ self.flush_account()
+ msg = 'Previous account information was flushed'
+ self.log('OK USER "%s". %s.' %(line, msg))
+ self.respond('331 %s, send password.' %msg)
+ self.username = line
+
+ def ftp_PASS(self, line):
+ """Check username's password against the authorizer."""
+ if self.authenticated:
+ self.respond("503 User already authenticated.")
+ return
+ if not self.username:
+ self.respond("503 Login with USER first.")
+ return
+
+ def auth_failed(msg="Authentication failed."):
+ if not self._closed:
+ self.attempted_logins += 1
+ if self.attempted_logins >= self.max_login_attempts:
+ msg = "530 " + msg + " Disconnecting."
+ self.respond(msg)
+ self.log(msg)
+ self.close_when_done()
+ else:
+ self.respond("530 " + msg)
+ self.log(msg)
+ self.sleeping = False
+
+ # username ok
+ if self.authorizer.has_user(self.username):
+ if self.username == 'anonymous' \
+ or self.authorizer.validate_authentication(self.username, line):
+ msg_login = self.authorizer.get_msg_login(self.username)
+ if len(msg_login) <= 75:
+ self.respond('230 %s' %msg_login)
+ else:
+ self.push("230-%s\r\n" %msg_login)
+ self.respond("230 ")
+
+ self.authenticated = True
+ self.password = line
+ self.attempted_logins = 0
+ self.fs.root = self.authorizer.get_home_dir(self.username)
+ self.log("User %s logged in." %self.username)
+ else:
+ CallLater(5, auth_failed)
+ self.username = ""
+ self.sleeping = True
+ # wrong username
+ else:
+ if self.username.lower() == 'anonymous':
+ CallLater(5, auth_failed, "Anonymous access not allowed.")
+ else:
+ CallLater(5, auth_failed)
+ self.username = ""
+ self.sleeping = True
+
+ def ftp_REIN(self, line):
+ """Reinitialize user's current session."""
+ # From RFC-959:
+ # REIN command terminates a USER, flushing all I/O and account
+ # information, except to allow any transfer in progress to be
+ # completed. All parameters are reset to the default settings
+ # and the control connection is left open. This is identical
+ # to the state in which a user finds himself immediately after
+ # the control connection is opened.
+ self.log("OK REIN. Flushing account information.")
+ self.flush_account()
+ # Note: RFC-959 erroneously mention "220" as the correct response
+ # code to be given in this case, but this is wrong...
+ self.respond("230 Ready for new user.")
+
+
+ # --- filesystem operations
+
+ def ftp_PWD(self, line):
+ """Return the name of the current working directory to the client."""
+ self.respond('257 "%s" is the current directory.' %self.fs.cwd)
+
+ def ftp_CWD(self, path):
+ """Change the current working directory."""
+ line = self.fs.fs2ftp(path)
+ try:
+ self.run_as_current_user(self.fs.chdir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL CWD "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK CWD "%s".' %self.fs.cwd)
+ self.respond('250 "%s" is the current directory.' %self.fs.cwd)
+
+ def ftp_CDUP(self, line):
+ """Change into the parent directory."""
+ # Note: RFC-959 says that code 200 is required but it also says
+ # that CDUP uses the same codes as CWD.
+ self.ftp_CWD('..')
+
+ def ftp_SIZE(self, path):
+ """Return size of file in a format suitable for using with
+ RESTart as defined in RFC-3659.
+
+ Implementation note:
+ properly handling the SIZE command when TYPE ASCII is used would
+ require to scan the entire file to perform the ASCII translation
+ logic (file.read().replace(os.linesep, '\r\n')) and then
+ calculating the len of such data which may be different than
+ the actual size of the file on the server. Considering that
+ calculating such result could be very resource-intensive it
+ could be easy for a malicious client to try a DoS attack, thus
+ we do not perform the ASCII translation.
+
+ However, clients in general should not be resuming downloads in
+ ASCII mode. Resuming downloads in binary mode is the recommended
+ way as specified in RFC-3659.
+ """
+ line = self.fs.fs2ftp(path)
+ if self.fs.isdir(path):
+ why = "%s is not retrievable" %line
+ self.log('FAIL SIZE "%s". %s.' %(line, why))
+ self.respond("550 %s." %why)
+ return
+ try:
+ size = self.run_as_current_user(self.fs.getsize, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL SIZE "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.respond("213 %s" %size)
+ self.log('OK SIZE "%s".' %line)
+
+ def ftp_MDTM(self, path):
+ """Return last modification time of file to the client as an ISO
+ 3307 style timestamp (YYYYMMDDHHMMSS) as defined in RFC-3659.
+ """
+ line = self.fs.fs2ftp(path)
+ if not self.fs.isfile(self.fs.realpath(path)):
+ why = "%s is not retrievable" %line
+ self.log('FAIL MDTM "%s". %s.' %(line, why))
+ self.respond("550 %s." %why)
+ return
+ try:
+ lmt = self.run_as_current_user(self.fs.getmtime, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL MDTM "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ lmt = time.strftime("%Y%m%d%H%M%S", time.localtime(lmt))
+ self.respond("213 %s" %lmt)
+ self.log('OK MDTM "%s".' %line)
+
+ def ftp_MKD(self, path):
+ """Create the specified directory."""
+ line = self.fs.fs2ftp(path)
+ try:
+ self.run_as_current_user(self.fs.mkdir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL MKD "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK MKD "%s".' %line)
+ self.respond("257 Directory created.")
+
+ def ftp_RMD(self, path):
+ """Remove the specified directory."""
+ line = self.fs.fs2ftp(path)
+ if self.fs.realpath(path) == self.fs.realpath(self.fs.root):
+ msg = "Can't remove root directory."
+ self.respond("550 %s" %msg)
+ self.log('FAIL MKD "/". %s' %msg)
+ return
+ try:
+ self.run_as_current_user(self.fs.rmdir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL RMD "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK RMD "%s".' %line)
+ self.respond("250 Directory removed.")
+
+ def ftp_DELE(self, path):
+ """Delete the specified file."""
+ line = self.fs.fs2ftp(path)
+ try:
+ self.run_as_current_user(self.fs.remove, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL DELE "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK DELE "%s".' %line)
+ self.respond("250 File removed.")
+
+ def ftp_RNFR(self, path):
+ """Rename the specified (only the source name is specified
+ here, see RNTO command)"""
+ if not self.fs.lexists(path):
+ self.respond("550 No such file or directory.")
+ elif self.fs.realpath(path) == self.fs.realpath(self.fs.root):
+ self.respond("550 Can't rename the home directory.")
+ else:
+ self.fs.rnfr = path
+ self.respond("350 Ready for destination name.")
+
+ def ftp_RNTO(self, path):
+ """Rename file (destination name only, source is specified with
+ RNFR).
+ """
+ if not self.fs.rnfr:
+ self.respond("503 Bad sequence of commands: use RNFR first.")
+ return
+ src = self.fs.rnfr
+ self.fs.rnfr = None
+ try:
+ self.run_as_current_user(self.fs.rename, src, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL RNFR/RNTO "%s ==> %s". %s.' \
+ %(self.fs.fs2ftp(src), self.fs.fs2ftp(path), why))
+ self.respond('550 %s.' %why)
+ else:
+ self.log('OK RNFR/RNTO "%s ==> %s".' \
+ %(self.fs.fs2ftp(src), self.fs.fs2ftp(path)))
+ self.respond("250 Renaming ok.")
+
+
+ # --- others
+
+ def ftp_TYPE(self, line):
+ """Set current type data type to binary/ascii"""
+ line = line.upper()
+ if line in ("A", "AN", "A N"):
+ self.respond("200 Type set to: ASCII.")
+ self.current_type = 'a'
+ elif line in ("I", "L8", "L 8"):
+ self.respond("200 Type set to: Binary.")
+ self.current_type = 'i'
+ else:
+ self.respond('504 Unsupported type "%s".' %line)
+
+ def ftp_STRU(self, line):
+ """Set file structure (obsolete)."""
+ # obsolete (backward compatibility with older ftp clients)
+ if line in ('f','F'):
+ self.respond('200 File transfer structure set to: F.')
+ else:
+ self.respond('504 Unimplemented STRU type.')
+
+ def ftp_MODE(self, line):
+ """Set data transfer mode (obsolete)"""
+ # obsolete (backward compatibility with older ftp clients)
+ if line in ('s', 'S'):
+ self.respond('200 Transfer mode set to: S')
+ else:
+ self.respond('504 Unimplemented MODE type.')
+
+ def ftp_STAT(self, path):
+ """Return statistics about current ftp session. If an argument
+ is provided return directory listing over command channel.
+
+ Implementation note:
+
+ RFC-959 does not explicitly mention globbing but many FTP
+ servers do support it as a measure of convenience for FTP
+ clients and users.
+
+ In order to search for and match the given globbing expression,
+ the code has to search (possibly) many directories, examine
+ each contained filename, and build a list of matching files in
+ memory. Since this operation can be quite intensive, both CPU-
+ and memory-wise, we do not support globbing.
+ """
+ # return STATus information about ftpd
+ if not path:
+ s = []
+ s.append('Connected to: %s:%s' %self.socket.getsockname()[:2])
+ if self.authenticated:
+ s.append('Logged in as: %s' %self.username)
+ else:
+ if not self.username:
+ s.append("Waiting for username.")
+ else:
+ s.append("Waiting for password.")
+ if self.current_type == 'a':
+ type = 'ASCII'
+ else:
+ type = 'Binary'
+ s.append("TYPE: %s; STRUcture: File; MODE: Stream" %type)
+ if self.data_server is not None:
+ s.append('Passive data channel waiting for connection.')
+ elif self.data_channel is not None:
+ bytes_sent = self.data_channel.tot_bytes_sent
+ bytes_recv = self.data_channel.tot_bytes_received
+ s.append('Data connection open:')
+ s.append('Total bytes sent: %s' %bytes_sent)
+ s.append('Total bytes received: %s' %bytes_recv)
+ else:
+ s.append('Data connection closed.')
+
+ self.push('211-FTP server status:\r\n')
+ self.push(''.join([' %s\r\n' %item for item in s]))
+ self.respond('211 End of status.')
+ # return directory LISTing over the command channel
+ else:
+ line = self.fs.fs2ftp(path)
+ try:
+ iterator = self.run_as_current_user(self.fs.get_list_dir, path)
+ except OSError, err:
+ why = _strerror(err)
+ self.log('FAIL STAT "%s". %s.' %(line, why))
+ self.respond('550 %s.' %why)
+ else:
+ self.push('213-Status of "%s":\r\n' %line)
+ self.push_with_producer(BufferedIteratorProducer(iterator))
+ self.respond('213 End of status.')
+
+ def ftp_FEAT(self, line):
+ """List all new features supported as defined in RFC-2398."""
+ features = ['EPRT','EPSV','MDTM','MLSD','REST STREAM','SIZE','TVFS']
+ s = ''
+ for fact in self._available_facts:
+ if fact in self._current_facts:
+ s += fact + '*;'
+ else:
+ s += fact + ';'
+ features.append('MLST ' + s)
+ features.sort()
+ self.push("211-Features supported:\r\n")
+ self.push("".join([" %s\r\n" %x for x in features]))
+ self.respond('211 End FEAT.')
+
+ def ftp_OPTS(self, line):
+ """Specify options for FTP commands as specified in RFC-2389."""
+ try:
+ assert (not line.count(' ') > 1), 'Invalid number of arguments'
+ if ' ' in line:
+ cmd, arg = line.split(' ')
+ assert (';' in arg), 'Invalid argument'
+ else:
+ cmd, arg = line, ''
+ # actually the only command able to accept options is MLST
+ assert (cmd.upper() == 'MLST'), 'Unsupported command "%s"' %cmd
+ except AssertionError, err:
+ self.respond('501 %s.' %err)
+ else:
+ facts = [x.lower() for x in arg.split(';')]
+ self._current_facts = [x for x in facts if x in self._available_facts]
+ f = ''.join([x + ';' for x in self._current_facts])
+ self.respond('200 MLST OPTS ' + f)
+
+ def ftp_NOOP(self, line):
+ """Do nothing."""
+ self.respond("200 I successfully done nothin'.")
+
+ def ftp_SYST(self, line):
+ """Return system type (always returns UNIX type: L8)."""
+ # This command is used to find out the type of operating system
+ # at the server. The reply shall have as its first word one of
+ # the system names listed in RFC-943.
+ # Since that we always return a "/bin/ls -lA"-like output on
+ # LIST we prefer to respond as if we would on Unix in any case.
+ self.respond("215 UNIX Type: L8")
+
+ def ftp_ALLO(self, line):
+ """Allocate bytes for storage (obsolete)."""
+ # obsolete (always respond with 202)
+ self.respond("202 No storage allocation necessary.")
+
+ def ftp_HELP(self, line):
+ """Return help text to the client."""
+ if line:
+ line = line.upper()
+ if line in proto_cmds:
+ self.respond("214 %s" %proto_cmds[line].help)
+ else:
+ self.respond("501 Unrecognized command.")
+ else:
+ # provide a compact list of recognized commands
+ def formatted_help():
+ cmds = []
+ keys = proto_cmds.keys()
+ keys.sort()
+ while keys:
+ elems = tuple((keys[0:8]))
+ cmds.append(' %-6s' * len(elems) %elems + '\r\n')
+ del keys[0:8]
+ return ''.join(cmds)
+
+ self.push("214-The following commands are recognized:\r\n")
+ self.push(formatted_help())
+ self.respond("214 Help command successful.")
+
+
+ # --- support for deprecated cmds
+
+ # RFC-1123 requires that the server treat XCUP, XCWD, XMKD, XPWD
+ # and XRMD commands as synonyms for CDUP, CWD, MKD, LIST and RMD.
+ # Such commands are obsoleted but some ftp clients (e.g. Windows
+ # ftp.exe) still use them.
+
+ def ftp_XCUP(self, line):
+ """Change to the parent directory. Synonym for CDUP. Deprecated."""
+ self.ftp_CDUP(line)
+
+ def ftp_XCWD(self, line):
+ """Change the current working directory. Synonym for CWD. Deprecated."""
+ self.ftp_CWD(line)
+
+ def ftp_XMKD(self, line):
+ """Create the specified directory. Synonym for MKD. Deprecated."""
+ self.ftp_MKD(line)
+
+ def ftp_XPWD(self, line):
+ """Return the current working directory. Synonym for PWD. Deprecated."""
+ self.ftp_PWD(line)
+
+ def ftp_XRMD(self, line):
+ """Remove the specified directory. Synonym for RMD. Deprecated."""
+ self.ftp_RMD(line)
+
+
+class FTPServer(asyncore.dispatcher):
+ """This class is an asyncore.disptacher subclass. It creates a FTP
+ socket listening on <address>, dispatching the requests to a <handler>
+ (typically FTPHandler class).
+
+ Depending on the type of address specified IPv4 or IPv6 connections
+ (or both, depending from the underlying system) will be accepted.
+
+ All relevant session information is stored in class attributes
+ described below.
+ Overriding them is strongly recommended to avoid running out of
+ file descriptors (DoS)!
+
+ - (int) max_cons:
+ number of maximum simultaneous connections accepted (defaults
+ to 0 == unlimited).
+
+ - (int) max_cons_per_ip:
+ number of maximum connections accepted for the same IP address
+ (defaults to 0 == unlimited).
+ """
+
+ max_cons = 0
+ max_cons_per_ip = 0
+
+ def __init__(self, address, handler):
+ """Initiate the FTP server opening listening on address.
+
+ - (tuple) address: the host:port pair on which the command
+ channel will listen.
+
+ - (classobj) handler: the handler class to use.
+ """
+ asyncore.dispatcher.__init__(self)
+ self.handler = handler
+ self.ip_map = []
+ host, port = address
+
+ # AF_INET or AF_INET6 socket
+ # Get the correct address family for our host (allows IPv6 addresses)
+ try:
+ info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
+ socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
+ except socket.gaierror:
+ # Probably a DNS issue. Assume IPv4.
+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.set_reuse_addr()
+ self.bind((host, port))
+ else:
+ for res in info:
+ af, socktype, proto, canonname, sa = res
+ try:
+ self.create_socket(af, socktype)
+ self.set_reuse_addr()
+ self.bind(sa)
+ except socket.error, msg:
+ if self.socket:
+ self.socket.close()
+ self.socket = None
+ continue
+ break
+ if not self.socket:
+ raise socket.error, msg
+ self.listen(5)
+
+ def set_reuse_addr(self):
+ # Overridden for convenience. Avoid to reuse address on Windows.
+ if (os.name in ('nt', 'ce')) or (sys.platform == 'cygwin'):
+ return
+ asyncore.dispatcher.set_reuse_addr(self)
+
+ def serve_forever(self, timeout=1, use_poll=False, map=None, count=None):
+ """A wrap around asyncore.loop(); starts the asyncore polling
+ loop including running the scheduler.
+ The arguments are the same expected by original asyncore.loop()
+ function.
+ """
+ if map is None:
+ map = asyncore.socket_map
+ # backward compatibility for python versions < 2.4
+ if not hasattr(self, '_map'):
+ self._map = self.handler._map = map
+
+ if use_poll and hasattr(asyncore.select, 'poll'):
+ poll_fun = asyncore.poll2
+ else:
+ poll_fun = asyncore.poll
+
+ if count is None:
+ log("Serving FTP on %s:%s" %self.socket.getsockname()[:2])
+ try:
+ while map or _tasks:
+ if map:
+ poll_fun(timeout, map)
+ if _tasks:
+ _scheduler()
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ log("Shutting down FTP server.")
+ self.close_all()
+ else:
+ while (map or _tasks) and count > 0:
+ if map:
+ poll_fun(timeout, map)
+ if _tasks:
+ _scheduler()
+ count = count - 1
+
+ def handle_accept(self):
+ """Called when remote client initiates a connection."""
+ sock_obj, addr = self.accept()
+ log("[]%s:%s Connected." %addr[:2])
+
+ handler = self.handler(sock_obj, self)
+ ip = addr[0]
+ self.ip_map.append(ip)
+
+ # For performance and security reasons we should always set a
+ # limit for the number of file descriptors that socket_map
+ # should contain. When we're running out of such limit we'll
+ # use the last available channel for sending a 421 response
+ # to the client before disconnecting it.
+ if self.max_cons:
+ if len(self._map) > self.max_cons:
+ handler.handle_max_cons()
+ return
+
+ # accept only a limited number of connections from the same
+ # source address.
+ if self.max_cons_per_ip:
+ if self.ip_map.count(ip) > self.max_cons_per_ip:
+ handler.handle_max_cons_per_ip()
+ return
+
+ handler.handle()
+
+ def writable(self):
+ return 0
+
+ def handle_error(self):
+ """Called to handle any uncaught exceptions."""
+ try:
+ raise
+ except (KeyboardInterrupt, SystemExit, asyncore.ExitNow):
+ raise
+ logerror(traceback.format_exc())
+ self.close()
+
+ def close_all(self, map=None, ignore_all=False):
+ """Stop serving; close all existent connections disconnecting
+ clients.
+
+ - (dict) map:
+ A dictionary whose items are the channels to close.
+ If map is omitted, the default asyncore.socket_map is used.
+
+ - (bool) ignore_all:
+ having it set to False results in raising exception in case
+ of unexpected errors.
+
+ Implementation note:
+
+ Instead of using the current asyncore.close_all() function
+ which only close sockets, we iterate over all existent channels
+ calling close() method for each one of them, avoiding memory
+ leaks.
+
+ This is how asyncore.close_all() function should work in
+ Python 2.6.
+ """
+ if map is None:
+ map = self._map
+ for x in map.values():
+ try:
+ x.close()
+ except OSError, x:
+ if x[0] == errno.EBADF:
+ pass
+ elif not ignore_all:
+ raise
+ except (asyncore.ExitNow, KeyboardInterrupt, SystemExit):
+ raise
+ except:
+ if not ignore_all:
+ raise
+ map.clear()
+
+
+def test():
+ # cmd line usage (provide a read-only anonymous ftp server):
+ # python -m pyftpdlib.FTPServer
+ authorizer = DummyAuthorizer()
+ authorizer.add_anonymous(os.getcwd())
+ FTPHandler.authorizer = authorizer
+ address = ('', 21)
+ ftpd = FTPServer(address, FTPHandler)
+ ftpd.serve_forever()
+
+if __name__ == '__main__':
+ test()
diff --git a/third_party/pyftpdlib/setup.py b/third_party/pyftpdlib/setup.py
new file mode 100644
index 0000000..752acd8
--- /dev/null
+++ b/third_party/pyftpdlib/setup.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+# setup.py
+
+"""pyftpdlib installer.
+
+To install pyftpdlib just open a command shell and run:
+> python setup.py install
+"""
+
+from distutils.core import setup
+
+long_descr = """\
+Python FTP server library, based on asyncore framework, provides
+an high-level portable interface to easily write asynchronous
+FTP servers with Python."""
+
+setup(
+ name='pyftpdlib',
+ version="0.5.0",
+ description='High-level asynchronous FTP server library',
+ long_description=long_descr,
+ license='MIT License',
+ platforms='Platform Independent',
+ author="Giampaolo Rodola'",
+ author_email='g.rodola@gmail.com',
+ url='http://code.google.com/p/pyftpdlib/',
+ download_url='http://pyftpdlib.googlecode.com/files/pyftpdlib-0.5.0.tar.gz',
+ packages=['pyftpdlib'],
+ classifiers=[
+ 'Development Status :: 4 - Beta',
+ 'Environment :: Console',
+ 'Intended Audience :: Developers',
+ 'Intended Audience :: System Administrators',
+ 'License :: OSI Approved :: MIT License',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python',
+ 'Topic :: Internet :: File Transfer Protocol (FTP)',
+ 'Topic :: Software Development :: Libraries :: Python Modules'
+ ],
+ )
diff --git a/third_party/pyftpdlib/test/test_ftpd.py b/third_party/pyftpdlib/test/test_ftpd.py
new file mode 100644
index 0000000..ffd8557
--- /dev/null
+++ b/third_party/pyftpdlib/test/test_ftpd.py
@@ -0,0 +1,1623 @@
+#!/usr/bin/env python
+# test_ftpd.py
+
+# ======================================================================
+# Copyright (C) 2007 Giampaolo Rodola' <g.rodola@gmail.com>
+#
+# 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, and that the name of
+# Giampaolo Rodola' not be used in advertising or publicity pertaining to
+# distribution of the software without specific, written prior
+# permission.
+#
+# Giampaolo Rodola' DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
+# NO EVENT Giampaolo Rodola' BE LIABLE FOR ANY SPECIAL, INDIRECT OR
+# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
+# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
+# NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
+# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+# ======================================================================
+
+
+# This test suite has been run successfully on the following systems:
+#
+# -----------------------------------------------------------
+# System | Python version
+# -----------------------------------------------------------
+# Linux Ubuntu 2.6.20-15 | 2.4, 2.5
+# Linux Kubuntu 8.04 32 & 64 bits | 2.5.2
+# Linux Debian 2.4.27-2-386 | 2.3.5
+# Windows XP prof SP3 | 2.3, 2.4, 2.5, 2.6-RC2
+# Windows Vista Ultimate 64 bit | 2.5.1
+# Windows Vista Business 32 bit | 2.5.1
+# Windows Server 2008 64bit | 2.5.1
+# Windows Mobile 6.1 | PythonCE 2.5
+# OS X 10.4.10 | 2.3, 2.4, 2.5
+# FreeBSD 7.0 | 2.4, 2.5
+# -----------------------------------------------------------
+
+
+import threading
+import unittest
+import socket
+import os
+import time
+import re
+import tempfile
+import ftplib
+import random
+import warnings
+import sys
+
+from pyftpdlib import ftpserver
+
+
+__release__ = 'pyftpdlib 0.5.0'
+
+# Attempt to use IP rather than hostname (test suite will run a lot faster)
+try:
+ HOST = socket.gethostbyname('localhost')
+except socket.error:
+ HOST = 'localhost'
+USER = 'user'
+PASSWD = '12345'
+HOME = os.getcwd()
+try:
+ from test.test_support import TESTFN
+except ImportError:
+ TESTFN = 'temp-fname'
+TESTFN2 = TESTFN + '2'
+TESTFN3 = TESTFN + '3'
+
+def try_address(host, port=0):
+ """Try to bind a daemon on the given host:port and return True
+ if that has been possible."""
+ try:
+ ftpserver.FTPServer((host, port), None)
+ except socket.error:
+ return False
+ else:
+ return True
+
+SUPPORTS_IPV4 = try_address('127.0.0.1')
+SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1')
+
+
+class TestAbstractedFS(unittest.TestCase):
+ """Test for conversion utility methods of AbstractedFS class."""
+
+ def test_ftpnorm(self):
+ # Tests for ftpnorm method.
+ ae = self.assertEquals
+ fs = ftpserver.AbstractedFS()
+
+ fs.cwd = '/'
+ ae(fs.ftpnorm(''), '/')
+ ae(fs.ftpnorm('/'), '/')
+ ae(fs.ftpnorm('.'), '/')
+ ae(fs.ftpnorm('..'), '/')
+ ae(fs.ftpnorm('a'), '/a')
+ ae(fs.ftpnorm('/a'), '/a')
+ ae(fs.ftpnorm('/a/'), '/a')
+ ae(fs.ftpnorm('a/..'), '/')
+ ae(fs.ftpnorm('a/b'), '/a/b')
+ ae(fs.ftpnorm('a/b/..'), '/a')
+ ae(fs.ftpnorm('a/b/../..'), '/')
+ fs.cwd = '/sub'
+ ae(fs.ftpnorm(''), '/sub')
+ ae(fs.ftpnorm('/'), '/')
+ ae(fs.ftpnorm('.'), '/sub')
+ ae(fs.ftpnorm('..'), '/')
+ ae(fs.ftpnorm('a'), '/sub/a')
+ ae(fs.ftpnorm('a/'), '/sub/a')
+ ae(fs.ftpnorm('a/..'), '/sub')
+ ae(fs.ftpnorm('a/b'), '/sub/a/b')
+ ae(fs.ftpnorm('a/b/'), '/sub/a/b')
+ ae(fs.ftpnorm('a/b/..'), '/sub/a')
+ ae(fs.ftpnorm('a/b/../..'), '/sub')
+ ae(fs.ftpnorm('a/b/../../..'), '/')
+ ae(fs.ftpnorm('//'), '/') # UNC paths must be collapsed
+
+ def test_ftp2fs(self):
+ # Tests for ftp2fs method.
+ ae = self.assertEquals
+ fs = ftpserver.AbstractedFS()
+ join = lambda x, y: os.path.join(x, y.replace('/', os.sep))
+
+ def goforit(root):
+ fs.root = root
+ fs.cwd = '/'
+ ae(fs.ftp2fs(''), root)
+ ae(fs.ftp2fs('/'), root)
+ ae(fs.ftp2fs('.'), root)
+ ae(fs.ftp2fs('..'), root)
+ ae(fs.ftp2fs('a'), join(root, 'a'))
+ ae(fs.ftp2fs('/a'), join(root, 'a'))
+ ae(fs.ftp2fs('/a/'), join(root, 'a'))
+ ae(fs.ftp2fs('a/..'), root)
+ ae(fs.ftp2fs('a/b'), join(root, r'a/b'))
+ ae(fs.ftp2fs('/a/b'), join(root, r'a/b'))
+ ae(fs.ftp2fs('/a/b/..'), join(root, 'a'))
+ ae(fs.ftp2fs('/a/b/../..'), root)
+ fs.cwd = '/sub'
+ ae(fs.ftp2fs(''), join(root, 'sub'))
+ ae(fs.ftp2fs('/'), root)
+ ae(fs.ftp2fs('.'), join(root, 'sub'))
+ ae(fs.ftp2fs('..'), root)
+ ae(fs.ftp2fs('a'), join(root, 'sub/a'))
+ ae(fs.ftp2fs('a/'), join(root, 'sub/a'))
+ ae(fs.ftp2fs('a/..'), join(root, 'sub'))
+ ae(fs.ftp2fs('a/b'), join(root, 'sub/a/b'))
+ ae(fs.ftp2fs('a/b/..'), join(root, 'sub/a'))
+ ae(fs.ftp2fs('a/b/../..'), join(root, 'sub'))
+ ae(fs.ftp2fs('a/b/../../..'), root)
+ ae(fs.ftp2fs('//a'), join(root, 'a')) # UNC paths must be collapsed
+
+ if os.sep == '\\':
+ goforit(r'C:\dir')
+ goforit('C:\\')
+ # on DOS-derived filesystems (e.g. Windows) this is the same
+ # as specifying the current drive directory (e.g. 'C:\\')
+ goforit('\\')
+ elif os.sep == '/':
+ goforit('/home/user')
+ goforit('/')
+ else:
+ # os.sep == ':'? Don't know... let's try it anyway
+ goforit(os.getcwd())
+
+ def test_fs2ftp(self):
+ # Tests for fs2ftp method.
+ ae = self.assertEquals
+ fs = ftpserver.AbstractedFS()
+ join = lambda x, y: os.path.join(x, y.replace('/', os.sep))
+
+ def goforit(root):
+ fs.root = root
+ ae(fs.fs2ftp(root), '/')
+ ae(fs.fs2ftp(join(root, '/')), '/')
+ ae(fs.fs2ftp(join(root, '.')), '/')
+ ae(fs.fs2ftp(join(root, '..')), '/') # can't escape from root
+ ae(fs.fs2ftp(join(root, 'a')), '/a')
+ ae(fs.fs2ftp(join(root, 'a/')), '/a')
+ ae(fs.fs2ftp(join(root, 'a/..')), '/')
+ ae(fs.fs2ftp(join(root, 'a/b')), '/a/b')
+ ae(fs.fs2ftp(join(root, 'a/b')), '/a/b')
+ ae(fs.fs2ftp(join(root, 'a/b/..')), '/a')
+ ae(fs.fs2ftp(join(root, '/a/b/../..')), '/')
+ fs.cwd = '/sub'
+ ae(fs.fs2ftp(join(root, 'a/')), '/a')
+
+ if os.sep == '\\':
+ goforit(r'C:\dir')
+ goforit('C:\\')
+ # on DOS-derived filesystems (e.g. Windows) this is the same
+ # as specifying the current drive directory (e.g. 'C:\\')
+ goforit('\\')
+ fs.root = r'C:\dir'
+ ae(fs.fs2ftp('C:\\'), '/')
+ ae(fs.fs2ftp('D:\\'), '/')
+ ae(fs.fs2ftp('D:\\dir'), '/')
+ elif os.sep == '/':
+ goforit('/')
+ assert os.path.realpath('/__home/user') == '/__home/user', \
+ 'Test skipped (symlinks not allowed).'
+ goforit('/__home/user')
+ fs.root = '/__home/user'
+ ae(fs.fs2ftp('/__home'), '/')
+ ae(fs.fs2ftp('/'), '/')
+ ae(fs.fs2ftp('/__home/userx'), '/')
+ else:
+ # os.sep == ':'? Don't know... let's try it anyway
+ goforit(os.getcwd())
+
+ def test_validpath(self):
+ # Tests for validpath method.
+ fs = ftpserver.AbstractedFS()
+ fs.root = HOME
+ self.failUnless(fs.validpath(HOME))
+ self.failUnless(fs.validpath(HOME + '/'))
+ self.failIf(fs.validpath(HOME + 'xxx'))
+
+ if hasattr(os, 'symlink'):
+ # Tests for validpath on systems supporting symbolic links.
+
+ def _safe_remove(self, path):
+ # convenience function for removing temporary files
+ try:
+ os.remove(path)
+ except os.error:
+ pass
+
+ def test_validpath_validlink(self):
+ # Test validpath by issuing a symlink pointing to a path
+ # inside the root directory.
+ fs = ftpserver.AbstractedFS()
+ fs.root = HOME
+ try:
+ open(TESTFN, 'w')
+ os.symlink(TESTFN, TESTFN2)
+ self.failUnless(fs.validpath(TESTFN))
+ finally:
+ self._safe_remove(TESTFN)
+ self._safe_remove(TESTFN2)
+
+ def test_validpath_external_symlink(self):
+ # Test validpath by issuing a symlink pointing to a path
+ # outside the root directory.
+ fs = ftpserver.AbstractedFS()
+ fs.root = HOME
+ try:
+ # tempfile should create our file in /tmp directory
+ # which should be outside the user root. If it is not
+ # we just skip the test.
+ file = tempfile.NamedTemporaryFile()
+ if HOME == os.path.dirname(file.name):
+ return
+ os.symlink(file.name, TESTFN)
+ self.failIf(fs.validpath(TESTFN))
+ finally:
+ self._safe_remove(TESTFN)
+ file.close()
+
+
+class TestDummyAuthorizer(unittest.TestCase):
+ """Tests for DummyAuthorizer class."""
+
+ # temporarily change warnings to exceptions for the purposes of testing
+ def setUp(self):
+ self.tempdir = tempfile.mkdtemp(dir=HOME)
+ self.subtempdir = tempfile.mkdtemp(dir=os.path.join(HOME, self.tempdir))
+ self.tempfile = open(os.path.join(self.tempdir, TESTFN), 'w').name
+ self.subtempfile = open(os.path.join(self.subtempdir, TESTFN), 'w').name
+ warnings.filterwarnings("error")
+
+ def tearDown(self):
+ os.remove(self.tempfile)
+ os.remove(self.subtempfile)
+ os.rmdir(self.subtempdir)
+ os.rmdir(self.tempdir)
+ warnings.resetwarnings()
+
+ def assertRaisesWithMsg(self, excClass, msg, callableObj, *args, **kwargs):
+ try:
+ callableObj(*args, **kwargs)
+ except excClass, why:
+ if str(why) == msg:
+ return
+ raise self.failureException("%s != %s" %(str(why), msg))
+ else:
+ if hasattr(excClass,'__name__'): excName = excClass.__name__
+ else: excName = str(excClass)
+ raise self.failureException, "%s not raised" % excName
+
+ def test_common_methods(self):
+ auth = ftpserver.DummyAuthorizer()
+ # create user
+ auth.add_user(USER, PASSWD, HOME)
+ auth.add_anonymous(HOME)
+ # check credentials
+ self.failUnless(auth.validate_authentication(USER, PASSWD))
+ self.failIf(auth.validate_authentication(USER, 'wrongpwd'))
+ # remove them
+ auth.remove_user(USER)
+ auth.remove_user('anonymous')
+ # raise exc if user does not exists
+ self.assertRaises(KeyError, auth.remove_user, USER)
+ # raise exc if path does not exist
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ 'No such directory: "%s"' %'?:\\',
+ auth.add_user, USER, PASSWD, '?:\\')
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ 'No such directory: "%s"' %'?:\\',
+ auth.add_anonymous, '?:\\')
+ # raise exc if user already exists
+ auth.add_user(USER, PASSWD, HOME)
+ auth.add_anonymous(HOME)
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ 'User "%s" already exists' %USER,
+ auth.add_user, USER, PASSWD, HOME)
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ 'User "anonymous" already exists',
+ auth.add_anonymous, HOME)
+ auth.remove_user(USER)
+ auth.remove_user('anonymous')
+ # raise on wrong permission
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ 'No such permission "?"',
+ auth.add_user, USER, PASSWD, HOME, perm='?')
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ 'No such permission "?"',
+ auth.add_anonymous, HOME, perm='?')
+ # expect warning on write permissions assigned to anonymous user
+ for x in "adfmw":
+ self.assertRaisesWithMsg(RuntimeWarning,
+ "Write permissions assigned to anonymous user.",
+ auth.add_anonymous, HOME, perm=x)
+
+ def test_override_perm_interface(self):
+ auth = ftpserver.DummyAuthorizer()
+ auth.add_user(USER, PASSWD, HOME, perm='elr')
+ # raise exc if user does not exists
+ self.assertRaises(KeyError, auth.override_perm, USER+'w', HOME, 'elr')
+ # raise exc if path does not exist or it's not a directory
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ 'No such directory: "%s"' %'?:\\',
+ auth.override_perm, USER, '?:\\', 'elr')
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ 'No such directory: "%s"' %self.tempfile,
+ auth.override_perm, USER, self.tempfile, 'elr')
+ # raise on wrong permission
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ 'No such permission "?"', auth.override_perm,
+ USER, HOME, perm='?')
+ # expect warning on write permissions assigned to anonymous user
+ auth.add_anonymous(HOME)
+ for p in "adfmw":
+ self.assertRaisesWithMsg(RuntimeWarning,
+ "Write permissions assigned to anonymous user.",
+ auth.override_perm, 'anonymous', HOME, p)
+ # raise on attempt to override home directory permissions
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ "Can't override home directory permissions",
+ auth.override_perm, USER, HOME, perm='w')
+ # raise on attempt to override a path escaping home directory
+ if os.path.dirname(HOME) != HOME:
+ self.assertRaisesWithMsg(ftpserver.AuthorizerError,
+ "Path escapes user home directory",
+ auth.override_perm, USER,
+ os.path.dirname(HOME), perm='w')
+ # try to re-set an overridden permission
+ auth.override_perm(USER, self.tempdir, perm='w')
+ auth.override_perm(USER, self.tempdir, perm='wr')
+
+ def test_override_perm_recursive_paths(self):
+ auth = ftpserver.DummyAuthorizer()
+ auth.add_user(USER, PASSWD, HOME, perm='elr')
+ self.assert_(auth.has_perm(USER, 'w', self.tempdir) is False)
+ auth.override_perm(USER, self.tempdir, perm='w', recursive=True)
+ self.assert_(auth.has_perm(USER, 'w', HOME) is False)
+ self.assert_(auth.has_perm(USER, 'w', self.tempdir) is True)
+ self.assert_(auth.has_perm(USER, 'w', self.tempfile) is True)
+ self.assert_(auth.has_perm(USER, 'w', self.subtempdir) is True)
+ self.assert_(auth.has_perm(USER, 'w', self.subtempfile) is True)
+
+ self.assert_(auth.has_perm(USER, 'w', HOME + '@') is False)
+ self.assert_(auth.has_perm(USER, 'w', self.tempdir + '@') is False)
+ path = os.path.join(self.tempdir + '@', os.path.basename(self.tempfile))
+ self.assert_(auth.has_perm(USER, 'w', path) is False)
+ # test case-sensitiveness
+ if (os.name in ('nt', 'ce')) or (sys.platform == 'cygwin'):
+ self.assert_(auth.has_perm(USER, 'w', self.tempdir.upper()) is True)
+
+ def test_override_perm_not_recursive_paths(self):
+ auth = ftpserver.DummyAuthorizer()
+ auth.add_user(USER, PASSWD, HOME, perm='elr')
+ self.assert_(auth.has_perm(USER, 'w', self.tempdir) is False)
+ auth.override_perm(USER, self.tempdir, perm='w')
+ self.assert_(auth.has_perm(USER, 'w', HOME) is False)
+ self.assert_(auth.has_perm(USER, 'w', self.tempdir) is True)
+ self.assert_(auth.has_perm(USER, 'w', self.tempfile) is True)
+ self.assert_(auth.has_perm(USER, 'w', self.subtempdir) is False)
+ self.assert_(auth.has_perm(USER, 'w', self.subtempfile) is False)
+
+ self.assert_(auth.has_perm(USER, 'w', HOME + '@') is False)
+ self.assert_(auth.has_perm(USER, 'w', self.tempdir + '@') is False)
+ path = os.path.join(self.tempdir + '@', os.path.basename(self.tempfile))
+ self.assert_(auth.has_perm(USER, 'w', path) is False)
+ # test case-sensitiveness
+ if (os.name in ('nt', 'ce')) or (sys.platform == 'cygwin'):
+ self.assert_(auth.has_perm(USER, 'w', self.tempdir.upper()) is True)
+
+
+class TestCallLater(unittest.TestCase):
+ """Tests for CallLater class."""
+
+ def setUp(self):
+ for task in ftpserver._tasks:
+ if not task.cancelled:
+ task.cancel()
+ del ftpserver._tasks[:]
+
+ def scheduler(self, timeout=0.01, count=100):
+ while ftpserver._tasks and count > 0:
+ ftpserver._scheduler()
+ count -= 1
+ time.sleep(timeout)
+
+ def test_interface(self):
+ fun = lambda: 0
+ self.assertRaises(AssertionError, ftpserver.CallLater, -1, fun)
+ x = ftpserver.CallLater(3, fun)
+ self.assertRaises(AssertionError, x.delay, -1)
+ self.assert_(x.cancelled is False)
+ x.cancel()
+ self.assert_(x.cancelled is True)
+ self.assertRaises(AssertionError, x.call)
+ self.assertRaises(AssertionError, x.reset)
+ self.assertRaises(AssertionError, x.delay, 2)
+ self.assertRaises(AssertionError, x.cancel)
+
+ def test_order(self):
+ l = []
+ fun = lambda x: l.append(x)
+ for x in [0.05, 0.04, 0.03, 0.02, 0.01]:
+ ftpserver.CallLater(x, fun, x)
+ self.scheduler()
+ self.assertEqual(l, [0.01, 0.02, 0.03, 0.04, 0.05])
+
+ def test_delay(self):
+ l = []
+ fun = lambda x: l.append(x)
+ ftpserver.CallLater(0.01, fun, 0.01).delay(0.07)
+ ftpserver.CallLater(0.02, fun, 0.02).delay(0.08)
+ ftpserver.CallLater(0.03, fun, 0.03)
+ ftpserver.CallLater(0.04, fun, 0.04)
+ ftpserver.CallLater(0.05, fun, 0.05)
+ ftpserver.CallLater(0.06, fun, 0.06).delay(0.001)
+ self.scheduler()
+ self.assertEqual(l, [0.06, 0.03, 0.04, 0.05, 0.01, 0.02])
+
+ def test_reset(self):
+ # will fail on such systems where time.time() does not provide
+ # time with a better precision than 1 second.
+ l = []
+ fun = lambda x: l.append(x)
+ ftpserver.CallLater(0.01, fun, 0.01)
+ ftpserver.CallLater(0.02, fun, 0.02)
+ ftpserver.CallLater(0.03, fun, 0.03)
+ x = ftpserver.CallLater(0.04, fun, 0.04)
+ ftpserver.CallLater(0.05, fun, 0.05)
+ time.sleep(0.1)
+ x.reset()
+ self.scheduler()
+ self.assertEqual(l, [0.01, 0.02, 0.03, 0.05, 0.04])
+
+ def test_cancel(self):
+ l = []
+ fun = lambda x: l.append(x)
+ ftpserver.CallLater(0.01, fun, 0.01).cancel()
+ ftpserver.CallLater(0.02, fun, 0.02)
+ ftpserver.CallLater(0.03, fun, 0.03)
+ ftpserver.CallLater(0.04, fun, 0.04)
+ ftpserver.CallLater(0.05, fun, 0.05).cancel()
+ self.scheduler()
+ self.assertEqual(l, [0.02, 0.03, 0.04])
+
+
+class TestFtpAuthentication(unittest.TestCase):
+ "test: USER, PASS, REIN."
+
+ def setUp(self):
+ self.server = FTPd()
+ self.server.start()
+ self.client = ftplib.FTP()
+ self.client.connect(self.server.host, self.server.port)
+ self.f1 = open(TESTFN, 'w+b')
+ self.f2 = open(TESTFN2, 'w+b')
+
+ def tearDown(self):
+ self.client.close()
+ self.server.stop()
+ if not self.f1.closed:
+ self.f1.close()
+ if not self.f2.closed:
+ self.f2.close()
+ os.remove(TESTFN)
+ os.remove(TESTFN2)
+
+ def test_auth_ok(self):
+ self.client.login(user=USER, passwd=PASSWD)
+
+ def test_anon_auth(self):
+ self.client.login(user='anonymous', passwd='anon@')
+ self.client.login(user='AnonYmoUs', passwd='anon@')
+ self.client.login(user='anonymous', passwd='')
+
+ # Commented after delayed response on wrong credentials has been
+ # introduced because tests take too much to complete.
+
+## def test_auth_failed(self):
+## self.assertRaises(ftplib.error_perm, self.client.login, USER, 'wrong')
+## self.assertRaises(ftplib.error_perm, self.client.login, 'wrong', PASSWD)
+## self.assertRaises(ftplib.error_perm, self.client.login, 'wrong', 'wrong')
+
+## def test_max_auth(self):
+## self.assertRaises(ftplib.error_perm, self.client.login, USER, 'wrong')
+## self.assertRaises(ftplib.error_perm, self.client.login, USER, 'wrong')
+## self.assertRaises(ftplib.error_perm, self.client.login, USER, 'wrong')
+## # If authentication fails for 3 times ftpd disconnects the
+## # client. We can check if that happens by using self.client.sendcmd()
+## # on the 'dead' socket object. If socket object is really
+## # closed it should be raised a socket.error exception (Windows)
+## # or a EOFError exception (Linux).
+## self.assertRaises((socket.error, EOFError), self.client.sendcmd, '')
+
+ def test_rein(self):
+ self.client.login(user=USER, passwd=PASSWD)
+ self.client.sendcmd('rein')
+ # user not authenticated, error response expected
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'pwd')
+ # by logging-in again we should be able to execute a
+ # file-system command
+ self.client.login(user=USER, passwd=PASSWD)
+ self.client.sendcmd('pwd')
+
+ def test_rein_during_transfer(self):
+ self.client.login(user=USER, passwd=PASSWD)
+ data = 'abcde12345' * 100000
+ self.f1.write(data)
+ self.f1.close()
+
+ self.client.voidcmd('TYPE I')
+ conn = self.client.transfercmd('retr ' + TESTFN)
+ rein_sent = 0
+ while 1:
+ chunk = conn.recv(8192)
+ if not chunk:
+ break
+ self.f2.write(chunk)
+ if not rein_sent:
+ rein_sent = 1
+ # flush account, error response expected
+ self.client.sendcmd('rein')
+ self.assertRaises(ftplib.error_perm, self.client.dir)
+
+ # a 226 response is expected once tranfer finishes
+ self.assertEqual(self.client.voidresp()[:3], '226')
+ # account is still flushed, error response is still expected
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd,
+ 'size ' + TESTFN)
+ # by logging-in again we should be able to execute a
+ # filesystem command
+ self.client.login(user=USER, passwd=PASSWD)
+ self.client.sendcmd('pwd')
+ self.f2.seek(0)
+ self.assertEqual(hash(data), hash (self.f2.read()))
+
+ def test_user(self):
+ # Test USER while already authenticated and no transfer
+ # is in progress.
+ self.client.login(user=USER, passwd=PASSWD)
+ self.client.sendcmd('user ' + USER) # authentication flushed
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'pwd')
+ self.client.sendcmd('pass ' + PASSWD)
+ self.client.sendcmd('pwd')
+
+ def test_user_on_transfer(self):
+ # Test USER while already authenticated and a transfer is
+ # in progress.
+ self.client.login(user=USER, passwd=PASSWD)
+ data = 'abcde12345' * 100000
+ self.f1.write(data)
+ self.f1.close()
+
+ self.client.voidcmd('TYPE I')
+ conn = self.client.transfercmd('retr ' + TESTFN)
+ rein_sent = 0
+ while 1:
+ chunk = conn.recv(8192)
+ if not chunk:
+ break
+ self.f2.write(chunk)
+ # stop transfer while it isn't finished yet
+ if not rein_sent:
+ rein_sent = 1
+ # flush account, expect an error response
+ self.client.sendcmd('user ' + USER)
+ self.assertRaises(ftplib.error_perm, self.client.dir)
+
+ # a 226 response is expected once tranfer finishes
+ self.assertEqual(self.client.voidresp()[:3], '226')
+ # account is still flushed, error response is still expected
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'pwd')
+ # by logging-in again we should be able to execute a
+ # filesystem command
+ self.client.sendcmd('pass ' + PASSWD)
+ self.client.sendcmd('pwd')
+ self.f2.seek(0)
+ self.assertEqual(hash(data), hash (self.f2.read()))
+
+
+class TestFtpDummyCmds(unittest.TestCase):
+ "test: TYPE, STRU, MODE, NOOP, SYST, ALLO, HELP"
+
+ def setUp(self):
+ self.server = FTPd()
+ self.server.start()
+ self.client = ftplib.FTP()
+ self.client.connect(self.server.host, self.server.port)
+ self.client.login(USER, PASSWD)
+
+ def tearDown(self):
+ self.client.close()
+ self.server.stop()
+
+ def test_type(self):
+ self.client.sendcmd('type a')
+ self.client.sendcmd('type i')
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'type ?!?')
+
+ def test_stru(self):
+ self.client.sendcmd('stru f')
+ self.client.sendcmd('stru F')
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'stru ?!?')
+
+ def test_mode(self):
+ self.client.sendcmd('mode s')
+ self.client.sendcmd('mode S')
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'mode ?!?')
+
+ def test_noop(self):
+ self.client.sendcmd('noop')
+
+ def test_syst(self):
+ self.client.sendcmd('syst')
+
+ def test_allo(self):
+ self.client.sendcmd('allo x')
+
+ def test_quit(self):
+ self.client.sendcmd('quit')
+
+ def test_help(self):
+ self.client.sendcmd('help')
+ cmd = random.choice(ftpserver.proto_cmds.keys())
+ self.client.sendcmd('help %s' %cmd)
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'help ?!?')
+
+ def test_rest(self):
+ # test error conditions only;
+ # restored data-transfer is tested later
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'rest')
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'rest str')
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'rest -1')
+
+ def test_opts_feat(self):
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'opts mlst bad_fact')
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'opts mlst type ;')
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'opts not_mlst')
+ # utility function which used for extracting the MLST "facts"
+ # string from the FEAT response
+ def mlst():
+ resp = self.client.sendcmd('feat')
+ return re.search(r'^\s*MLST\s+(\S+)$', resp, re.MULTILINE).group(1)
+ # we rely on "type", "perm", "size", and "modify" facts which
+ # are those available on all platforms
+ self.failUnless('type*;perm*;size*;modify*;' in mlst())
+ self.assertEqual(self.client.sendcmd('opts mlst type;'), '200 MLST OPTS type;')
+ self.assertEqual(self.client.sendcmd('opts mLSt TypE;'), '200 MLST OPTS type;')
+ self.failUnless('type*;perm;size;modify;' in mlst())
+
+ self.assertEqual(self.client.sendcmd('opts mlst'), '200 MLST OPTS ')
+ self.failUnless(not '*' in mlst())
+
+ self.assertEqual(self.client.sendcmd('opts mlst fish;cakes;'), '200 MLST OPTS ')
+ self.failUnless(not '*' in mlst())
+ self.assertEqual(self.client.sendcmd('opts mlst fish;cakes;type;'), \
+ '200 MLST OPTS type;')
+ self.failUnless('type*;perm;size;modify;' in mlst())
+
+
+class TestFtpCmdsSemantic(unittest.TestCase):
+
+ arg_cmds = ('allo','appe','dele','eprt','mdtm','mode','mkd','opts','port',
+ 'rest','retr','rmd','rnfr','rnto','size', 'stor', 'stru','type',
+ 'user','xmkd','xrmd')
+
+ def setUp(self):
+ self.server = FTPd()
+ self.server.start()
+ self.client = ftplib.FTP()
+ self.client.connect(self.server.host, self.server.port)
+ self.client.login(USER, PASSWD)
+
+ def tearDown(self):
+ self.client.close()
+ self.server.stop()
+
+ def test_arg_cmds(self):
+ # test commands requiring an argument
+ expected = "501 Syntax error: command needs an argument."
+ for cmd in self.arg_cmds:
+ self.client.putcmd(cmd)
+ resp = self.client.getmultiline()
+ self.assertEqual(resp, expected)
+
+ def test_no_arg_cmds(self):
+ # test commands accepting no arguments
+ expected = "501 Syntax error: command does not accept arguments."
+ for cmd in ('abor','cdup','feat','noop','pasv','pwd','quit','rein',
+ 'syst','xcup','xpwd'):
+ self.client.putcmd(cmd + ' arg')
+ resp = self.client.getmultiline()
+ self.assertEqual(resp, expected)
+
+ def test_auth_cmds(self):
+ # test those commands requiring client to be authenticated
+ expected = "530 Log in with USER and PASS first."
+ self.client.sendcmd('rein')
+ for cmd in ftpserver.proto_cmds:
+ cmd = cmd.lower()
+ if cmd in ('feat','help','noop','user','pass','stat','syst','quit'):
+ continue
+ if cmd in self.arg_cmds:
+ cmd = cmd + ' arg'
+ self.client.putcmd(cmd)
+ resp = self.client.getmultiline()
+ self.assertEqual(resp, expected)
+
+ def test_no_auth_cmds(self):
+ # test those commands that do not require client to be authenticated
+ self.client.sendcmd('rein')
+ for cmd in ('feat','help','noop','stat','syst'):
+ self.client.sendcmd(cmd)
+ # STAT provided with an argument is equal to LIST hence not allowed
+ # if not authenticated
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'stat /')
+ self.client.sendcmd('quit')
+
+
+class TestFtpFsOperations(unittest.TestCase):
+ "test: PWD, CWD, CDUP, SIZE, RNFR, RNTO, DELE, MKD, RMD, MDTM, STAT"
+
+ def setUp(self):
+ self.server = FTPd()
+ self.server.start()
+ self.client = ftplib.FTP()
+ self.client.connect(self.server.host, self.server.port)
+ self.client.login(USER, PASSWD)
+ self.tempfile = os.path.basename(open(TESTFN, 'w+b').name)
+ self.tempdir = os.path.basename(tempfile.mktemp(dir=HOME))
+ os.mkdir(self.tempdir)
+
+ def tearDown(self):
+ self.client.close()
+ self.server.stop()
+ if os.path.exists(self.tempfile):
+ os.remove(self.tempfile)
+ if os.path.exists(self.tempdir):
+ os.rmdir(self.tempdir)
+
+ def test_cwd(self):
+ self.client.cwd(self.tempdir)
+ self.assertEqual(self.client.pwd(), '/' + self.tempdir)
+ self.assertRaises(ftplib.error_perm, self.client.cwd, 'subtempdir')
+ # cwd provided with no arguments is supposed to move us to the
+ # root directory
+ self.client.sendcmd('cwd')
+ self.assertEqual(self.client.pwd(), '/')
+
+ def test_pwd(self):
+ self.assertEqual(self.client.pwd(), '/')
+ self.client.cwd(self.tempdir)
+ self.assertEqual(self.client.pwd(), '/' + self.tempdir)
+
+ def test_cdup(self):
+ self.client.cwd(self.tempdir)
+ self.assertEqual(self.client.pwd(), '/' + self.tempdir)
+ self.client.sendcmd('cdup')
+ self.assertEqual(self.client.pwd(), '/')
+ # make sure we can't escape from root directory
+ self.client.sendcmd('cdup')
+ self.assertEqual(self.client.pwd(), '/')
+
+ def test_mkd(self):
+ tempdir = os.path.basename(tempfile.mktemp(dir=HOME))
+ self.client.mkd(tempdir)
+ # make sure we can't create directories which already exist
+ # (probably not really necessary);
+ # let's use a try/except statement to avoid leaving behind
+ # orphaned temporary directory in the event of a test failure.
+ try:
+ self.client.mkd(tempdir)
+ except ftplib.error_perm:
+ os.rmdir(tempdir) # ok
+ else:
+ self.fail('ftplib.error_perm not raised.')
+
+ def test_rmd(self):
+ self.client.rmd(self.tempdir)
+ self.assertRaises(ftplib.error_perm, self.client.rmd, self.tempfile)
+ # make sure we can't remove the root directory
+ self.assertRaises(ftplib.error_perm, self.client.rmd, '/')
+
+ def test_dele(self):
+ self.client.delete(self.tempfile)
+ self.assertRaises(ftplib.error_perm, self.client.delete, self.tempdir)
+
+ def test_rnfr_rnto(self):
+ # rename file
+ tempname = os.path.basename(tempfile.mktemp(dir=HOME))
+ self.client.rename(self.tempfile, tempname)
+ self.client.rename(tempname, self.tempfile)
+ # rename dir
+ tempname = os.path.basename(tempfile.mktemp(dir=HOME))
+ self.client.rename(self.tempdir, tempname)
+ self.client.rename(tempname, self.tempdir)
+ # rnfr/rnto over non-existing paths
+ bogus = os.path.basename(tempfile.mktemp(dir=HOME))
+ self.assertRaises(ftplib.error_perm, self.client.rename, bogus, '/x')
+ self.assertRaises(ftplib.error_perm, self.client.rename, self.tempfile, '/')
+ # make sure we can't rename root directory
+ self.assertRaises(ftplib.error_perm, self.client.rename, '/', '/x')
+
+ def test_mdtm(self):
+ self.client.sendcmd('mdtm ' + self.tempfile)
+ # make sure we can't use mdtm against directories
+ try:
+ self.client.sendcmd('mdtm ' + self.tempdir)
+ except ftplib.error_perm, err:
+ self.failUnless("not retrievable" in str(err))
+ else:
+ self.fail('Exception not raised')
+
+ def test_size(self):
+ self.client.size(self.tempfile)
+ # make sure we can't use size against directories
+ try:
+ self.client.sendcmd('size ' + self.tempdir)
+ except ftplib.error_perm, err:
+ self.failUnless("not retrievable" in str(err))
+ else:
+ self.fail('Exception not raised')
+
+
+class TestFtpRetrieveData(unittest.TestCase):
+ "test: RETR, REST, LIST, NLST, argumented STAT"
+
+ def setUp(self):
+ self.server = FTPd()
+ self.server.start()
+ self.client = ftplib.FTP()
+ self.client.connect(self.server.host, self.server.port)
+ self.client.login(USER, PASSWD)
+ self.f1 = open(TESTFN, 'w+b')
+ self.f2 = open(TESTFN2, 'w+b')
+
+ def tearDown(self):
+ self.client.close()
+ self.server.stop()
+ if not self.f1.closed:
+ self.f1.close()
+ if not self.f2.closed:
+ self.f2.close()
+ os.remove(TESTFN)
+ os.remove(TESTFN2)
+
+ def test_retr(self):
+ data = 'abcde12345' * 100000
+ self.f1.write(data)
+ self.f1.close()
+ self.client.retrbinary("retr " + TESTFN, self.f2.write)
+ self.f2.seek(0)
+ self.assertEqual(hash(data), hash(self.f2.read()))
+
+ def test_restore_on_retr(self):
+ data = 'abcde12345' * 100000
+ fname_1 = os.path.basename(self.f1.name)
+ self.f1.write(data)
+ self.f1.close()
+
+ # look at ftplib.FTP.retrbinary method to understand this mess
+ self.client.voidcmd('TYPE I')
+ conn = self.client.transfercmd('retr ' + fname_1)
+ chunk = conn.recv(len(data) / 2)
+ self.f2.write(chunk)
+ conn.close()
+ # transfer wasn't finished yet so we expect a 426 response
+ self.assertRaises(ftplib.error_temp, self.client.voidresp)
+
+ # resuming transfer by using a marker value greater than the
+ # file size stored on the server should result in an error
+ # on retr (RFC-1123)
+ file_size = self.client.size(fname_1)
+ self.client.sendcmd('rest %s' %((file_size + 1)))
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'retr ' + fname_1)
+
+ # test resume
+ self.client.sendcmd('rest %s' %len(chunk))
+ self.client.retrbinary("retr " + fname_1, self.f2.write)
+ self.f2.seek(0)
+ self.assertEqual(hash(data), hash (self.f2.read()))
+
+ def _test_listing_cmds(self, cmd):
+ """Tests common to LIST NLST and MLSD commands."""
+ # assume that no argument has the same meaning of "/"
+ l1 = l2 = []
+ self.client.retrlines(cmd, l1.append)
+ self.client.retrlines(cmd + ' /', l2.append)
+ self.assertEqual(l1, l2)
+ if cmd.lower() != 'mlsd':
+ # if pathname is a file one line is expected
+ x = []
+ self.client.retrlines('%s ' %cmd + TESTFN, x.append)
+ self.assertEqual(len(x), 1)
+ self.failUnless(''.join(x).endswith(TESTFN))
+ # non-existent path, 550 response is expected
+ bogus = os.path.basename(tempfile.mktemp(dir=HOME))
+ self.assertRaises(ftplib.error_perm, self.client.retrlines,
+ '%s ' %cmd + bogus, lambda x: x)
+ # for an empty directory we excpect that the data channel is
+ # opened anyway and that no data is received
+ x = []
+ tempdir = os.path.basename(tempfile.mkdtemp(dir=HOME))
+ try:
+ self.client.retrlines('%s %s' %(cmd, tempdir), x.append)
+ self.assertEqual(x, [])
+ finally:
+ os.rmdir(tempdir)
+
+ def test_nlst(self):
+ # common tests
+ self._test_listing_cmds('nlst')
+
+ def test_list(self):
+ # common tests
+ self._test_listing_cmds('list')
+ # known incorrect pathname arguments (e.g. old clients) are
+ # expected to be treated as if pathname would be == '/'
+ l1 = l2 = l3 = l4 = l5 = []
+ self.client.retrlines('list /', l1.append)
+ self.client.retrlines('list -a', l2.append)
+ self.client.retrlines('list -l', l3.append)
+ self.client.retrlines('list -al', l4.append)
+ self.client.retrlines('list -la', l5.append)
+ tot = (l1, l2, l3, l4, l5)
+ for x in range(len(tot) - 1):
+ self.assertEqual(tot[x], tot[x+1])
+
+ def test_mlst(self):
+ # utility function for extracting the line of interest
+ mlstline = lambda cmd: self.client.voidcmd(cmd).split('\n')[1]
+
+ # the fact set must be preceded by a space
+ self.failUnless(mlstline('mlst').startswith(' '))
+ # where TVFS is supported, a fully qualified pathname is expected
+ self.failUnless(mlstline('mlst ' + TESTFN).endswith('/' + TESTFN))
+ self.failUnless(mlstline('mlst').endswith('/'))
+ # assume that no argument has the same meaning of "/"
+ self.assertEqual(mlstline('mlst'), mlstline('mlst /'))
+ # non-existent path
+ bogus = os.path.basename(tempfile.mktemp(dir=HOME))
+ self.assertRaises(ftplib.error_perm, mlstline, bogus)
+ # test file/dir notations
+ self.failUnless('type=dir' in mlstline('mlst'))
+ self.failUnless('type=file' in mlstline('mlst ' + TESTFN))
+ # let's add some tests for OPTS command
+ self.client.sendcmd('opts mlst type;')
+ self.assertEqual(mlstline('mlst'), ' type=dir; /')
+ # where no facts are present, two leading spaces before the
+ # pathname are required (RFC-3659)
+ self.client.sendcmd('opts mlst')
+ self.assertEqual(mlstline('mlst'), ' /')
+
+ def test_mlsd(self):
+ # common tests
+ self._test_listing_cmds('mlsd')
+ dir = os.path.basename(tempfile.mkdtemp(dir=HOME))
+ try:
+ try:
+ self.client.retrlines('mlsd ' + TESTFN, lambda x: x)
+ except ftplib.error_perm, resp:
+ # if path is a file a 501 response code is expected
+ self.assertEqual(str(resp)[0:3], "501")
+ else:
+ self.fail("Exception not raised")
+ finally:
+ os.rmdir(dir)
+
+ def test_stat(self):
+ # test STAT provided with argument which is equal to LIST
+ self.client.sendcmd('stat /')
+ self.client.sendcmd('stat ' + TESTFN)
+ self.client.putcmd('stat *')
+ resp = self.client.getmultiline()
+ self.assertEqual(resp, '550 Globbing not supported.')
+ bogus = os.path.basename(tempfile.mktemp(dir=HOME))
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'stat ' + bogus)
+
+
+class TestFtpAbort(unittest.TestCase):
+ "test: ABOR"
+
+ def setUp(self):
+ self.server = FTPd()
+ self.server.start()
+ self.client = ftplib.FTP()
+ self.client.connect(self.server.host, self.server.port)
+ self.client.login(USER, PASSWD)
+ self.f1 = open(TESTFN, 'w+b')
+ self.f2 = open(TESTFN2, 'w+b')
+
+ def tearDown(self):
+ self.client.close()
+ self.server.stop()
+ if not self.f1.closed:
+ self.f1.close()
+ if not self.f2.closed:
+ self.f2.close()
+ os.remove(self.f1.name)
+ os.remove(self.f2.name)
+
+ def test_abor_no_data(self):
+ # Case 1: ABOR while no data channel is opened: respond with 225.
+ resp = self.client.sendcmd('ABOR')
+ self.failUnlessEqual('225 No transfer to abort.', resp)
+
+ def test_abor_pasv(self):
+ # Case 2: user sends a PASV, a data-channel socket is listening
+ # but not connected, and ABOR is sent: close listening data
+ # socket, respond with 225.
+ self.client.makepasv()
+ respcode = self.client.sendcmd('ABOR')[:3]
+ self.failUnlessEqual('225', respcode)
+
+ def test_abor_port(self):
+ # Case 3: data channel opened with PASV or PORT, but ABOR sent
+ # before a data transfer has been started: close data channel,
+ # respond with 225
+ self.client.makeport()
+ respcode = self.client.sendcmd('ABOR')[:3]
+ self.failUnlessEqual('225', respcode)
+
+ def test_abor(self):
+ # Case 4: ABOR while a data transfer on DTP channel is in
+ # progress: close data channel, respond with 426, respond
+ # with 226.
+ data = 'abcde12345' * 100000
+ self.f1.write(data)
+ self.f1.close()
+
+ # this ugly loop construct is to simulate an interrupted
+ # transfer since ftplib doesn't like running storbinary()
+ # in a separate thread
+ self.client.voidcmd('TYPE I')
+ conn = self.client.transfercmd('retr ' + TESTFN)
+ chunk = conn.recv(len(data) / 2)
+ # stop transfer while it isn't finished yet
+ self.client.putcmd('ABOR')
+
+ # transfer isn't finished yet so ftpd should respond with 426
+ self.assertRaises(ftplib.error_temp, self.client.voidresp)
+
+ # transfer successfully aborted, so should now respond with a 226
+ self.failUnlessEqual('226', self.client.voidresp()[:3])
+
+ if hasattr(socket, 'MSG_OOB'):
+ def test_oob_abor(self):
+ # Send ABOR by following the RFC-959 directives of sending
+ # Telnet IP/Synch sequence as OOB data.
+ # On some systems like FreeBSD this happened to be a problem
+ # due to a different SO_OOBINLINE behavior.
+ # On some platforms (e.g. Python CE) the test may fail
+ # although the MSG_OOB constant is defined.
+ self.client.sock.sendall(chr(244), socket.MSG_OOB)
+ self.client.sock.sendall(chr(242), socket.MSG_OOB)
+ self.client.sock.sendall('abor\r\n')
+ self.client.sock.settimeout(1)
+ self.assertEqual(self.client.getresp()[:3], '225')
+
+
+class TestFtpStoreData(unittest.TestCase):
+ "test: STOR, STOU, APPE, REST"
+
+ def setUp(self):
+ self.server = FTPd()
+ self.server.start()
+ self.client = ftplib.FTP()
+ self.client.connect(self.server.host, self.server.port)
+ self.client.login(USER, PASSWD)
+ self.f1 = open(TESTFN, 'w+b')
+ self.f2 = open(TESTFN2, 'w+b')
+
+ def tearDown(self):
+ self.client.close()
+ self.server.stop()
+ if not self.f1.closed:
+ self.f1.close()
+ if not self.f2.closed:
+ self.f2.close()
+ os.remove(TESTFN)
+ os.remove(TESTFN2)
+
+ def test_stor(self):
+ # TESTFN3 is the remote file name
+ try:
+ data = 'abcde12345' * 100000
+ self.f1.write(data)
+ self.f1.seek(0)
+ self.client.storbinary('stor ' + TESTFN3, self.f1)
+ self.client.retrbinary('retr ' + TESTFN3, self.f2.write)
+ self.f2.seek(0)
+ self.assertEqual(hash(data), hash (self.f2.read()))
+ finally:
+ # we do not use os.remove because file could be still
+ # locked by ftpd thread
+ if os.path.exists(TESTFN3):
+ self.client.delete(TESTFN3)
+
+ def test_stou(self):
+ data = 'abcde12345' * 100000
+ self.f1.write(data)
+ self.f1.seek(0)
+
+ self.client.voidcmd('TYPE I')
+ # filename comes in as "1xx FILE: <filename>"
+ filename = self.client.sendcmd('stou').split('FILE: ')[1]
+ try:
+ sock = self.client.makeport()
+ conn, sockaddr = sock.accept()
+ while 1:
+ buf = self.f1.read(8192)
+ if not buf:
+ break
+ conn.sendall(buf)
+ conn.close()
+ # transfer finished, a 226 response is expected
+ self.client.voidresp()
+ self.client.retrbinary('retr ' + filename, self.f2.write)
+ self.f2.seek(0)
+ self.assertEqual(hash(data), hash (self.f2.read()))
+ finally:
+ # we do not use os.remove because file could be
+ # still locked by ftpd thread
+ if os.path.exists(filename):
+ self.client.delete(filename)
+
+ def test_stou_rest(self):
+ # watch for STOU preceded by REST, which makes no sense.
+ self.client.sendcmd('rest 10')
+ self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'stou')
+
+ def test_appe(self):
+ # TESTFN3 is the remote file name
+ try:
+ data1 = 'abcde12345' * 100000
+ self.f1.write(data1)
+ self.f1.seek(0)
+ self.client.storbinary('stor ' + TESTFN3, self.f1)
+
+ data2 = 'fghil67890' * 100000
+ self.f1.write(data2)
+ self.f1.seek(self.client.size(TESTFN3))
+ self.client.storbinary('appe ' + TESTFN3, self.f1)
+
+ self.client.retrbinary("retr " + TESTFN3, self.f2.write)
+ self.f2.seek(0)
+ self.assertEqual(hash(data1 + data2), hash (self.f2.read()))
+ finally:
+ # we do not use os.remove because file could be still
+ # locked by ftpd thread
+ if os.path.exists(TESTFN3):
+ self.client.delete(TESTFN3)
+
+ def test_appe_rest(self):
+ # watch for APPE preceded by REST, which makes no sense.
+ self.client.sendcmd('rest 10')
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'appe x')
+
+ def test_rest_on_stor(self):
+ # TESTFN3 is the remote file name
+ data = 'abcde12345' * 100000
+ self.f1.write(data)
+ self.f1.seek(0)
+
+ self.client.voidcmd('TYPE I')
+ conn = self.client.transfercmd('stor ' + TESTFN3)
+ bytes_sent = 0
+ while 1:
+ chunk = self.f1.read(8192)
+ conn.sendall(chunk)
+ bytes_sent += len(chunk)
+ # stop transfer while it isn't finished yet
+ if bytes_sent >= 524288: # 2^19
+ break
+ elif not chunk:
+ break
+ conn.close()
+ # transfer wasn't finished yet so we expect a 426 response
+ self.client.voidresp()
+
+ # resuming transfer by using a marker value greater than the
+ # file size stored on the server should result in an error
+ # on stor
+ file_size = self.client.size(TESTFN3)
+ self.assertEqual(file_size, bytes_sent)
+ self.client.sendcmd('rest %s' %((file_size + 1)))
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'stor ' + TESTFN3)
+
+ self.client.sendcmd('rest %s' %bytes_sent)
+ self.client.storbinary('stor ' + TESTFN3, self.f1)
+
+ self.client.retrbinary('retr ' + TESTFN3, self.f2.write)
+ self.f1.seek(0)
+ self.f2.seek(0)
+ self.assertEqual(hash(self.f1.read()), hash(self.f2.read()))
+ self.client.delete(TESTFN3)
+
+
+class TestTimeouts(unittest.TestCase):
+ """Test idle-timeout capabilities of control and data channels.
+ Some tests may fail on slow machines.
+ """
+
+ def _setUp(self, idle_timeout=300, data_timeout=300, pasv_timeout=30):
+ self.server = FTPd()
+ self.server.handler.timeout = idle_timeout
+ self.server.handler.dtp_handler.timeout = data_timeout
+ self.server.handler.passive_dtp.timeout = pasv_timeout
+ self.server.start()
+ self.client = ftplib.FTP()
+ self.client.connect(self.server.host, self.server.port)
+ self.client.login(USER, PASSWD)
+
+ def tearDown(self):
+ self.client.close()
+ self.server.handler.timeout = 300
+ self.server.handler.dtp_handler.timeout = 300
+ self.server.handler.passive_dtp.timeout = 30
+ self.server.stop()
+
+ def test_idle_timeout(self):
+ # Test control channel timeout. The client which does not send
+ # any command within the time specified in FTPHandler.timeout is
+ # supposed to be kicked off.
+ self._setUp(idle_timeout=0.1)
+ # fail if no msg is received within 1 second
+ self.client.sock.settimeout(1)
+ data = self.client.sock.recv(1024)
+ self.assertEqual(data, "421 Control connection timed out.\r\n")
+ # ensure client has been kicked off
+ self.assertRaises((socket.error, EOFError), self.client.sendcmd, 'noop')
+
+ def test_data_timeout(self):
+ # Test data channel timeout. The client which does not send
+ # or receive any data within the time specified in
+ # DTPHandler.timeout is supposed to be kicked off.
+ self._setUp(data_timeout=0.1)
+ addr = self.client.makepasv()
+ s = socket.socket()
+ s.connect(addr)
+ # fail if no msg is received within 1 second
+ self.client.sock.settimeout(1)
+ data = self.client.sock.recv(1024)
+ self.assertEqual(data, "421 Data connection timed out.\r\n")
+ # ensure client has been kicked off
+ self.assertRaises((socket.error, EOFError), self.client.sendcmd, 'noop')
+
+ def test_idle_data_timeout1(self):
+ # Tests that the control connection timeout is suspended while
+ # the data channel is opened
+ self._setUp(idle_timeout=0.1, data_timeout=0.2)
+ addr = self.client.makepasv()
+ s = socket.socket()
+ s.connect(addr)
+ # fail if no msg is received within 1 second
+ self.client.sock.settimeout(1)
+ data = self.client.sock.recv(1024)
+ self.assertEqual(data, "421 Data connection timed out.\r\n")
+ # ensure client has been kicked off
+ self.assertRaises((socket.error, EOFError), self.client.sendcmd, 'noop')
+
+ def test_idle_data_timeout2(self):
+ # Tests that the control connection timeout is restarted after
+ # data channel has been closed
+ self._setUp(idle_timeout=0.1, data_timeout=0.2)
+ addr = self.client.makepasv()
+ s = socket.socket()
+ s.connect(addr)
+ # close data channel
+ self.client.sendcmd('abor')
+ self.client.sock.settimeout(1)
+ data = self.client.sock.recv(1024)
+ self.assertEqual(data, "421 Control connection timed out.\r\n")
+ # ensure client has been kicked off
+ self.assertRaises((socket.error, EOFError), self.client.sendcmd, 'noop')
+
+ def test_pasv_timeout(self):
+ # Test pasv data channel timeout. The client which does not connect
+ # to the listening data socket within the time specified in
+ # PassiveDTP.timeout is supposed to receive a 421 response.
+ self._setUp(pasv_timeout=0.1)
+ self.client.makepasv()
+ # fail if no msg is received within 1 second
+ self.client.sock.settimeout(1)
+ data = self.client.sock.recv(1024)
+ self.assertEqual(data, "421 Passive data channel timed out.\r\n")
+ # client is not expected to be kicked off
+ self.client.sendcmd('noop')
+
+
+class TestMaxConnections(unittest.TestCase):
+ """Test maximum connections (FTPServer.max_cons)."""
+
+ def setUp(self):
+ self.server = FTPd()
+ self.server.server.max_cons = 3
+ self.server.start()
+
+ def tearDown(self):
+ self.server.server.max_cons = 0
+ self.server.stop()
+
+ def test_max_connections(self):
+ c1 = ftplib.FTP()
+ c2 = ftplib.FTP()
+ c3 = ftplib.FTP()
+ try:
+ c1.connect(self.server.host, self.server.port)
+ c2.connect(self.server.host, self.server.port)
+ self.assertRaises(ftplib.error_temp, c3.connect, self.server.host,
+ self.server.port)
+ # with passive data channel established
+ c2.close()
+ c1.login(USER, PASSWD)
+ c1.makepasv()
+ self.assertRaises(ftplib.error_temp, c2.connect, self.server.host,
+ self.server.port)
+ # with passive data socket waiting for connection
+ c1.login(USER, PASSWD)
+ c1.sendcmd('pasv')
+ self.assertRaises(ftplib.error_temp, c2.connect, self.server.host,
+ self.server.port)
+ # with active data channel established
+ c1.login(USER, PASSWD)
+ c1.makeport()
+ self.assertRaises(ftplib.error_temp, c2.connect, self.server.host,
+ self.server.port)
+ finally:
+ c1.close()
+ c2.close()
+ c3.close()
+
+
+class _TestNetworkProtocols(unittest.TestCase):
+ """Test PASV, EPSV, PORT and EPRT commands.
+
+ Do not use this class directly. Let TestIPv4Environment and
+ TestIPv6Environment classes use it instead.
+ """
+ HOST = HOST
+
+ def setUp(self):
+ self.server = FTPd(self.HOST)
+ self.server.start()
+ self.client = ftplib.FTP()
+ self.client.connect(self.server.host, self.server.port)
+ self.client.login(USER, PASSWD)
+ if self.client.af == socket.AF_INET:
+ self.proto = "1"
+ self.other_proto = "2"
+ else:
+ self.proto = "2"
+ self.other_proto = "1"
+
+ def tearDown(self):
+ self.client.close()
+ self.server.stop()
+
+ def cmdresp(self, cmd):
+ """Send a command and return response, also if the command failed."""
+ try:
+ return self.client.sendcmd(cmd)
+ except ftplib.Error, err:
+ return str(err)
+
+ def test_eprt(self):
+ # test wrong proto
+ try:
+ self.client.sendcmd('eprt |%s|%s|%s|' %(self.other_proto,
+ self.server.host, self.server.port))
+ except ftplib.error_perm, err:
+ self.assertEqual(str(err)[0:3], "522")
+ else:
+ self.fail("Exception not raised")
+
+ # test bad args
+ msg = "501 Invalid EPRT format."
+ # len('|') > 3
+ self.assertEqual(self.cmdresp('eprt ||||'), msg)
+ # len('|') < 3
+ self.assertEqual(self.cmdresp('eprt ||'), msg)
+ # port > 65535
+ self.assertEqual(self.cmdresp('eprt |%s|%s|65536|' %(self.proto,
+ self.HOST)), msg)
+ # port < 0
+ self.assertEqual(self.cmdresp('eprt |%s|%s|-1|' %(self.proto,
+ self.HOST)), msg)
+ # port < 1024
+ self.assertEqual(self.cmdresp('eprt |%s|%s|222|' %(self.proto,
+ self.HOST)), "501 Can't connect over a privileged port.")
+
+ # test connection
+ sock = socket.socket(self.client.af, socket.SOCK_STREAM)
+ sock.bind((self.client.sock.getsockname()[0], 0))
+ sock.listen(5)
+ sock.settimeout(2)
+ ip, port = sock.getsockname()[:2]
+ self.client.sendcmd('eprt |%s|%s|%s|' %(self.proto, ip, port))
+ try:
+ try:
+ sock.accept()
+ except socket.timeout:
+ self.fail("Server didn't connect to passive socket")
+ finally:
+ sock.close()
+
+ def test_epsv(self):
+ # test wrong proto
+ try:
+ self.client.sendcmd('epsv ' + self.other_proto)
+ except ftplib.error_perm, err:
+ self.assertEqual(str(err)[0:3], "522")
+ else:
+ self.fail("Exception not raised")
+
+ # test connection
+ for cmd in ('EPSV', 'EPSV ' + self.proto):
+ host, port = ftplib.parse229(self.client.sendcmd(cmd),
+ self.client.sock.getpeername())
+ s = socket.socket(self.client.af, socket.SOCK_STREAM)
+ s.settimeout(2)
+ try:
+ s.connect((host, port))
+ self.client.sendcmd('abor')
+ finally:
+ s.close()
+
+ def test_epsv_all(self):
+ self.client.sendcmd('epsv all')
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd, 'pasv')
+ self.assertRaises(ftplib.error_perm, self.client.sendport, self.HOST, 2000)
+ self.assertRaises(ftplib.error_perm, self.client.sendcmd,
+ 'eprt |%s|%s|%s|' %(self.proto, self.HOST, 2000))
+
+
+class TestIPv4Environment(_TestNetworkProtocols):
+ """Test PASV, EPSV, PORT and EPRT commands.
+
+ Runs tests contained in _TestNetworkProtocols class by using IPv4
+ plus some additional specific tests.
+ """
+ HOST = '127.0.0.1'
+
+ def test_port_v4(self):
+ # test connection
+ self.client.makeport()
+ self.client.sendcmd('abor')
+ # test bad arguments
+ ae = self.assertEqual
+ msg = "501 Invalid PORT format."
+ ae(self.cmdresp('port 127,0,0,1,1.1'), msg) # sep != ','
+ ae(self.cmdresp('port X,0,0,1,1,1'), msg) # value != int
+ ae(self.cmdresp('port 127,0,0,1,1,1,1'), msg) # len(args) > 6
+ ae(self.cmdresp('port 127,0,0,1'), msg) # len(args) < 6
+ ae(self.cmdresp('port 256,0,0,1,1,1'), msg) # oct > 255
+ ae(self.cmdresp('port 127,0,0,1,256,1'), msg) # port > 65535
+ ae(self.cmdresp('port 127,0,0,1,-1,0'), msg) # port < 0
+ msg = "501 Can't connect over a privileged port."
+ ae(self.cmdresp('port %s,1,1' %self.HOST.replace('.',',')),msg) # port < 1024
+ if "1.2.3.4" != self.HOST:
+ msg = "501 Can't connect to a foreign address."
+ ae(self.cmdresp('port 1,2,3,4,4,4'), msg)
+
+ def test_eprt_v4(self):
+ self.assertEqual(self.cmdresp('eprt |1|0.10.10.10|2222|'),
+ "501 Can't connect to a foreign address.")
+
+ def test_pasv_v4(self):
+ host, port = ftplib.parse227(self.client.sendcmd('pasv'))
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.settimeout(2)
+ try:
+ s.connect((host, port))
+ finally:
+ s.close()
+
+
+class TestIPv6Environment(_TestNetworkProtocols):
+ """Test PASV, EPSV, PORT and EPRT commands.
+
+ Runs tests contained in _TestNetworkProtocols class by using IPv6
+ plus some additional specific tests.
+ """
+ HOST = '::1'
+
+ def test_port_v6(self):
+ # 425 expected
+ self.assertRaises(ftplib.error_temp, self.client.sendport,
+ self.server.host, self.server.port)
+
+ def test_pasv_v6(self):
+ # 425 expected
+ self.assertRaises(ftplib.error_temp, self.client.sendcmd, 'pasv')
+
+ def test_eprt_v6(self):
+ self.assertEqual(self.cmdresp('eprt |2|::xxx|2222|'),
+ "501 Can't connect to a foreign address.")
+
+
+class FTPd(threading.Thread):
+ """A threaded FTP server used for running tests."""
+
+ def __init__(self, host=HOST, port=0, verbose=False):
+ threading.Thread.__init__(self)
+ self.active = False
+ if not verbose:
+ ftpserver.log = ftpserver.logline = lambda x: x
+ self.authorizer = ftpserver.DummyAuthorizer()
+ self.authorizer.add_user(USER, PASSWD, HOME, perm='elradfmw') # full perms
+ self.authorizer.add_anonymous(HOME)
+ self.handler = ftpserver.FTPHandler
+ self.handler.authorizer = self.authorizer
+ self.server = ftpserver.FTPServer((host, port), self.handler)
+ self.host, self.port = self.server.socket.getsockname()[:2]
+ self.active_lock = threading.Lock()
+
+ def start(self):
+ assert not self.active
+ self.__flag = threading.Event()
+ threading.Thread.start(self)
+ self.__flag.wait()
+
+ def run(self):
+ self.active = True
+ self.__flag.set()
+ while self.active:
+ self.active_lock.acquire()
+ self.server.serve_forever(timeout=0.001, count=1)
+ self.active_lock.release()
+ self.server.close_all(ignore_all=True)
+
+ def stop(self):
+ assert self.active
+ self.active = False
+ self.join()
+
+
+def remove_test_files():
+ "Convenience function for removing temporary test files"
+ for file in [TESTFN, TESTFN2, TESTFN3]:
+ try:
+ os.remove(file)
+ except os.error:
+ pass
+
+def test_main(tests=None):
+ test_suite = unittest.TestSuite()
+ if tests is None:
+ tests = [
+ TestAbstractedFS,
+ TestDummyAuthorizer,
+ TestCallLater,
+ TestFtpAuthentication,
+ TestFtpDummyCmds,
+ TestFtpCmdsSemantic,
+ TestFtpFsOperations,
+ TestFtpRetrieveData,
+ TestFtpAbort,
+ TestFtpStoreData,
+ TestTimeouts,
+ TestMaxConnections
+ ]
+ if SUPPORTS_IPV4:
+ tests.append(TestIPv4Environment)
+ if SUPPORTS_IPV6:
+ tests.append(TestIPv6Environment)
+
+ for test in tests:
+ test_suite.addTest(unittest.makeSuite(test))
+ remove_test_files()
+ unittest.TextTestRunner(verbosity=2).run(test_suite)
+ remove_test_files()
+
+
+if __name__ == '__main__':
+ test_main()