Spamworldpro Mini Shell
Spamworldpro


Server : Apache/2.4.52 (Ubuntu)
System : Linux webserver 6.8.0-49-generic #49~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Wed Nov 6 17:42:15 UTC 2 x86_64
User : www-data ( 33)
PHP Version : 8.1.2-1ubuntu2.21
Disable Function : NONE
Directory :  /lib/python3/dist-packages/twisted/protocols/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //lib/python3/dist-packages/twisted/protocols/__pycache__/ftp.cpython-310.pyc
o

�b��@s�dZddlZddlZddlZddlZddlZddlZz
ddlZddlZWn
e	y1dZZYnwddl
mZmZddl
mZddlmZmZmZmZddlmZmZmZmZmZddlmZmZddlmZmZm Z d	Z!d
Z"dZ#dZ$d
Z%dZ&dZ'dZ(dZ)dZ*dZ+dZ,dZ-dZ.dZ/dZ0dZ1dZ2dZ3dZ4dZ5dZ6dZ7d Z8d!Z9d"Z:d#Z;d$Z<d%Z=d&Z>d'Z?d(Z@d)ZAd*ZBd+ZCd,ZDd-ZEd.ZFd/ZGd0ZHd1ZId2ZJd3ZKd4ZLd5ZMd6ZNd7ZOd8ZPd9ZQd:ZRd;ZSd<ZTd=ZUd>ZVd?ZWd@ZXdAZYdBZZie!dC�e"dD�e#dE�e$dF�e%dG�e&dH�e'dI�e(dJ�e)dK�e*dLdMg�e+dN�e,dO�e-dP�e.dQ�e0dR�e/dS�e1dT�ie2dU�e3dV�e4dW�e5dX�e6dY�e7dZ�e8d[�e9d\�e:d]�e;d^�e<d_�e=d`�e>da�e?db�e@dc�eAdd�eBde��ieCdf�eDdg�eEdh�eFdi�eGdj�eHdk�eIdl�eJdm�eKdn�eLdo�eMdp�eNdq�eOdr�ePds�eQdt�eRdu�eSdv��eTdweVdxeWdyeUdzeXd{eYd|eZd}i�Z[Gd~d�de\�Z]d�d��Z^d�d��Z_e�`d��Zad�d�d��ZbGd�d��d�e\�ZcGd�d��d�ec�ZdGd�d��d�ec�ZeGd�d��d�ec�ZfGd�d��d�ec�ZgGd�d��d�ec�ZhGd�d��d�ec�ZiGd�d��d�ec�ZjGd�d��d�ec�ZkGd�d��d�ec�ZlGd�d��d�ec�ZmGd�d��d�e\�ZnGd�d��d�e\�ZoGd�d��d�ec�ZpGd�d��d�ec�Zqd�d��Zrgd��Zseejt�Gd�d��d�eju��ZvGd�d��d�ejw�ZxGd�d��d��Zyeejt�Gd�d��d���ZzGd�d��d�ej{�Z|Gd�d��d�ej{ej}�Z~Gd�d��d�ej�Z�Gd�d��d�e�Z�Gd�d��d�e�Z�Gd�d��d�e�Z�d�d��Z�d�d�d��Z�ee��Gd�d„dƒ�Z�ee��Gd�dĄdă�Z�Gd�dƄd�e��Z�ee��Gd�dȄdȃ�Z�eej��Gd�dʄdʃ�Z�Gd�d̄d�e��Z�Gd�d΄d�e��Z�Gd�dЄd�en�Z�Gd�d҄d�en�Z�Gd�dԄd�en�Z�Gd�dքd�en�Z�Gd�d؄d�en�Z�Gd�dڄdڃZ�Gd�d܄d�eju�Z�Gd�dބd�ejt�Z�ee��Gd�d�d�eju��Z�d�d�Z�d�d�Z�d�d�Z�Gd�d�d�ej��Z�Gd�d�d�ej{�Z�Gd�d�d�ejw�Z�Gd�d�d�e��Z�Gd�d�d�ej{�Z�d�d�Z�dS)�z 
An FTP protocol implementation
�N)�	Interface�implementer)�	copyright)�checkers�credentials�error�portal)�deferr�
interfaces�protocol�reactor)�basic�policies)�failure�filepath�log�100�120�125�150z200.1z200.2z200.3�202z211.1z211.2�212�213�214�215z220.1z220.2z221.1z221.2�225z226.1z226.2�227�229z230.1z230.2�250z257.1z257.2z331.1z331.2�332�350z421.1z421.2�425�426�450�451�452�500�501z502.1z502.2�503�504z530.1z530.2�532z550.1z550.2z550.3z550.4z550.5z550.6z550.7�551�552�553z110 MARK yyyy-mmmmz120 service ready in %s minutesz3125 Data connection already open, starting transferz4150 File status okay; about to open data connection.z200 Command OKz200 Type set to %s.z200 PORT OKz5202 Command not implemented, superfluous at this sitez211 System status replyz
211-Features:z211 Endz212 %sz213 %sz214 help: %sz215 UNIX Type: L8z220 %sz220 Service readyz&221 Service closing control connectionz221 Goodbye.z1225 data connection open, no transfer in progressz226 Abort successfulz226 Transfer Complete.z227 Entering Passive Mode (%s).z,229 Entering Extended Passive Mode (|||%s|).z230 User logged in, proceedz2230 Anonymous login ok, access restrictions apply.z&250 Requested File Action Completed OKz257 "%s"z257 "%s" createdz331 Password required for %s.z8331 Guest login ok, type your email address as password.z332 Need account for login.z6350 Requested file action pending further information.z6421 Service not available, closing control connection.z9421 Too many users right now, try again in a few minutes.z425 Can't open data connection.z.426 Transfer aborted.  Data connection closed.z/450 Requested action aborted. File unavailable.z8451 Requested action aborted. Local error in processing.z3452 Requested action aborted. Insufficient storage.z500 Syntax error: %sz#501 syntax error in argument(s) %s.z 502 Command '%s' not implementedz 502 Option '%s' not implemented.z&503 Incorrect sequence of commands: %sz'504 Not implemented for parameter '%s'.z$530 Please login with USER and PASS.z!530 Sorry, Authentication failed.z%532 Need an account for storing filesz"550 %s: No such file or directory.z550 %s: Permission denied.z:550 Anonymous users are forbidden to change the filesystemz%550 Cannot rmd, %s is not a directoryz550 %s: File existsz550 %s: is a directoryz"550 Requested action not taken: %sz551 Page type unknownzC552 Requested file action aborted, exceeded file storage allocationz5553 Requested action not taken, file name not allowedc@seZdZdZdS)�InvalidPathzL
    Internal exception used to signify an error during parsing a path.
    N)�__name__�
__module__�__qualname__�__doc__�r3r3�7/usr/lib/python3/dist-packages/twisted/protocols/ftp.pyr.�sr.cCs�|�d�rg}n|dd�}|�d�D]-}|dks|dkrq|dkr.|r)|��qt||��d|vs6d|vr;t||��|�|�q|S)zn
    Normalize a path, as represented by a list of strings each
    representing one segment of the path.
    �/N�.��..�)�
startswith�split�popr.�append)�cwd�path�segs�sr3r3r4�
toSegments�s



rBcCs�|tjkrt�t|��S|tjks|tjkrt�t|��S|tjkr)t�t	|��S|tj
kr5t�t|��S|tjkrAt�t
|��St��S)z?
    Map C{OSError} and C{IOError} to standard FTP errors.
    )�errno�ENOENTr	�fail�FileNotFoundError�EACCES�EPERM�PermissionDeniedError�ENOTDIR�IsNotADirectoryError�EEXIST�FileExistsError�EISDIR�IsADirectoryError)�er?r3r3r4�errnoToFailure�s



rQ�TESTcCs8|sdS|d}t�|�}t�d|d�}||krdSdS)a�
    Helper for checking if a FTPShell `segments` contains a wildcard Unix
    expression.

    Only filename globbing is supported.
    This means that wildcards can only be presents in the last element of
    `segments`.

    @type  segments: C{list}
    @param segments: List of path elements as used by the FTP server protocol.

    @rtype: Boolean
    @return: True if `segments` contains a globbing expression.
    F���rR�T)�fnmatch�	translate�_testTranslation�replace)�segments�
globCandidate�globTranslations�nonGlobTranslationsr3r3r4�_isGlobbingExpression�s
r]c@� eZdZdZdd�Zdd�ZdS)�FTPCmdErrorz-
    Generic exception for FTP commands.
    cGstj|g|�R�||_dS�N)�	Exception�__init__�errorMessage)�self�msgr3r3r4rbs
zFTPCmdError.__init__cCst|j|jS)zA
        Generate a FTP response message for this error.
        )�RESPONSE�	errorCoderc�rdr3r3r4�responseszFTPCmdError.responseN)r/r0r1r2rbrir3r3r3r4r_
sr_c@�eZdZdZeZdS)rFzH
    Raised when trying to access a non existent file or directory.
    N)r/r0r1r2�FILE_NOT_FOUNDrgr3r3r3r4rF�rFc@rj)�AnonUserDeniedErrorz[
    Raised when an anonymous user issues a command that will alter the
    filesystem
    N)r/r0r1r2�ANON_USER_DENIEDrgr3r3r3r4rm"�rmc@rj)rIz[
    Raised when access is attempted to a resource to which access is
    not allowed.
    N)r/r0r1r2�PERMISSION_DENIEDrgr3r3r3r4rI+rorIc@rj)rKzE
    Raised when RMD is called on a path that isn't a directory.
    N)r/r0r1r2�IS_NOT_A_DIRrgr3r3r3r4rK4rlrKc@rj)rMzA
    Raised when attempted to override an existing resource.
    N)r/r0r1r2�FILE_EXISTSrgr3r3r3r4rM<rlrMc@rj)rOzC
    Raised when DELE is called on a path that is a directory.
    N)r/r0r1r2�IS_A_DIRrgr3r3r3r4rODrlrOc@rj)�CmdSyntaxErrorz0
    Raised when a command syntax is wrong.
    N)r/r0r1r2�
SYNTAX_ERRrgr3r3r3r4rtLrlrtc@rj)�CmdArgSyntaxErrorz^
    Raised when a command is called with wrong value or a wrong number of
    arguments.
    N)r/r0r1r2�SYNTAX_ERR_IN_ARGSrgr3r3r3r4rvTrorvc@rj)�CmdNotImplementedErrorzF
    Raised when an unimplemented command is given to the server.
    N)r/r0r1r2�CMD_NOT_IMPLMNTDrgr3r3r3r4rx]rlrxc@rj)�CmdNotImplementedForArgErrorze
    Raised when the handling of a parameter for a command is not implemented by
    the server.
    N)r/r0r1r2�CMD_NOT_IMPLMNTD_FOR_PARAMrgr3r3r3r4rzerorzc@�eZdZdS)�FTPErrorN�r/r0r1r3r3r3r4r}n�r}c@r|)�PortConnectionErrorNr~r3r3r3r4r�rrr�c@rj)�BadCmdSequenceErrorzS
    Raised when a client sends a series of commands in an illogical sequence.
    N)r/r0r1r2�BAD_CMD_SEQrgr3r3r3r4r�vrlr�c@rj)�AuthorizationErrorz2
    Raised when client authentication fails.
    N)r/r0r1r2�AUTH_FAILURErgr3r3r3r4r�~rlr�cGstjdt|�dd�dS)NzdebugDeferred(): %sT��debug)rre�str)rd�_r3r3r4�
debugDeferred�sr�)
N�Jan�Feb�Mar�Apr�May�Jun�Jul�Aug�Sep�Oct�Nov�Decc@s�eZdZdZdZdZdZdZdd�Zdd�Z	dd	�Z
d
d�Zdd
�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�ZdS)"�DTPFN�latin-1cCsd|_|jj�d�g|_dS�NT)�isConnected�factory�deferred�callback�_bufferrhr3r3r4�connectionMade�s
zDTP.connectionMadecCs$d|_|jdur|j�d�dSdS�NF)r��_onConnLostr��rd�reasonr3r3r4�connectionLost�s
�zDTP.connectionLostcCs|j�|d�dS)zv
        Send a line to data channel.

        @param line: The line to be sent.
        @type line: L{bytes}
        s
N��	transport�write�rd�liner3r3r4�sendLine�szDTP.sendLinec	CsZdd�}	d}
|
|rdpd|��||dd�|dd�||	t�|��d��|j�}||S)	a
        Helper method to format one entry's info into a text entry like:
        'drwxrwxrwx   0 user   group   0 Jan 01  1970 filename.txt'

        @param name: C{bytes} name of the entry (file or directory or link)
        @param size: C{int} size of the entry
        @param directory: evals to C{bool} - whether the entry is a directory
        @param permissions: L{twisted.python.filepath.Permissions} object
            representing that entry's permissions
        @param hardlinks: C{int} number of hardlinks
        @param modified: C{float} - entry's last modified time in seconds
            since the epoch
        @param owner: C{str} username of the owner
        @param group: C{str} group name of the owner

        @return: C{str} in the requisite format
        cSsBt��}t|j|j|j|j|jd�}|j|jkrd|Sd|S)N)�month�day�year�hour�minutez%(month)s %(day)02d %(year)5dz+%(month)s %(day)02d %(hour)02d:%(minute)02d)�time�gmtime�_months�tm_mon�tm_mday�tm_year�tm_hour�tm_min)�mtime�now�infor3r3r4�
formatDate�s�z.DTP._formatOneListResponse.<locals>.formatDatezY%(directory)s%(permissions)s%(hardlinks)4d %(owner)-9s %(group)-9s %(size)15d %(date)12s �d�-N�)�	directory�permissions�	hardlinks�owner�group�size�date)�	shorthandr�r��encode�	_encoding)rd�namer�r�r�r��modifiedr�r�r��formatrer3r3r4�_formatOneListResponse�s �


��
�zDTP._formatOneListResponsecCs|�|j|g|�R��dSr`)r�r�)rdr�rir3r3r4�sendListResponse�szDTP.sendListResponsecCs|j�||�Sr`�r��registerProducer�rd�producer�	streamingr3r3r4r���zDTP.registerProducercCs|j��|j��dSr`)r��unregisterProducer�loseConnectionrhr3r3r4r��s
zDTP.unregisterProducercCs|jr	|j�|�Std��)NzCrap damn crap damn crap damn)r�r�r�ra�rd�datar3r3r4r��sz	DTP.writecCs2z	|j�|�WdSty|j��YdSwr`)�_consr��
BaseExceptionr��errback�rd�bytesr3r3r4�
_conswrites
�zDTP._conswritecCs(|jdur|�|�dS|j�|�dSr`)r�r�r�r=r�r3r3r4�dataReceiveds
zDTP.dataReceivedcCs|j��d|_|`|Sr`)r�r�r��rd�ignoredr3r3r4�_unregConsumer
s
zDTP._unregConsumercCs||jdusJ�||_|j�|d�|jD]}|�|�qd|_|jr1t��|_}|�|j	�|S|j�
�d|_t�d�Sr�)r�r�r�r�r�r	�Deferredr��addBothr�r��succeed)rd�cons�chunkr�r3r3r4�registerConsumers


zDTP.registerConsumercC�|j��dSr`)r��resumeProducingrhr3r3r4r�#r�zDTP.resumeProducingcCr�r`)r��pauseProducingrhr3r3r4r�&r�zDTP.pauseProducingcCr�r`)r��
stopProducingrhr3r3r4r�)r�zDTP.stopProducing)r/r0r1r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r3r3r3r4r��s*	6r�c@sdeZdZdZe�Ze�Ze�ZeZdZ	ddd�Z
dd�Zdd	�Zd
d�Z
dd
�Zdd�Zdd�ZdS)�
DTPFactorya
    Client factory for I{data transfer process} protocols.

    @ivar peerCheck: perform checks to make sure the ftp-pi's peer is the same
        as the dtp's
    @ivar pi: a reference to this factory's protocol interpreter

    @ivar _state: Indicates the current state of the DTPFactory.  Initially,
        this is L{_IN_PROGRESS}.  If the connection fails or times out, it is
        L{_FAILED}.  If the connection succeeds before the timeout, it is
        L{_FINISHED}.

    @cvar _IN_PROGRESS: Token to signal that connection is active.
    @type _IN_PROGRESS: L{object}.

    @cvar _FAILED: Token to signal that connection has failed.
    @type _FAILED: L{object}.

    @cvar _FINISHED: Token to signal that connection was successfully closed.
    @type _FINISHED: L{object}.
    FNcCs:||_||_t��|_d|_|durddlm}||_dS)z�
        Constructor

        @param pi: this factory's protocol interpreter
        @param peerHost: if peerCheck is True, this is the tuple that the
            generated instance will use to perform security checks
        Nr�r)	�pi�peerHostr	r�r��delayedCall�twisted.internetr�_reactor)rdr�r�rr3r3r4rbNs

zDTPFactory.__init__cCsNtjddd�|j|jurdS|j|_|��t�}||_|j|_||j_	|S)N�DTPFactory.buildProtocolTr�)
rre�_state�_IN_PROGRESS�	_FINISHED�
cancelTimeoutr�r�r��dtpInstance�rd�addr�pr3r3r4�
buildProtocol_sr�cCstjddd�|��dS)NzdtpFactory.stopFactoryTr�)rrer�rhr3r3r4�stopFactorymszDTPFactory.stopFactorycCsFt�d�|j|jur
dS|j|_|j}d|_|�tt�	d���dS)Nz$timed out waiting for DTP connectionzDTPFactory timeout)
rrer�r��_FAILEDr�r�r�r	�TimeoutError)rdr�r3r3r4�timeoutFactoryqs
zDTPFactory.timeoutFactorycCs8|jdur|j��rtjddd�|j��dSdSdS)Nzcancelling DTP timeoutTr�)r��activerre�cancelrhr3r3r4r�{s�zDTPFactory.cancelTimeoutcCs$t�d|�|j�||j�|_dS)Nz'DTPFactory.setTimeout set to %s seconds)rrer��	callLaterr�r�)rd�secondsr3r3r4�
setTimeout�szDTPFactory.setTimeoutcCs6|j|jurdS|j|_|j}d|_|�t|��dSr`)r�r�r�r�r�r�)rd�	connectorr�r�r3r3r4�clientConnectionFailed�sz!DTPFactory.clientConnectionFailed)NN)r/r0r1r2�objectr�r�r�r��	peerCheckrbr�r�r�r�rrr3r3r3r4r�-s

r�c@seZdZdd�Zdd�ZdS)�ASCIIConsumerWrappercCsP||_|j|_|j|_tjdksttj�dksJd��tjdkr&|j|_dSdS)N�
rTz6Unsupported platform (yea right like this even exists))r�r�r��os�linesep�lenr�)rdr�r3r3r4rb�s�
�zASCIIConsumerWrapper.__init__cCs|j�|�tjd��S)Nr
)r�r�rXrrr�r3r3r4r��szASCIIConsumerWrapper.writeN)r/r0r1rbr�r3r3r3r4r	�sr	c@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�FileConsumerz�
    A consumer for FTP input that writes data to a file.

    @ivar fObj: a file object opened for writing, used to write data received.
    @type fObj: C{file}
    cC�
||_dSr`)�fObj�rdrr3r3r4rb��
zFileConsumer.__init__cCs||_|sJ�dSr`)r�r�r3r3r4r���zFileConsumer.registerProducercCsd|_|j��dSr`)r�r�closerhr3r3r4r��szFileConsumer.unregisterProducercC�|j�|�dSr`)rr�r�r3r3r4r���zFileConsumer.writeN)r/r0r1r2rbr�r�r�r3r3r3r4r�src@�eZdZdZdZdd�ZdS)�FTPOverflowProtocolz:FTP mini-protocol for when there are too many connections.r�cCs$|�tt�|j��|j��dSr`)r�rf�TOO_MANY_CONNECTIONSr�r�r�r�rhr3r3r4r��sz"FTPOverflowProtocol.connectionMadeN)r/r0r1r2r�r�r3r3r3r4r�srcs�eZdZdZdZed�\ZZZZ	dZ
dZdZdZ
dZdZdZddgZgd	�Zed
d�ZejZdZd
d�Z�fdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Z dd �Z!d!d"�Z"d#d$�Z#d%d&�Z$d\d(d)�Z%d*d+�Z&d,d-�Z'd.d/�Z(d0d1�Z)d2d3�Z*d4d5�Z+d6d7�Z,d8d9�Z-d:d;�Z.d<d=�Z/d>d?�Z0d@dA�Z1dBdC�Z2dDdE�Z3dFdG�Z4dHdI�Z5dJdK�Z6dLdM�Z7dNdO�Z8dPdQ�Z9dRdS�Z:dTdU�Z;dVdW�Z<dXdY�Z=dZd[�Z>�Z?S)]�FTPa;
    Protocol Interpreter for the File Transfer Protocol

    @ivar state: The current server state.  One of L{UNAUTH},
        L{INAUTH}, L{AUTHED}, L{RENAMING}.

    @ivar shell: The connected avatar
    @ivar binary: The transfer mode.  If false, ASCII.
    @ivar dtpFactory: Generates a single DTP for this session
    @ivar dtpPort: Port returned from listenTCP
    @ivar listenFactory: A callable with the signature of
        L{twisted.internet.interfaces.IReactorTCP.listenTCP} which will be used
        to create Ports for passive connections (mainly for testing).

    @ivar passivePortRange: iterator used as source of passive port numbers.
    @type passivePortRange: C{iterator}

    @cvar UNAUTH: Command channel is not yet authenticated.
    @type UNAUTH: L{int}

    @cvar INAUTH: Command channel is in the process of being authenticated.
    @type INAUTH: L{int}

    @cvar AUTHED: Command channel was successfully authenticated.
    @type AUTHED: L{int}

    @cvar RENAMING: Command channel is between the renaming command sequence.
    @type RENAMING: L{int}
    F��
NT�FEAT�QUIT)r�MDTM�PASV�SIZEzTYPE A;IrrTr�cGst||}|�|�dSr`)rfr�)rd�key�argsrer3r3r4�reply�sz	FTP.replycs&t|t�r|�|j�}t��|�dS)za
        (Private) Encodes and sends a line

        @param line: L{bytes} or L{unicode}
        N)�
isinstancer�r�r��superr�r���	__class__r3r4r��s
zFTP.sendLinecCs(|j|_|�|j�|�t|jj�dSr`)�UNAUTH�stater�timeOutr$�WELCOME_MSGr��welcomeMessagerhr3r3r4r�szFTP.connectionMadecCsJ|jr|��|�d�t|jd�r|jjdur|j��d|_d|_dS)N�logout)�
dtpFactory�
cleanupDTPr�hasattr�shellr.r�r�r3r3r4r�s


zFTP.connectionLostcCr�r`�r�r�rhr3r3r4�timeoutConnectionr�zFTP.timeoutConnectionc	s�������ttkr|��j�}��fdd�}�fdd�}�fdd�}|�d�}|dkr>|d|��||d	d�f}n|�d
}tj�j	�g|�R�}|�
||�|�tj
�ddlm}|�d|j|�dS)
Ncsx��t�r���j���dS��t�r*t�fdd�dD��r*��t��d��dSt	�
d�t	�����td�dS)Nc3s �|]}|�jjdvVqdS)rN)�valuer#)�.0re��errr3r4�	<genexpr>#s
��
�z:FTP.lineReceived.<locals>.processFailed.<locals>.<genexpr>)z
takes exactlyzrequired positional argumentz requires an argument.zUnexpected FTP errorzinternal server error)
�checkr_r�r5ri�	TypeError�anyr$rurrer8�REQ_ACTN_NOT_TAKENr7��cmdrdr7r4�
processFailed s
�

z'FTP.lineReceived.<locals>.processFailedcs2t|t�r�j|�dS|dur��|�dSdSr`)r%�tupler$��resultrhr3r4�processSucceeded-s

�z*FTP.lineReceived.<locals>.processSucceededcs�js	���dSdSr`)�disconnectedr��r�rhr3r4�allDone3s�z!FTP.lineReceived.<locals>.allDone� rSrTr3rr�)�resetTimeoutr�r�r��decoder��findr	�
maybeDeferred�processCommand�addCallbacks�
addErrbackrr8r�rrr�)	rdr�r@rDrG�
spaceIndexr#r�rr3r>r4�lineReceiveds$

zFTP.lineReceivedcs���fdd�}|��}|�jvr||�S�j�jkr-|dkr#�j��S|dkr+tdfStS�j�jkr@|dkr<�j��StdfS�j�j	krJ||�S�j�j
kr]|dkrY�j��StdfSdS)	Ncs.t�d|d�}|dur|��St�t|��S)N�ftp_)�getattrr	rErx)�command�method��paramsrdr3r4�call_ftp_commandJsz,FTP.processCommand.<locals>.call_ftp_command�USER�PASSzUSER required before PASSzPASS required after USER�RNTOzRNTO required after RNFR)�upper�PUBLIC_COMMANDSr*r)�ftp_USERr��
NOT_LOGGED_IN�INAUTH�ftp_PASS�AUTHED�RENAMING�ftp_RNTO)rdr?rWrXr3rVr4rMIs*



�zFTP.processCommandc	CsL|jD]}z|�||�}W|StjyYqwt�d|d|j����)ze
        Return a port for passive access, using C{self.passivePortRange}
        attribute.
        r7zNo port available in range )�passivePortRange�
listenFactoryr�CannotListenError)rdr��portn�dtpPortr3r3r4�
getDTPPortls
���zFTP.getDTPPortcCsB|s	t�td��S||_|j|_|jjr|j|jjkrt	St
|fS)zc
        First part of login.  Get the username the peer wants to
        authenticate as.
        zUSER requires an argument)r	rErt�_userr`r*r��allowAnonymous�
userAnonymous�GUEST_NAME_OK_NEED_EMAIL�USR_NAME_OK_NEED_PASS)rd�usernamer3r3r4r^|szFTP.ftp_USERcst�jjr�j�jjkrt��}t�n	t��j|�}t��`��fdd�}�fdd�}�j	�
|dt�}|�||�|S)zf
        Second part of login.  Get the password the peer wants to
        authenticate with.
        cs8|\}}}|tus
Jd��|�_|�_g�_�j�_�S)NzThe realm is busted, jerk.)�	IFTPShellr2r.�workingDirectoryrbr*)rC�	interface�avatarr.�r$rdr3r4�_cbLogin�s
zFTP.ftp_PASS.<locals>._cbLogincs|�tjtj��j�_t�r`)�trap�
cred_error�UnauthorizedLogin�UnhandledCredentialsr)r*r��rrhr3r4�_ebLogin�szFTP.ftp_PASS.<locals>._ebLoginN)
r�rlrkrmr�	Anonymous�GUEST_LOGGED_IN_PROCEED�UsernamePassword�USR_LOGGED_IN_PROCEEDr�loginrqrN)rd�password�credsrvr|r�r3rur4ra�s	zFTP.ftp_PASScCsv|jdur	|��t|d�|_|j�|j�|�|j�|_|j��j	}|j��j
}|�tt
||��|jj�dd��S)a�
        Request for a passive connection

        from the rfc::

            This command requests the server-DTP to "listen" on a data port
            (which is not its default data port) and to wait for a connection
            rather than initiate one upon receipt of a transfer command.  The
            response to this command includes the host and port address this
            server is listening on.
        N)r�cS�dSr`r3��ignr3r3r4�<lambda>��zFTP.ftp_PASV.<locals>.<lambda>)r/r0r�r�
dtpTimeoutrjrir��getHost�host�portr$�ENTERING_PASV_MODE�encodeHostPortr��addCallback)rdr�r�r3r3r4�ftp_PASV�s

zFTP.ftp_PASVcCs�ttt|�d���}dt|dd��}|dd>|dB}|jdur'|��t||j��j	d�|_|j�
|j�t�
|||j�|_dd�}d	d
�}|jj�||�S)N�,z%d.%d.%d.%drr��)r�r�cS�tSr`)�ENTERING_PORT_MODErFr3r3r4�	connected��zFTP.ftp_PORT.<locals>.connectedcSs|�t�tSr`)rwr��CANT_OPEN_DATA_CNXr7r3r3r4�
connFailed�s
z FTP.ftp_PORT.<locals>.connFailed)rA�map�intr;r/r0r�r��getPeerr�rr�r�
connectTCPrir�rN)rd�addressr��ipr�r�r�r3r3r4�ftp_PORT�s
zFTP.ftp_PORTcCst|t�r
|�d�S|S)a�
        Encode C{name} to be sent over the wire.

        This encodes L{unicode} objects as UTF-8 and leaves L{bytes} as-is.

        As described by U{RFC 3659 section
        2.2<https://tools.ietf.org/html/rfc3659#section-2.2>}::

            Various FTP commands take pathnames as arguments, or return
            pathnames in responses. When the MLST command is supported, as
            indicated in the response to the FEAT command, pathnames are to be
            transferred in one of the following two formats.

                pathname = utf-8-name / raw
                utf-8-name = <a UTF-8 encoded Unicode string>
                raw = <any string that is not a valid UTF-8 encoding>

            Which format is used is at the option of the user-PI or server-PI
            sending the pathname.

        @param name: Name to be encoded.
        @type name: L{bytes} or L{unicode}

        @return: Wire format of C{name}.
        @rtype: L{bytes}
        zutf-8)r%r�r�)rdr�r3r3r4�_encodeName�s

zFTP._encodeNamer7cs��jdus	�jjst�td��S|��dvrd}�fdd�}zt�j|�}Wnty6t�t	|��YSw�j
�|d�}|�|�|S)a�This command causes a list to be sent from the server to the
        passive DTP.  If the pathname specifies a directory or other
        group of files, the server should transfer a list of files
        in the specified directory.  If the pathname specifies a
        file then the server should send current information on the
        file.  A null argument implies the user's current working or
        default directory.
        N�"must send PORT or PASV before RETR)z-az-lz-laz-alr7csB��t�|D]\}}��|�}�j�||�q�jj��tfSr`)r$�DATA_CNX_ALREADY_OPEN_START_XFRr�r�r�r�r��TXFR_COMPLETE_OK)�resultsr��attrsrhr3r4�
gotListings

z FTP.ftp_LIST.<locals>.gotListing)r�r�r�r�r�r�r�)
r�r�r	rEr��lowerrBrrr.rFr2�listr�)rdr?r�rYr�r3rhr4�ftp_LIST�s 
��
zFTP.ftp_LISTcs��jdus	�jjst�td��Szt�j|�}Wnty(t�t|��YSw�fdd�}�fdd�}t	|�r>|�
�}nd}�j�|�}|�
||�|�|�|S)a\
        This command causes a directory listing to be sent from the server to
        the client. The pathname should specify a directory or other
        system-specific file group descriptor. An empty path implies the
        current working directory. If the path is non-existent, send nothing.
        If the path is to a file, send only the file name.

        @type path: C{str}
        @param path: The path for which a directory listing should be returned.

        @rtype: L{Deferred}
        @return: a L{Deferred} which will be fired when the listing request
            is finished.
        Nr�csT��t�|D]\}}|r|r t�||�r ��|�}�j�|�q�jj��tfS)a�
            Send, line by line, each matching file in the directory listing,
            and then close the connection.

            @type results: A C{list} of C{tuple}. The first element of each
                C{tuple} is a C{str} and the second element is a C{list}.
            @param results: The names of the files in the directory.

            @param glob: A shell-style glob through which to filter results
                (see U{http://docs.python.org/2/library/fnmatch.html}), or
                L{None} for no filtering.
            @type glob: L{str} or L{None}

            @return: A C{tuple} containing the status code for a successful
                transfer.
            @rtype: C{tuple}
            )	r$r�rUr�r�r�r�r�r�)r��globr�r�rhr3r4�cbListCs

�zFTP.ftp_NLST.<locals>.cbListcs�jj��tfS)a
            RFC 959 specifies that an NLST request may only return directory
            listings. Thus, send nothing and just close the connection.

            @type results: L{Failure}
            @param results: The L{Failure} wrapping a L{FileNotFoundError} that
                occurred while trying to list the contents of a nonexistent
                directory.

            @returns: A C{tuple} containing the status code for a successful
                transfer.
            @rtype: C{tuple}
            )r�r�r�r�)r�rhr3r4�listErr]szFTP.ftp_NLST.<locals>.listErr)r�r�r	rEr�rBrrr.rFr]r<r2r�r�rO)rdr?rYr�r�r�r�r3rhr4�ftp_NLST+s �

zFTP.ftp_NLSTcsRzt�j|��Wntyt�t|��YSw��fdd�}�j����|�S)Ncs��_tfSr`)rr�REQ_FILE_ACTN_COMPLETED_OKrB�rYrdr3r4�
accessGranted�sz"FTP.ftp_CWD.<locals>.accessGranted)	rBrrr.r	rErFr2�accessr�)rdr?r�r3r�r4�ftp_CWD{s�zFTP.ftp_CWDcC�
|�d�S)Nr8)r�rhr3r3r4�ftp_CDUP�rzFTP.ftp_CDUPcCstdd�|j�fS)Nr5)�	PWD_REPLY�joinrrrhr3r3r4�ftp_PWD�szFTP.ftp_PWDcs��jdur	td��zt�j|��Wnty!t�t|��YSw��d��fdd�}�j	s6t
�j��n�j�dd��dd������fd	d
�}�fdd�}�j���}|�
||�|�|�|S)
a�
        This command causes the content of a file to be sent over the data
        transfer channel. If the path is to a folder, an error will be raised.

        @type path: C{str}
        @param path: The path to the file which should be transferred over the
        data transfer channel.

        @rtype: L{Deferred}
        @return: a L{Deferred} which will be fired when the transfer is done.
        Nz!PORT or PASV required before RETRc����jj�|Sr`�rr�r+rBrhr3r4�
enableTimeout��z#FTP.ftp_RETR.<locals>.enableTimeoutcS�tfSr`�r�rBr3r3r4�cbSent��zFTP.ftp_RETR.<locals>.cbSentcSs(t�d�t�|�|�t�r|StfS)Nz7Unexpected error attempting to transmit file to client:)rrer8r:r_�CNX_CLOSED_TXFR_ABORTEDr7r3r3r4�ebSent�s



zFTP.ftp_RETR.<locals>.ebSentcs8�jjr
��t�n��t�|���}|����|Sr`)r�r�r$r��FILE_STATUS_OK_OPEN_DATA_CNX�sendrN��filer�)r�r�r�rdr3r4�cbOpened�s

zFTP.ftp_RETR.<locals>.cbOpenedcsL|�ttt�st�d�t�|�|�t�r|jj	d�
��fStd�
��fS)Nz:Unexpected error attempting to open file for transmission:r5)r:rIrFrOrrer8r_r5rgr�rkr7��newsegsr3r4�ebOpened�s�


zFTP.ftp_RETR.<locals>.ebOpened)r�r�rBrrr.r	rErFr�binaryr	r2�openForReadingrNr��rdr?r�r�r�r�r3)r�r�r�r�rdr4�ftp_RETR�s(
�


zFTP.ftp_RETRcs��jdur	td��zt�j|��Wnty!t�t|��YSw��d��fdd�}���fdd�}�fdd�}�fd	d
��dd��d
d���j	�
��}|�||�|�|�|S)a�
        STORE (STOR)

        This command causes the server-DTP to accept the data
        transferred via the data connection and to store the data as
        a file at the server site.  If the file specified in the
        pathname exists at the server site, then its contents shall
        be replaced by the data being transferred.  A new file is
        created at the server site if the file specified in the
        pathname does not already exist.
        Nz!PORT or PASV required before STORcr�r`r�rBrhr3r4r��r�z#FTP.ftp_STOR.<locals>.enableTimeoutcs4���}|���|��fdd��|����|S)zx
            File was open for reading. Launch the data transfer channel via
            the file consumer.
            cs���Sr`)rrF�r�r3r4r���z0FTP.ftp_STOR.<locals>.cbOpened.<locals>.<lambda>)�receiver�rNr�)�
cbConsumerr�r�r�r4r��s

zFTP.ftp_STOR.<locals>.cbOpenedcs8t|jt�r|jjd���fSt�|d�td���fS)z�
            Called when failed to open the file for reading.

            For known errors, return the FTP error code.
            For all other, return a file not found error.
            r5z-Unexpected error received while opening file:)r%r5r_rgr�rr8rkr7r�r3r4r�szFTP.ftp_STOR.<locals>.ebOpenedcs>�jst|�}�j�|�}�jjr��t�|S��t�|S)z�
            Called after the file was opended for reading.

            Prepare the data transfer channel and send the response
            to the command channel.
            )r�r	r�r�r�r$r�r�)r�r�rhr3r4r�
s

�z FTP.ftp_STOR.<locals>.cbConsumercSr�)zK
            Called from data transport when transfer is done.
            r�rBr3r3r4r�!szFTP.ftp_STOR.<locals>.cbSentcSs t�|d�|�t�r
|StfS)zk
            Called from data transport when there are errors during the
            transfer.
            z*Unexpected error received during transfer:)rr8r:r_r�r7r3r3r4r�'s
zFTP.ftp_STOR.<locals>.ebSent)
r�r�rBrrr.r	rErFrr2�openForWritingrNr�r�r3)r�r�r�r�rdr4�ftp_STOR�s$
�


zFTP.ftp_STORcC�Nzt|j|�}Wntyt�t|��YSwdd�}|j�|d��|�S)ab
        File SIZE

        The FTP command, SIZE OF FILE (SIZE), is used to obtain the transfer
        size of a file from the server-FTP process.  This is the exact number
        of octets (8 bit bytes) that would be transmitted over the data
        connection should that file be transmitted.  This value will change
        depending on the current STRUcture, MODE, and TYPE of the data
        connection or of a data connection that would be created were one
        created now.  Thus, the result of the SIZE command is dependent on
        the currently established STRU, MODE, and TYPE parameters.

        The SIZE command returns how many octets would be transferred if the
        file were to be transferred using the current transfer structure,
        mode, and type.  This command is normally used in conjunction with
        the RESTART (REST) command when STORing a file to a remote server in
        STREAM mode, to determine the restart point.  The server-PI might
        need to read the partially transferred file, do any appropriate
        conversion, and count the number of octets that would be generated
        when sending the file in order to correctly respond to this command.
        Estimates of the file transfer size MUST NOT be returned; only
        precise information is acceptable.

        http://tools.ietf.org/html/rfc3659
        cSs|\}tt|�fSr`)�FILE_STATUSr�)rCr�r3r3r4�cbStatWrzFTP.ftp_SIZE.<locals>.cbStat)r��	rBrrr.r	rErFr2�statr��rdr?r�r�r3r3r4�ftp_SIZE8s�zFTP.ftp_SIZEcCr�)a!
        File Modification Time (MDTM)

        The FTP command, MODIFICATION TIME (MDTM), can be used to determine
        when a file in the server NVFS was last modified.  This command has
        existed in many FTP servers for many years, as an adjunct to the REST
        command for STREAM mode, thus is widely available.  However, where
        supported, the "modify" fact that can be provided in the result from
        the new MLST command is recommended as a superior alternative.

        http://tools.ietf.org/html/rfc3659
        cSs|\}tt�dt�|��fS)Nz%Y%m%d%H%M%S)r�r��strftimer�)rCr�r3r3r4r�oszFTP.ftp_MDTM.<locals>.cbStat)r�r�r�r3r3r4�ftp_MDTM]s
�zFTP.ftp_MDTMcCsH|��}|r!t|d|dd�}|dur||dd��S|�|�StfS)a
        REPRESENTATION TYPE (TYPE)

        The argument specifies the representation type as described
        in the Section on Data Representation and Storage.  Several
        types take a second parameter.  The first parameter is
        denoted by a single Telnet character, as is the second
        Format parameter for ASCII and EBCDIC; the second parameter
        for local byte is a decimal integer to indicate Bytesize.
        The parameters are separated by a <SP> (Space, ASCII code
        32).
        �type_rNrT)r\rS�type_UNKNOWNru)rd�typer��fr3r3r4�ftp_TYPEus

zFTP.ftp_TYPEcCs0|dks|dkrd|_td|fSt�t|��S)Nr7�NF�A�r��TYPE_SET_OKr	rErv�rd�coder3r3r4�type_A�sz
FTP.type_AcCs$|dkrd|_tdfSt�t|��S)Nr7T�Ir�r�r3r3r4�type_I�sz
FTP.type_IcCst�t|��Sr`)r	rErzr�r3r3r4r��r�zFTP.type_UNKNOWNcCr�r`)�
NAME_SYS_TYPErhr3r3r4�ftp_SYST�r�zFTP.ftp_SYSTcC�$|��}|dkrtfSt�t|��S)N�F�r\�CMD_OKr	rErz)rd�	structurer�r3r3r4�ftp_STRU��zFTP.ftp_STRUcCr�)N�Sr�)rd�moder�r3r3r4�ftp_MODE�r�zFTP.ftp_MODEcsLzt|j��}Wntyt�t���YSw|j�|���fdd��S)Ncst�fSr`)�	MKD_REPLYr��r?r3r4r��r�zFTP.ftp_MKD.<locals>.<lambda>)	rBrrr.r	rErFr2�
makeDirectoryr��rdr?r�r3r�r4�ftp_MKD�s�
�zFTP.ftp_MKDcC�Hzt|j|�}Wntyt�t|��YSw|j�|��dd��S)NcSr�r`�r�r�r3r3r4r���zFTP.ftp_RMD.<locals>.<lambda>)	rBrrr.r	rErFr2�removeDirectoryr�r�r3r3r4�ftp_RMD����zFTP.ftp_RMDcCr�)NcSr�r`r�r�r3r3r4r��r�zFTP.ftp_DELE.<locals>.<lambda>)	rBrrr.r	rErFr2�
removeFiler�r�r3r3r4�ftp_DELE�rzFTP.ftp_DELEcCr�r`)r�rhr3r3r4�ftp_NOOP�r�zFTP.ftp_NOOPcCs||_|j|_tfSr`)�	_fromNamercr*�"REQ_FILE_ACTN_PENDING_FURTHER_INFO)rd�fromNamer3r3r4�ftp_RNFR�szFTP.ftp_RNFRcCsh|j}|`|j|_zt|j|�}t|j|�}Wnty't�t|��YSw|j	�
||��dd��S)NcSr�r`r�r�r3r3r4r��r�zFTP.ftp_RNTO.<locals>.<lambda>)rrbr*rBrrr.r	rErFr2�renamer�)rd�toNamer�fromsegs�tosegsr3r3r4rd�s��zFTP.ftp_RNTOcCsB|�ttd�|jD]	}|�d|�q|�ttd�dS)zm
        Advertise the features supported by the server.

        http://tools.ietf.org/html/rfc2389
        rrHrTN)r�rf�FEAT_OK�FEATURES)rd�featurer3r3r4�ftp_FEAT�s
zFTP.ftp_FEATcCs|�t|�S)zl
        Handle OPTS command.

        http://tools.ietf.org/html/draft-ietf-ftpext-utf-8-option-00
        )r$�OPTS_NOT_IMPLEMENTED)rd�optionr3r3r4�ftp_OPTS�szFTP.ftp_OPTScCs|�t�|j��d|_dSr�)r$�GOODBYE_MSGr�r�rErhr3r3r4�ftp_QUIT�s


zFTP.ftp_QUITcCs�tjddd�t�|j�|jd}|_tj�|�r|��ntj�|�r*|��nJd|f��|j	�
�d|_	|jdurCd|_dSdS)z0
        Call when DTP connection exits
        r0Tr�NFz@dtpPort should be an IListeningPort or IConnector, instead is %r)rrerir
�IListeningPort�
providedBy�
stopListening�
IConnector�
disconnectr/r�r�)rdrir3r3r4r0�s"

��


�zFTP.cleanupDTP)r7)@r/r0r1r2rE�ranger)r`rbrcr�rr2r/rir�r�r]rrer�	listenTCPrfr�r$r�r�r�r4rQrMrjr^rar�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrrdrrrr0�
__classcell__r3r3r'r4r�sn

/#!
-P
J`%			rc@sVeZdZdZeZeZdZdZ	dZ
dej�d�Z
edd�Zdd
d�Zdd
�Zdd�Zd	S)�
FTPFactorya
    A factory for producing ftp protocol instances

    @ivar timeOut: the protocol interpreter's idle timeout time in seconds,
        default is 600 seconds.

    @ivar passivePortRange: value forwarded to C{protocol.passivePortRange}.
    @type passivePortRange: C{iterator}
    T�	anonymousiXzTwisted z FTP ServerrrTNcCs||_||_g|_dSr`)rrm�	instances)rdrrmr3r3r4rb!s
zFTPFactory.__init__cCs8tj�||�}|dur|j|j_|j|j_|j|j_|Sr`)r�LimitTotalConnectionsFactoryr�r�wrappedProtocolr+rer�r3r3r4r�&s


zFTPFactory.buildProtocolcCs dd�|jD�tj�|�dS)NcSs g|]}|jdur|�d��qSr`)r+r�r6r�r3r3r4�
<listcomp>1s z*FTPFactory.stopFactory.<locals>.<listcomp>)r rr!r�rhr3r3r4r�.szFTPFactory.stopFactory)Nr)r/r0r1r2rrr�overflowProtocolrlrmr+r�versionr-rrerbr�r�r3r3r3r4rs


rc@s\eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
d�Z	ddd�Z
dd�Zdd�ZdS)rqz�
    An abstraction of the shell commands used by the FTP protocol for
    a given user account.

    All path names must be absolute.
    cC�dS)a
        Create a directory.

        @param path: The path, as a list of segments, to create
        @type path: C{list} of C{unicode}

        @return: A Deferred which fires when the directory has been
        created, or which fails if the directory cannot be created.
        Nr3r�r3r3r4r�@r�zIFTPShell.makeDirectorycCr')a
        Remove a directory.

        @param path: The path, as a list of segments, to remove
        @type path: C{list} of C{unicode}

        @return: A Deferred which fires when the directory has been
        removed, or which fails if the directory cannot be removed.
        Nr3r�r3r3r4r�Kr�zIFTPShell.removeDirectorycCr')a

        Remove a file.

        @param path: The path, as a list of segments, to remove
        @type path: C{list} of C{unicode}

        @return: A Deferred which fires when the file has been
        removed, or which fails if the file cannot be removed.
        Nr3r�r3r3r4rVr�zIFTPShell.removeFilecCr')ax
        Rename a file or directory.

        @param fromPath: The current name of the path.
        @type fromPath: C{list} of C{unicode}

        @param toPath: The desired new name of the path.
        @type toPath: C{list} of C{unicode}

        @return: A Deferred which fires when the path has been
        renamed, or which fails if the path cannot be renamed.
        Nr3)�fromPath�toPathr3r3r4r	ar�zIFTPShell.renamecCr')a
        Determine whether access to the given path is allowed.

        @param path: The path, as a list of segments

        @return: A Deferred which fires with None if access is allowed
        or which fails with a specific exception type if access is
        denied.
        Nr3r�r3r3r4r�or�zIFTPShell.accessr3cCr')z�
        Retrieve information about the given path.

        This is like list, except it will never return results about
        child paths.
        Nr3�r?�keysr3r3r4r�zr�zIFTPShell.statcCr')ae
        Retrieve information about the given path.

        If the path represents a non-directory, the result list should
        have only one entry with information about that non-directory.
        Otherwise, the result list should have an element for each
        child of the directory.

        @param path: The path, as a list of segments, to list
        @type path: C{list} of C{unicode} or C{bytes}

        @param keys: A tuple of keys desired in the resulting
        dictionaries.

        @return: A Deferred which fires with a list of (name, list),
        where the name is the name of the entry as a unicode string or
        bytes and each list contains values corresponding to the requested
        keys.  The following are possible elements of keys, and the
        values which should be returned for them:

            - C{'size'}: size in bytes, as an integer (this is kinda required)

            - C{'directory'}: boolean indicating the type of this entry

            - C{'permissions'}: a bitvector (see os.stat(foo).st_mode)

            - C{'hardlinks'}: Number of hard links to this entry

            - C{'modified'}: number of seconds since the epoch since entry was
              modified

            - C{'owner'}: string indicating the user owner of this entry

            - C{'group'}: string indicating the group owner of this entry
        Nr3r*r3r3r4r��r�zIFTPShell.listcCr')z�
        @param path: The path, as a list of segments, to open
        @type path: C{list} of C{unicode}

        @rtype: C{Deferred} which will fire with L{IReadFile}
        Nr3r�r3r3r4r��r�zIFTPShell.openForReadingcCr')z�
        @param path: The path, as a list of segments, to open
        @type path: C{list} of C{unicode}

        @rtype: C{Deferred} which will fire with L{IWriteFile}
        Nr3r�r3r3r4r��r�zIFTPShell.openForWritingN�r3)
r/r0r1r2r�r�rr	r�r�r�r�r�r3r3r3r4rq8s

%rqc@�eZdZdZdd�ZdS)�	IReadFilez0
    A file out of which bytes may be read.
    cCr')a
        Produce the contents of the given path to the given consumer.  This
        method may only be invoked once on each provider.

        @type consumer: C{IConsumer}

        @return: A Deferred which fires when the file has been
        consumed completely.
        Nr3)�consumerr3r3r4r��r�zIReadFile.sendN)r/r0r1r2r�r3r3r3r4r.�sr.c@r^)�
IWriteFilez1
    A file into which bytes may be written.
    cCr')z�
        Create a consumer which will write to this file.  This method may
        only be invoked once on each provider.

        @rtype: C{Deferred} of C{IConsumer}
        Nr3r3r3r3r4r��r�zIWriteFile.receivecCr')ae
        Perform any post-write work that needs to be done. This method may
        only be invoked once on each provider, and will always be invoked
        after receive().

        @rtype: C{Deferred} of anything: the value is ignored. The FTP client
        will not see their upload request complete until this Deferred has
        been fired.
        Nr3r3r3r3r4r�r�zIWriteFile.closeN)r/r0r1r2r�rr3r3r3r4r0�sr0cCsDg}t�|�}|�|j�t��D]}|j|jvr|�|j�q|S)z_
    Return the primary and supplementary groups for the given UID.

    @type uid: C{int}
    )	�pwd�getpwuidr=�pw_gid�grp�getgrall�pw_name�gr_mem�gr_gid)�uidrC�pwent�grentr3r3r4�
_getgroups�s
�r<�rc
Cs�|dkrtj}tj}tj}tj}n|dkr"tj}tj}tj}tj	}nt
d|�d���d}tj�|�r`|dkr9d}n't�|�}	||	j
@rK||	jkrKd}n||	j
@rY|t|�vrYd}n||	j
@r`d}|rut�||�sud}t�d|t��f�|S)	a�
    checks to see if uid has proper permissions to access path with mode

    @type uid: C{int}
    @param uid: numeric user id

    @type gid: C{int}
    @param gid: numeric group id

    @type spath: C{str}
    @param spath: the path on the server to test

    @type mode: C{str}
    @param mode: 'r' or 'w' (read or write)

    @rtype: C{bool}
    @return: True if the given credentials have the specified form of
        access to the given path
    r=�wz
Invalid mode z: must specify 'r' or 'w'FrTzUFilesystem grants permission to UID %d but it is inaccessible to me running as UID %d)r��S_IRUSR�S_IRGRP�S_IROTHr�R_OK�S_IWUSR�S_IWGRP�S_IWOTH�W_OK�
ValueErrorr?�exists�st_mode�st_uidr<r�rre�getuid)
r9�gid�spathr��usrr4�oth�amoder�rAr3r3r4�_testPermissions�s>


��rQc@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
d,dd�Zd,dd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+S)-�FTPAnonymousShellz�
    An anonymous implementation of IFTPShell

    @type filesystemRoot: L{twisted.python.filepath.FilePath}
    @ivar filesystemRoot: The path which is considered the root of
    this shell.
    cCrr`)�filesystemRoot)rdrSr3r3r4rb6rzFTPAnonymousShell.__init__cC�|j�|�Sr`)rS�
descendant�rdr?r3r3r4�_path9�zFTPAnonymousShell._pathcC�t�t��Sr`�r	rErmrVr3r3r4r�<rXzFTPAnonymousShell.makeDirectorycCrYr`rZrVr3r3r4r�?rXz!FTPAnonymousShell.removeDirectorycCrYr`rZrVr3r3r4rBrXzFTPAnonymousShell.removeFilecCrYr`rZ)rdr(r)r3r3r4r	ErXzFTPAnonymousShell.renamecCs|�|�}t�t��Sr`)rWr	rErmrVr3r3r4r�Hs
zFTPAnonymousShell.receivec
C�|�|�}|��rt�t|��Sz|�d�}Wn$ty/}zt|j|�WYd}~Sd}~wt	y;t��YSwt�
t|��S)a�
        Open C{path} for reading.

        @param path: The path, as a list of segments, to open.
        @type path: C{list} of C{unicode}
        @return: A L{Deferred} is returned that will fire with an object
            implementing L{IReadFile} if the file is successfully opened.  If
            C{path} is a directory, or if an exception is raised while trying
            to open the file, the L{Deferred} will fire with an error.
        r=N)rW�isdirr	rErO�open�OSErrorrQrCr�r��_FileReader)rdr?r�r�rPr3r3r4r�Ls
��z FTPAnonymousShell.openForReadingcCst�td��S)za
        Reject write attempts by anonymous users with
        L{PermissionDeniedError}.
        zSTOR not allowed)r	rErIrVr3r3r4r�esz FTPAnonymousShell.openForWritingc
Cs�|�|�}|��st�t|��Sz|��Wn$ty.}zt|j|�WYd}~Sd}~wt	y:t��YSwt�
d�Sr`)rWrHr	rErF�listdirr^rQrCr�r��rdr?r�rPr3r3r4r�ls
��
zFTPAnonymousShell.accessr3c
Cs�|�|�}|��r;z|�||�}Wn$ty)}zt|j|�WYd}~Sd}~wty5t��YSwt�	|�S|�
||��dd��S)NcSs|ddS)NrrTr3)�resr3r3r4r��sz(FTPAnonymousShell.stat.<locals>.<lambda>)rWr\�	_statNoder^rQrCr�r	rEr�r�r�)rdr?r+r��
statResultrPr3r3r4r�|s
��
zFTPAnonymousShell.statc	s|�|�����r���}�fdd�|D�}n���r*tjj��|j��g}�g}nt	�
t|��Sg}t||�D]C\}�g}|�
||f�|r{z|�|��|��Wq8tyl}zt|j|�WYd}~Sd}~wtyzt	�
�YSwq8t	�|�S)a
        Return the list of files at given C{path}, adding C{keys} stat
        informations if specified.

        @param path: the directory or file to check.
        @type path: C{str}

        @param keys: the list of desired metadata
        @type keys: C{list} of C{str}
        csg|]}��|��qSr3)�childr#��filePathr3r4r$�sz*FTPAnonymousShell.list.<locals>.<listcomp>N)rWr\r`�isfilerr?r��segmentsFromrSr	rErF�zipr=�extendrcr^rQrCr�r�)	rdr?r+�entries�fileEntriesr��fileName�entrPr3rfr4r��s.
���
zFTPAnonymousShell.listcs�����fdd�|D�S)z�
        Shortcut method to get stat info on a node.

        @param filePath: the node to stat.
        @type filePath: C{filepath.FilePath}

        @param keys: the stat keys to get.
        @type keys: C{iterable}
        csg|]}t�d|����qS)�_stat_)rS)r6�k�rgrdr3r4r$�sz/FTPAnonymousShell._statNode.<locals>.<listcomp>)�restat)rdrgr+r3rrr4rc�s
zFTPAnonymousShell._statNodecC�|��S)z�
        Get the filepath's size as an int

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{int} representing the size
        )�getsize�rd�fpr3r3r4�
_stat_size��zFTPAnonymousShell._stat_sizecCrt)z�
        Get the filepath's permissions object

        @param fp: L{twisted.python.filepath.FilePath}
        @return: L{twisted.python.filepath.Permissions} of C{fp}
        )�getPermissionsrvr3r3r4�_stat_permissions�ryz#FTPAnonymousShell._stat_permissionscCs z|��WStyYdSw)a�
        Get the number of hardlinks for the filepath - if the number of
        hardlinks is not yet implemented (say in Windows), just return 0 since
        stat-ing a file in Windows seems to return C{st_nlink=0}.

        (Reference:
        U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{int} representing the number of hardlinks
        r)�getNumberOfHardLinks�NotImplementedErrorrvr3r3r4�_stat_hardlinks�s

�z!FTPAnonymousShell._stat_hardlinkscCrt)z�
        Get the filepath's last modified date

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{int} as seconds since the epoch
        )�getModificationTimervr3r3r4�_stat_modified�ryz FTPAnonymousShell._stat_modifiedcC�\z|��}Wn
tyYdSwtdur*zt�|�dWSty)Yt|�Swt|�S)a�
        Get the filepath's owner's username.  If this is not implemented
        (say in Windows) return the string "0" since stat-ing a file in
        Windows seems to return C{st_uid=0}.

        (Reference:
        U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{str} representing the owner's username
        �0Nr)�	getUserIDr}r1r2�KeyErrorr�)rdrw�userIDr3r3r4�_stat_owner����zFTPAnonymousShell._stat_ownercCr�)a�
        Get the filepath's owner's group.  If this is not implemented
        (say in Windows) return the string "0" since stat-ing a file in
        Windows seems to return C{st_gid=0}.

        (Reference:
        U{http://stackoverflow.com/questions/5275731/os-stat-on-windows})

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{str} representing the owner's group
        r�Nr)�
getGroupIDr}r4�getgrgidr�r�)rdrw�groupIDr3r3r4�_stat_group�r�zFTPAnonymousShell._stat_groupcCrt)z�
        Get whether the filepath is a directory

        @param fp: L{twisted.python.filepath.FilePath}
        @return: C{bool}
        )r\rvr3r3r4�_stat_directoryryz!FTPAnonymousShell._stat_directoryNr,)r/r0r1r2rbrWr�r�rr	r�r�r�r�r�r�rcrxr{r~r�r�r�r�r3r3r3r4rR,s,

#
			rRc@�$eZdZdd�Zdd�Zdd�ZdS)r_cC�||_d|_dSr�)r�_sendrr3r3r4rb"�
z_FileReader.__init__cCsd|_|j��|Sr�)r�rr)rd�passthroughr3r3r4�_close&s
z_FileReader._closecCs6|jrJd��d|_t���|j|�}|�|j�|S)Nz0Can only call IReadFile.send *once* per instanceT)r�r
�
FileSender�beginFileTransferrr�r�)rdr/r�r3r3r4r�+s
z_FileReader.sendN)r/r0r1rbr�r�r3r3r3r4r_ sr_c@s8eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�ZdS)
�FTPShellz:
    An authenticated implementation of L{IFTPShell}.
    c
Csj|�|�}z|��Wn$ty#}zt|j|�WYd}~Sd}~wty/t��YSwt�d�Sr`)	rW�makedirsr^rQrCr�r	rEr�rar3r3r4r�8s
��
zFTPShell.makeDirectoryc
Cs�|�|�}|��rt�t|��Szt�|j�Wn$ty0}zt	|j
|�WYd}~Sd}~wty<t��YSwt�d�Sr`)
rWrhr	rErKr�rmdirr?r^rQrCr�r�rar3r3r4r�Cs
��
zFTPShell.removeDirectoryc
Cs�|�|�}|��rt�t|��Sz|��Wn$ty.}zt|j|�WYd}~Sd}~wt	y:t��YSwt�
d�Sr`)rWr\r	rErO�remover^rQrCr�r�rar3r3r4rSs
��
zFTPShell.removeFilec
Cs||�|�}|�|�}z
t�|j|j�Wn$ty,}zt|j|�WYd}~Sd}~wty8t�	�YSwt�
d�Sr`)rWrr	r?r^rQrCr�r	rEr�)rdr(r)rw�tprPr3r3r4r	cs

��
zFTPShell.renamec
Cr[)a�
        Open C{path} for writing.

        @param path: The path, as a list of segments, to open.
        @type path: C{list} of C{unicode}
        @return: A L{Deferred} is returned that will fire with an object
            implementing L{IWriteFile} if the file is successfully opened.  If
            C{path} is a directory, or if an exception is raised while trying
            to open the file, the L{Deferred} will fire with an error.
        r>N)rWr\r	rErOr]r^rQrCr�r��_FileWriter)rdr?r�rrPr3r3r4r�os
��zFTPShell.openForWritingN)	r/r0r1r2r�r�rr	r�r3r3r3r4r�3sr�c@r�)r�cCr�r�)r�_receiverr3r3r4rb�r�z_FileWriter.__init__cCs$|jrJd��d|_t�t|j��S)Nz4Can only call IWriteFile.receive *once* per instanceT)r�r	r�rrrhr3r3r4r��sz_FileWriter.receivecCs
t�d�Sr`)r	r�rhr3r3r4r�rz_FileWriter.closeN)r/r0r1rbr�rr3r3r3r4r��sr�c@�(eZdZdZdd�Zdd�Zdd�ZdS)	�BaseFTPRealmz{
    Base class for simple FTP realms which provides an easy hook for specifying
    the home directory for each user.
    cCst�|�|_dSr`)r�FilePath�
anonymousRoot)rdr�r3r3r4rb�rzBaseFTPRealm.__init__cCst|j�d���)a
        Return a L{FilePath} representing the home directory of the given
        avatar.  Override this in a subclass.

        @param avatarId: A user identifier returned from a credentials checker.
        @type avatarId: C{str}

        @rtype: L{FilePath}
        z" did not override getHomeDirectory)r}r(�rd�avatarIdr3r3r4�getHomeDirectory�s

�zBaseFTPRealm.getHomeDirectorycGsX|D]%}|tur'|tjurt|j�}nt|�|��}t|t|ddd��fSqtd��)Nr.cSr�r`r3r3r3r3r4r��r�z,BaseFTPRealm.requestAvatar.<locals>.<lambda>z3Only IFTPShell interface is supported by this realm)	rqr�	ANONYMOUSrRr�r�r�rSr})rdr��mindr
�ifacertr3r3r4�
requestAvatar�s
�zBaseFTPRealm.requestAvatarN)r/r0r1r2rbr�r�r3r3r3r4r��s
r�c@s"eZdZdZddd�Zdd�ZdS)	�FTPRealma"
    @type anonymousRoot: L{twisted.python.filepath.FilePath}
    @ivar anonymousRoot: Root of the filesystem to which anonymous
        users will be granted access.

    @type userHome: L{filepath.FilePath}
    @ivar userHome: Root of the filesystem containing user home directories.
    �/homecCst�||�t�|�|_dSr`)r�rbrr��userHome)rdr�r�r3r3r4rb�szFTPRealm.__init__cCrT)z�
        Use C{avatarId} as a single path segment to construct a child of
        C{self.userHome} and return that child.
        )r�rer�r3r3r4r���zFTPRealm.getHomeDirectoryN)r�)r/r0r1r2rbr�r3r3r3r4r��s
	r�c@r-)�SystemFTPRealmz�
    L{SystemFTPRealm} uses system user account information to decide what the
    home directory for a particular avatarId is.

    This works on POSIX but probably is not reliable on Windows.
    cCs,tj�d|�}|�d�rt���t�|�S)zx
        Return the system-defined home directory of the system user account
        with the name C{avatarId}.
        �~)rr?�
expanduserr:rxryrr�)rdr�r?r3r3r4r��s

zSystemFTPRealm.getHomeDirectoryN)r/r0r1r2r�r3r3r3r4r��sr�c@r|)�ConnectionLostNr~r3r3r3r4r��rr�c@r|)�
CommandFailedNr~r3r3r3r4r��rr�c@r|)�BadResponseNr~r3r3r3r4r��rr�c@r|)�UnexpectedResponseNr~r3r3r3r4r�	rr�c@r|)�UnexpectedDataNr~r3r3r3r4r�	rr�c@seZdZddd�Zdd�ZdS)�
FTPCommandNrcCs&||_t��|_d|_||_d|_dS)NrT)�textr	r�r��ready�public�transferDeferred)rdr�r�r3r3r4rb	s


zFTPCommand.__init__cCs|jr|j�|�dSdSr`)r�r�r�)rdrr3r3r4rE	s�zFTPCommand.fail�Nr)r/r0r1rbrEr3r3r3r4r�
	s
r�c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�ProtocolWrappercCs||_||_dSr`)�originalr�)rdr�r�r3r3r4rb	r�zProtocolWrapper.__init__cCrr`)r��makeConnection�rdr�r3r3r4r�	rzProtocolWrapper.makeConnectioncCrr`)r�r�r�r3r3r4r�	rzProtocolWrapper.dataReceivedcCs|j�|�|j�d�dSr`)r�r�r�r�r�r3r3r4r�"	szProtocolWrapper.connectionLostN)r/r0r1rbr�r�r�r3r3r3r4r�	s
r�c@r-)�IFinishableConsumerzA
    A Consumer for producers that finish.

    @since: 11.0
    cCr')z6
        The producer has finished producing.
        Nr3r3r3r3r4�finish/	r�zIFinishableConsumer.finishN)r/r0r1r2r�r3r3r3r4r�(	sr�c@sLeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dS)�SenderProtocolcCst��|_t��|_dSr`)r	r��connectedDeferredr�rhr3r3r4rb7	s
zSenderProtocol.__init__cCstd��)Nz<Received data from the server on a send-only data-connection)r�r�r3r3r4r�?	s�zSenderProtocol.dataReceivedcCstj�||�|j�|�dSr`)r�Protocolr�r�r�r�r3r3r4r�D	szSenderProtocol.makeConnectioncCs,|�tj�r|j�d�dS|j�|�dS)Nzconnection done)r:r�ConnectionDoner�r�r�r�r3r3r4r�H	szSenderProtocol.connectionLostcCrr`r�r�r3r3r4r�O	rzSenderProtocol.writecCs|j�||�dS)zA
        Register the given producer with our transport.
        Nr�r�r3r3r4r�R	szSenderProtocol.registerProducercCs|j��dS)z@
        Unregister the previously registered producer.
        N)r�r�rhr3r3r4r�X	�z!SenderProtocol.unregisterProducercCr�r`r3rhr3r3r4r�^	r�zSenderProtocol.finishN)r/r0r1rbr�r�r�r�r�r�r�r3r3r3r4r�5	sr�cCs�t�dd|�}dd�|�d�D�}|D]}|dks|dkr#td||��q|\}}}}}}	|�d	|�d	|�d	|��}
t|�d
>t|	�}|
|fS)ze
    Decode an FTP response specifying a host and port.

    @return: a 2-tuple of (host, port).
    z[^0-9, ]r7cSsg|]}t|����qSr3)r��stripr#r3r3r4r$i	�z"decodeHostPort.<locals>.<listcomp>r�r�zOut of ranger6r�)�re�subr;rGr�)r��abcdef�parsed�x�a�b�cr�rPr�r�r�r3r3r4�decodeHostPortb	s�r�cCs,|�d�t|d?�t|d�g}d�|�S)Nr6r��r�)r;r�r�)r�r��numbersr3r3r4r�s	s"
r�cCs|�tj�|jjSr`)rwr	�
FirstErrorr5�
subFailurer{r3r3r4�_unwrapFirstErrorx	sr�c@r)�FTPDataPortFactoryz_
    Factory for data connections that use the PORT command

    (i.e. "active" transfers)
    FcCs||j_|j��|jSr`)rr�r�r�)rdr�r3r3r4r��	s
z FTPDataPortFactory.buildProtocolN)r/r0r1r2�noisyr�r3r3r3r4r�}	sr�c@szeZdZdZdZdZdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zddd�Z
dd�Zdd�Zdd�Zdd�ZdS)�FTPClientBasicz'
    Foundations of an FTP client.
    Fr�cCs<g|_d|_t���|j�|_|j�|j�g|_	d|_
dSr�)�actionQueue�greetingr	r�r��_cb_greeting�nextDeferredrOrEri�_failedrhr3r3r4rb�	s
zFTPClientBasic.__init__cCs|�|�dS)z8
        Give an error to any queued deferreds.
        N��_fail�rdrr3r3r4rE�	r�zFTPClientBasic.failcCsn|jr|Sd|_|jr$z|j�t�td|���Wn
tjy#Ynw|jD]
}|�	t�td|���q'|S)z/
        Errback all queued deferreds.
        rTzFTP connection lost)
r�r�r�r�Failurer�r	�AlreadyCalledErrorr�rE)rdr�
ftpCommandr3r3r4r��	s ��
�zFTPClientBasic._failcCrr`)r�)rdr�r3r3r4r��	rzFTPClientBasic._cb_greetingcCs4|durdSt|t�r|�|j�}tj�||�dS)z�
        Sends a line, unless line is None.

        @param line: Line to send
        @type line: L{bytes} or L{unicode}
        N)r%r�r�r�r
�LineReceiverr�r�r3r3r4r��	s

zFTPClientBasic.sendLinecCs�|��}|dur
d|_dS|js#|j�d|�t�d|j�d|_dS|jdkr-|�	|�|j
r8t�d|j�|j
|_|�|j�dS)zD
        (Private) Processes the next command in the queue.
        Nrg�?�PORTz<-- %s)�popCommandQueuer�r�r��insertrr�sendNextCommandr��generatePortCommandr�rrer�r��rdr�r3r3r4r��	s

zFTPClientBasic.sendNextCommandcCsF|j�|�t|j�dkr|jdur|jdur!|��dSdSdSdS)a
        Add an FTPCommand object to the queue.

        If it's the only thing in the queue, and we are connected and we aren't
        waiting for a response of an earlier command, the command will be sent
        immediately.

        @param ftpCommand: an L{FTPCommand}
        rTN)r�r=r
r�r�r�r�r3r3r4�queueCommand�	s


�zFTPClientBasic.queueCommandrTcCst||�}|�|�|jS)au
        Queues a string to be issued as an FTP command

        @param command: string of an FTP command to queue
        @param public: a flag intended for internal use by FTPClient.  Don't
            change it unless you know what you're doing.

        @return: a L{Deferred} that will be called when the response to the
            command has been received.
        )r�r�r�)rdrTr�r�r3r3r4�queueStringCommand�	s

z!FTPClientBasic.queueStringCommandcCs|jr	|j�d�SdS)zR
        Return the front element of the command queue, or None if empty.
        rN)r�r<rhr3r3r4r�
szFTPClientBasic.popCommandQueuecs�g}�jd|dd�}|�|�|dur3td|dd������|��j���fdd�}|�|�|D]}|��j�|�dd	��q5dS)
a
        Login: send the username, send the password.

        If the password is L{None}, the PASS command won't be sent.  Also, if
        the response to the USER command has a response code of 230 (User
        logged in), then PASS won't be sent either.
        zUSER r�r�NzPASS cs|d�d�r
�j���|S)Nr�230)r:r�r�)ri��passwordCmdrdr3r4�cancelPasswordIfNotNeeded"
sz<FTPClientBasic.queueLogin.<locals>.cancelPasswordIfNotNeededcSr�r`r3�r�r3r3r4r�/
r�z+FTPClientBasic.queueLogin.<locals>.<lambda>)r�r=r�r�r�r�rOrE)rdrpr��	deferreds�userDeferredr�r�r3r�r4�
queueLogin
s	


�zFTPClientBasic.queueLogincCs�ttkr
|�|j�}|jrt�d|�|j�|�t	�
d|�}|s$dS|dd�}|ddkr2dS|jdurA|�t
|j��dS|j}g|_|ddvrT|j�|�n%|ddvrf|j�t�t|���nt�d	|���|j�t�t|���|��dS)
zM
        (Private) Parses the response messages from the FTP server.
        z--> %sz\d{3} Nr��1)�2�3)�4�5z"Server sent invalid response code )r�r�rJr�r�rrerir=r��matchr�rEr�r�r�rr�r�r�r�)rdr��codeIsValidr�rir3r3r4rQ1
s.
zFTPClientBasic.lineReceivedcCs|�|�dSr`r�r�r3r3r4r�a
r�zFTPClientBasic.connectionLostN)rT)r/r0r1r2r�r�rbrEr�r�r�r�r�r�r�r�rQr�r3r3r3r4r��	s 

	$0r�c@r�)	�_PassiveConnectionFactoryFcCrr`)�
protoInstance)rdr�r3r3r4rbh
rz"_PassiveConnectionFactory.__init__cCs||j_|jSr`)r�r�r�r3r3r4r�k
sz'_PassiveConnectionFactory.buildProtocolcCstd|�}|jj�|�dS)NzConnection Failed)r}r�r�r�)rdrr�rPr3r3r4ro
s
z0_PassiveConnectionFactory.clientConnectionFailedN)r/r0r1r�rbr�rr3r3r3r4r�e
s
r�c@s�eZdZdZejZ	d1dd�Zdd�Zd	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
dd�Zd2dd�ZeZd2dd�ZeZdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0S)3�	FTPClientaI
    L{FTPClient} is a client implementation of the FTP protocol which
    exposes FTP commands as methods which return L{Deferred}s.

    Each command method returns a L{Deferred} which is called back when a
    successful response code (2xx or 3xx) is received from the server or
    which is error backed if an error response code (4xx or 5xx) is received
    from the server or if a protocol violation occurs.  If an error response
    code is received, the L{Deferred} fires with a L{Failure} wrapping a
    L{CommandFailed} instance.  The L{CommandFailed} instance is created
    with a list of the response lines received from the server.

    See U{RFC 959<http://www.ietf.org/rfc/rfc959.txt>} for error code
    definitions.

    Both active and passive transfers are supported.

    @ivar passive: See description in __init__.
    r�twisted@twistedmatrix.comrTcCs t�|�|�||�||_dS)ay
        Constructor.

        I will login as soon as I receive the welcome message from the server.

        @param username: FTP username
        @param password: FTP password
        @param passive: flag that controls if I use active or passive data
            connections.  You can also change this after construction by
            assigning to C{self.passive}.
        N)r�rbr��passive)rdrpr�rr3r3r4rb�
s

zFTPClient.__init__cCs|j��|�|�dS)zM
        Disconnect, and also give an error to any queued deferreds.
        N)r�r�r�r�r3r3r4rE�
s
zFTPClient.failcCs$t�|�}t|t���}|�||�S)a�
        Retrieves a file or listing generated by the given command,
        feeding it to the given protocol.

        @param commands: list of strings of FTP commands to execute then
            receive the results of (e.g. C{LIST}, C{RETR})
        @param protocol: A L{Protocol} B{instance} e.g. an
            L{FTPFileListProtocol}, or something that can be adapted to one.
            Typically this will be an L{IConsumer} implementation.

        @return: L{Deferred}.
        )r
�	IProtocolr�r	r��_openDataConnection)rd�commandsr�wrapperr3r3r4�receiveFromConnection�
s

zFTPClient.receiveFromConnectioncCs:t�|||�|jddd�}|�|j�|�dd��dS)zg
        Login: send the username, send the password, and
        set retrieval mode to binary
        zTYPE Irr�cSr�r`r3r�r3r3r4r��
r�z&FTPClient.queueLogin.<locals>.<lambda>N)r�r�r�rOrE)rdrpr�r�r3r3r4r��
szFTPClient.queueLogincCst�}|�||�}|j|fS)aQ
        XXX

        @return: A tuple of two L{Deferred}s:
                  - L{Deferred} L{IFinishableConsumer}. You must call
                    the C{finish} method on the IFinishableConsumer when the
                    file is completely transferred.
                  - L{Deferred} list of control-connection responses.
        )r�rr�)rdrrAr=r3r3r4�sendToConnection�
s

zFTPClient.sendToConnectioncsJdd�|D�}tjdd�|D�ddd�}|�t��jrZdg����fdd�}td	�}��|�|j�|���j	�||j�jg}tj|ddd�}|�t��fd
d�}	|�
|	�n?td�}
�j|
_�|
_|
j�|
jj
���|
�d
d�|
_dd�|
_	|�|
fdd��||
j|
jg}tj|ddd�}|�t�|D]}��|�q�|S)z5
        This method returns a DeferredList.
        cSsg|]}t|dd��qS)rTr�)r�)r6rTr3r3r4r$�
r�z1FTPClient._openDataConnection.<locals>.<listcomp>cSsg|]}|j�qSr3)r�)r6r?r3r3r4r$�
sT)�fireOnOneErrback�
consumeErrorsNcs6t|ddd��\}}t��}��|||��d<dS)z5Connect to the port specified in the response to PASVrSrNr)r�r��connectFactory)rir�r�r���_mutablerrdr3r4�	doPassive�
sz0FTPClient._openDataConnection.<locals>.doPassiver cSs|do|d��|S|Sr�)r)r��mr3r3r4r�
s�z,FTPClient._openDataConnection.<locals>.closer�cS�|Sr`r3rBr3r3r4r�	r�z/FTPClient._openDataConnection.<locals>.<lambda>cSrr`r3)rr3r3r4r�
r�cSs|�|�p|Sr`)rE)rP�pcr3r3r4r�
s)r	�DeferredListrOr�rr�r�r�r�rEr�r�rr�r�)rdrr�cmds�cmdsDeferredr
�pasvCmdr�r�r�portCmdr?r3rr4r�
s<�


	



zFTPClient._openDataConnectioncCs\t�}|j|_t�d|�}||_|fdd�}||_|j��j}|��j}dt	||�|_
dS)zG
        (Private) Generates the text of a given PORT command.
        rcSs|jr|��|Sr`)r�r�)r�listenerr3r3r4�listenerFail.sz3FTPClient.generatePortCommand.<locals>.listenerFailzPORT N)r�rrrr�rEr�r�r�r�r�)rdrr�rrr�r�r3r3r4r�s
zFTPClient.generatePortCommandcCs|�dd�S)zK
        Returns a FTP escaped path (replace newlines with nulls).
        �
r9)rXrVr3r3r4�
escapePath:r�zFTPClient.escapePathrcCs4d|�|�g}|r|�ddt|��|�||�S)a�
        Retrieve a file from the given path

        This method issues the 'RETR' FTP command.

        The file is fed into the given Protocol instance.  The data connection
        will be passive if self.passive is set.

        @param path: path to file that you wish to receive.
        @param protocol: a L{Protocol} instance.
        @param offset: offset to start downloading from

        @return: L{Deferred}
        zRETR r�REST )rr�r�r)rdr?r�offsetrr3r3r4�retrieveFileAszFTPClient.retrieveFilecCs2d|�|�g}|r|�ddt|��|�|�S)a�
        Store a file at the given path.

        This method issues the 'STOR' FTP command.

        @return: A tuple of two L{Deferred}s:
                  - L{Deferred} L{IFinishableConsumer}. You must call
                    the C{finish} method on the IFinishableConsumer when the
                    file is completely transferred.
                  - L{Deferred} list of control-connection responses.
        zSTOR rr)rr�r�r)rdr?rrr3r3r4�	storeFileWs
zFTPClient.storeFilecsp��d��|��}��d��|��}g�t������fdd����fdd�}|��j|�|����S)a]
        Rename a file.

        This method issues the I{RNFR}/I{RNTO} command sequence to rename
        C{pathFrom} to C{pathTo}.

        @param pathFrom: the absolute path to the file to be renamed
        @type pathFrom: C{str}

        @param pathTo: the absolute path to rename the file to.
        @type pathTo: C{str}

        @return: A L{Deferred} which fires when the rename operation has
            succeeded or failed.  If it succeeds, the L{Deferred} is called
            back with a two-tuple of lists.  The first list contains the
            responses to the I{RNFR} command.  The second list contains the
            responses to the I{RNTO} command.  If either I{RNFR} or I{RNTO}
            fails, the L{Deferred} is errbacked with L{CommandFailed} or
            L{BadResponse}.
        @rtype: L{Deferred}

        @since: 8.2
        zRNFR zRNTO cs�|fSr`r3)�
toResponse)�fromResponser3r4r��r�z"FTPClient.rename.<locals>.<lambda>cs�����|�dSr`)r�r�r{)rCrdr3r4�ebFrom�sz FTPClient.rename.<locals>.ebFrom)r�rr	r�r�rNrk�
chainDeferred)rd�pathFrom�pathTo�
renameFrom�renameTor r3)rrCrdr4r	js
zFTPClient.renamecC�$|durd}|�d|�|�g|�S)a|
        Retrieve a file listing into the given protocol instance.

        This method issues the 'LIST' FTP command.

        @param path: path to get a file listing for.
        @param protocol: a L{Protocol} instance, probably a
            L{FTPFileListProtocol} instance.  It can cope with most common file
            listing formats.

        @return: L{Deferred}
        Nr7zLIST �rr�rdr?rr3r3r4r��s
zFTPClient.listcCr&)a1
        Retrieve a short file listing into the given protocol instance.

        This method issues the 'NLST' FTP command.

        NLST (should) return a list of filenames, one per line.

        @param path: path to get short file listing for.
        @param protocol: a L{Protocol} instance.
        Nr7zNLST r'r(r3r3r4�nlst�szFTPClient.nlstcC�|�d|�|��S)z�
        Issues the CWD (Change Working Directory) command.

        @return: a L{Deferred} that will be called when done.
        zCWD �r�rrVr3r3r4r>�sz
FTPClient.cwdcCr*)a@
        Make a directory

        This method issues the MKD command.

        @param path: The path to the directory to create.
        @type path: C{str}

        @return: A L{Deferred} which fires when the server responds.  If the
            directory is created, the L{Deferred} is called back with the
            server response.  If the server response indicates the directory
            was not created, the L{Deferred} is errbacked with a L{Failure}
            wrapping L{CommandFailed} or L{BadResponse}.
        @rtype: L{Deferred}

        @since: 8.2
        zMKD r+rVr3r3r4r���zFTPClient.makeDirectorycCr*)a^
        Delete a file on the server.

        L{removeFile} issues a I{DELE} command to the server to remove the
        indicated file.  Note that this command cannot remove a directory.

        @param path: The path to the file to delete. May be relative to the
            current dir.
        @type path: C{str}

        @return: A L{Deferred} which fires when the server responds.  On error,
            it is errbacked with either L{CommandFailed} or L{BadResponse}.  On
            success, it is called back with a list of response lines.
        @rtype: L{Deferred}

        @since: 8.2
        zDELE r+rVr3r3r4r�r,zFTPClient.removeFilecCr*)a`
        Delete a directory on the server.

        L{removeDirectory} issues a I{RMD} command to the server to remove the
        indicated directory. Described in RFC959.

        @param path: The path to the directory to delete. May be relative to
            the current working directory.
        @type path: C{str}

        @return: A L{Deferred} which fires when the server responds. On error,
            it is errbacked with either L{CommandFailed} or L{BadResponse}. On
            success, it is called back with a list of response lines.
        @rtype: L{Deferred}

        @since: 11.1
        zRMD r+rVr3r3r4r��r,zFTPClient.removeDirectorycCr�)z
        Issues the CDUP (Change Directory UP) command.

        @return: a L{Deferred} that will be called when done.
        �CDUP�r�rhr3r3r4�cdup�s
zFTPClient.cdupcCr�)ah
        Issues the PWD (Print Working Directory) command.

        The L{getDirectory} does the same job but automatically parses the
        result.

        @return: a L{Deferred} that will be called when done.  It is up to the
            caller to interpret the response, but the L{parsePWDResponse}
            method in this module should work.
        �PWDr.rhr3r3r4r1s
z
FTPClient.pwdcCsdd�}|���|�S)a
        Returns the current remote directory.

        @return: a L{Deferred} that will be called back with a C{str} giving
            the remote directory or which will errback with L{CommandFailed}
            if an error response is returned.
        c	Sspzt|d�dd�d�dkrt�Wnttfy$t�t|��YSwt|d�}|dur6t�t|��S|S)NrrHrTi)r�r;rG�
IndexErrorrr�r��parsePWDResponse)rCr?r3r3r4�cbParses��z'FTPClient.getDirectory.<locals>.cbParse)r1r�)rdr3r3r3r4�getDirectorys	zFTPClient.getDirectorycCr�)z�
        Issues the I{QUIT} command.

        @return: A L{Deferred} that fires when the server acknowledges the
            I{QUIT} command.  The transport should not be disconnected until
            this L{Deferred} fires.
        rr.rhr3r3r4�quit*s
zFTPClient.quitN)rrrT)r)r/r0r1r2rr�r
rbrErr�rrr�rr�retrr�storr	r�r)r>r�rr�r/r1r4r5r3r3r3r4r�t
s6
�G#

0
r�c@sJeZdZdZe�d�ZdZdZdd�Z	dd�Z
d	d
�Zdd�Zd
d�Z
dS)�FTPFileListProtocola�
    Parser for standard FTP file listings

    This is the evil required to match::

        -rw-r--r--   1 root     other        531 Jan 29 03:26 README

    If you need different evil for a wacky FTP server, you can
    override either C{fileLinePattern} or C{parseDirectoryLine()}.

    It populates the instance attribute self.files, which is a list containing
    dicts with the following keys (examples from the above line):
        - filetype:   e.g. 'd' for directories, or '-' for an ordinary file
        - perms:      e.g. 'rw-r--r--'
        - nlinks:     e.g. 1
        - owner:      e.g. 'root'
        - group:      e.g. 'other'
        - size:       e.g. 531
        - date:       e.g. 'Jan 29 03:26'
        - filename:   e.g. 'README'
        - linktarget: e.g. 'some/file'

    Note that the 'date' value will be formatted differently depending on the
    date.  Check U{http://cr.yp.to/ftp.html} if you really want to try to parse
    it.

    It also matches the following::
        -rw-r--r--   1 root     other        531 Jan 29 03:26 I HAVE\ SPACE
           - filename:   e.g. 'I HAVE SPACE'

        -rw-r--r--   1 root     other        531 Jan 29 03:26 LINK -> TARGET
           - filename:   e.g. 'LINK'
           - linktarget: e.g. 'TARGET'

        -rw-r--r--   1 root     other        531 Jan 29 03:26 N S -> L S
           - filename:   e.g. 'N S'
           - linktarget: e.g. 'L S'

    @ivar files: list of dicts describing the files in this listing
    z�^(?P<filetype>.)(?P<perms>.{9})\s+(?P<nlinks>\d*)\s*(?P<owner>\S+)\s+(?P<group>\S+)\s+(?P<size>\d+)\s+(?P<date>...\s+\d+\s+[\d:]+)\s+(?P<filename>.{1,}?)( -> (?P<linktarget>[^\r]*))?\r?$�
r�cCs
g|_dSr`)�filesrhr3r3r4rbhrzFTPFileListProtocol.__init__cCsBttkr
|�|j�}|�|�}|dur|�|�dS|�|�dSr`)r�r�rJr��parseDirectoryLine�unknownLine�addFile)rdr�r�r3r3r4rQks
z FTPFileListProtocol.lineReceivedcCst|j�|�}|durdS|��}|d�dd�|d<t|d�|d<t|d�|d<|dr8|d�dd�|d<|S)z�
        Return a dictionary of fields, or None if line cannot be parsed.

        @param line: line of text expected to contain a directory entry
        @type line: str

        @return: dict
        N�filenamez\ rH�nlinksr��
linktarget)�fileLinePatternr��	groupdictrXr�)rdr�r�r�r3r3r4r;ts	z&FTPFileListProtocol.parseDirectoryLinecCs|j�|�dS)a�
        Append file information dictionary to the list of known files.

        Subclasses can override or extend this method to handle file
        information differently without affecting the parsing of data
        from the server.

        @param info: dictionary containing the parsed representation
                     of the file information
        @type info: dict
        N)r:r=)rdr�r3r3r4r=�szFTPFileListProtocol.addFilecCr')a
        Deal with received lines which could not be parsed as file
        information.

        Subclasses can override this to perform any special processing
        needed.

        @param line: unparsable line as received
        @type line: str
        Nr3r�r3r3r4r<�szFTPFileListProtocol.unknownLineN)r/r0r1r2r��compilerA�	delimiterr�rbrQr;r=r<r3r3r3r4r85s)�	r8cCs t�d|�}|r|��dSdS)z�
    Returns the path from a response to a PWD command.

    Responses typically look like::

        257 "/home/andrew" is current directory.

    For this example, I will return C{'/home/andrew'}.

    If I can't find the path, I return L{None}.
    z"(.*)"rN)r��search�groups)rir�r3r3r4r2�sr2r`)r=)�r2rCrUrr�r�r�r4r1�ImportError�zope.interfacerr�twistedr�twisted.credrrrrxrr�r	r
rr�twisted.protocolsr
r�twisted.pythonrrr�RESTART_MARKER_REPLY�SERVICE_READY_IN_N_MINUTESr�r�r�r�r��CMD_NOT_IMPLMNTD_SUPERFLUOUS�SYS_STATUS_OR_HELP_REPLYr
�
DIR_STATUSr��HELP_MSGr��SVC_READY_FOR_NEW_USERr,�SVC_CLOSING_CTRL_CNXr� DATA_CNX_OPEN_NO_XFR_IN_PROGRESS�CLOSING_DATA_CNXr�r��ENTERING_EPSV_MODEr�r~r�r�r�rorn�NEED_ACCT_FOR_LOGINr�SVC_NOT_AVAIL_CLOSING_CTRL_CNXrr�r��REQ_ACTN_ABRTD_FILE_UNAVAIL�REQ_ACTN_ABRTD_LOCAL_ERR�REQ_ACTN_ABRTD_INSUFF_STORAGErurwryrr�r{r_r��NEED_ACCT_FOR_STORrkrprnrqr=rrrs�
PAGE_TYPE_UNK�EXCEEDED_STORAGE_ALLOC�FILENAME_NOT_ALLOWEDrfrar.rBrQrVrWr]r_rFrmrIrKrMrOrtrvrxrzr}r�r�r�r�r��	IConsumerr�r��
ClientFactoryr�r	rr�r�TimeoutMixinrr!rrqr.r0r<rQrRr_r�r��IRealmr�r�r�r�r�r�r�r�r�r�r�r�r�r�r��
ServerFactoryr�r�r�r�r8r2r3r3r3r4�<module>s�����
���
���������������� �!�#�$�%�'�(�*�+�.�0�2�3�4�5�7�:�;�<�=�>�?�@�A�B�C�D�E�F�Q

!				c
O,
8tU"%

,VDp

Spamworldpro Mini