/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/transport/ftp.py

  • Committer: Vincent Ladeuil
  • Date: 2007-06-06 14:26:08 UTC
  • mto: (2485.8.44 bzr.connection.sharing)
  • mto: This revision was merged to the branch mainline in revision 2646.
  • Revision ID: v.ladeuil+lp@free.fr-20070606142608-i9ufaqewadslf1cn
Finish sftp refactoring. Test suite passing.

* bzrlib/transport/sftp.py:
(clear_connection_cache): Deprecated.
(_sftp_connect, _sftp_connect_uncached): Deleted.
(SFTPTransport.__init__): Simplified.
(SFTPTransport._create_connection): New method. Copied from
_sftp_connect_uncached
(SFTPTransport._get_sftp): New method. Ensures that the connection
is established.
(SFTPTransport.clone): Deleted.
(SFTPTransport.has, SFTPTransport.get, SFTPTransport.readv,
SFTPTransport._put,
SFTPTransport._put_non_atomic_helper._open_and_write_file,
SFTPTransport._mkdir, SFTPTransport.append_file,
SFTPTransport.rename, SFTPTransport._rename_and_overwrite,
SFTPTransport.delete, SFTPTransport.rmdir, SFTPTransport.stat):
Use _get_sftp.

* bzrlib/tests/test_transport_implementations.py:
(TransportTests.test_connection_error): Simplified now that sftp
does not connection on construction.

* bzrlib/tests/test_sftp_transport.py:
(SFTPLockTests.test_sftp_locks): Delete test_multiple_connections.
(FakeSFTPTransport): Deleted.
(SFTPNonServerTest.test_parse_url_with_home_dir,
SFTPNonServerTest.test_relpath,
SSHVendorBadConnection.test_bad_connection_paramiko): Delete the
from_transport parameter as it's not needed anymore.
(SFTPLatencyKnob.test_latency_knob_slows_transport,
SFTPLatencyKnob.test_default): Force connection by issuing a
request.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
16
"""Implementation of Transport over ftp.
18
17
 
19
18
Written by Daniel Silverstone <dsilvers@digital-scurf.org> with serious
26
25
"""
27
26
 
28
27
from cStringIO import StringIO
 
28
import asyncore
 
29
import errno
29
30
import ftplib
30
 
import getpass
31
31
import os
32
 
import random
33
 
import socket
 
32
import os.path
 
33
import urllib
 
34
import urlparse
 
35
import select
34
36
import stat
 
37
import threading
35
38
import time
 
39
import random
 
40
from warnings import warn
36
41
 
37
42
from bzrlib import (
38
 
    config,
39
43
    errors,
40
44
    osutils,
41
45
    urlutils,
42
46
    )
43
47
from bzrlib.trace import mutter, warning
44
48
from bzrlib.transport import (
45
 
    AppendBasedFileStream,
 
49
    Server,
46
50
    ConnectedTransport,
47
 
    _file_streams,
48
 
    register_urlparse_netloc_protocol,
49
 
    Server,
50
51
    )
51
 
 
52
 
 
53
 
register_urlparse_netloc_protocol('aftp')
 
52
from bzrlib.transport.local import LocalURLServer
 
53
import bzrlib.ui
 
54
 
 
55
_have_medusa = False
54
56
 
55
57
 
56
58
class FtpPathError(errors.PathError):
58
60
 
59
61
 
60
62
class FtpStatResult(object):
61
 
 
62
 
    def __init__(self, f, abspath):
 
63
    def __init__(self, f, relpath):
63
64
        try:
64
 
            self.st_size = f.size(abspath)
 
65
            self.st_size = f.size(relpath)
65
66
            self.st_mode = stat.S_IFREG
66
67
        except ftplib.error_perm:
67
68
            pwd = f.pwd()
68
69
            try:
69
 
                f.cwd(abspath)
 
70
                f.cwd(relpath)
70
71
                self.st_mode = stat.S_IFDIR
71
72
            finally:
72
73
                f.cwd(pwd)
75
76
_number_of_retries = 2
76
77
_sleep_between_retries = 5
77
78
 
78
 
# FIXME: there are inconsistencies in the way temporary errors are
79
 
# handled. Sometimes we reconnect, sometimes we raise an exception. Care should
80
 
# be taken to analyze the implications for write operations (read operations
81
 
# are safe to retry). Overall even some read operations are never
82
 
# retried. --vila 20070720 (Bug #127164)
83
79
class FtpTransport(ConnectedTransport):
84
80
    """This is the transport agent for ftp:// access."""
85
81
 
86
 
    def __init__(self, base, _from_transport=None):
 
82
    def __init__(self, base, from_transport=None):
87
83
        """Set the base path where files will be stored."""
88
 
        if not (base.startswith('ftp://') or base.startswith('aftp://')):
89
 
            raise ValueError(base)
90
 
        super(FtpTransport, self).__init__(base,
91
 
                                           _from_transport=_from_transport)
 
84
        assert base.startswith('ftp://') or base.startswith('aftp://')
 
85
        super(FtpTransport, self).__init__(base, from_transport)
92
86
        self._unqualified_scheme = 'ftp'
93
87
        if self._scheme == 'aftp':
94
88
            self.is_active = True
95
89
        else:
96
90
            self.is_active = False
97
91
 
98
 
        # Most modern FTP servers support the APPE command. If ours doesn't, we
99
 
        # (re)set this flag accordingly later.
100
 
        self._has_append = True
101
 
 
102
92
    def _get_FTP(self):
103
93
        """Return the ftplib.FTP instance for this object."""
104
94
        # Ensures that a connection is established
109
99
            self._set_connection(connection, credentials)
110
100
        return connection
111
101
 
112
 
    connection_class = ftplib.FTP
113
 
 
114
102
    def _create_connection(self, credentials=None):
115
103
        """Create a new connection with the provided credentials.
116
104
 
118
106
 
119
107
        :return: The created connection and its associated credentials.
120
108
 
121
 
        The input credentials are only the password as it may have been
122
 
        entered interactively by the user and may be different from the one
123
 
        provided in base url at transport creation time.  The returned
124
 
        credentials are username, password.
 
109
        The credentials are only the password as it may have been entered
 
110
        interactively by the user and may be different from the one provided
 
111
        in base url at transport creation time.
125
112
        """
126
113
        if credentials is None:
127
 
            user, password = self._user, self._password
 
114
            password = self._password
128
115
        else:
129
 
            user, password = credentials
 
116
            password = credentials
130
117
 
131
 
        auth = config.AuthenticationConfig()
132
 
        if user is None:
133
 
            user = auth.get_user('ftp', self._host, port=self._port,
134
 
                                 default=getpass.getuser())
135
118
        mutter("Constructing FTP instance against %r" %
136
 
               ((self._host, self._port, user, '********',
 
119
               ((self._host, self._port, self._user, '********',
137
120
                self.is_active),))
138
121
        try:
139
 
            connection = self.connection_class()
 
122
            connection = ftplib.FTP()
140
123
            connection.connect(host=self._host, port=self._port)
141
 
            self._login(connection, auth, user, password)
 
124
            if self._user and self._user != 'anonymous' and \
 
125
                    password is not None: # '' is a valid password
 
126
                get_password = bzrlib.ui.ui_factory.get_password
 
127
                password = get_password(prompt='FTP %(user)s@%(host)s password',
 
128
                                        user=self._user, host=self._host)
 
129
            connection.login(user=self._user, passwd=password)
142
130
            connection.set_pasv(not self.is_active)
143
 
            # binary mode is the default
144
 
            connection.voidcmd('TYPE I')
145
 
        except socket.error, e:
146
 
            raise errors.SocketConnectionError(self._host, self._port,
147
 
                                               msg='Unable to connect to',
148
 
                                               orig_error= e)
149
131
        except ftplib.error_perm, e:
150
132
            raise errors.TransportError(msg="Error setting up connection:"
151
133
                                        " %s" % str(e), orig_error=e)
152
 
        return connection, (user, password)
153
 
 
154
 
    def _login(self, connection, auth, user, password):
155
 
        # '' is a valid password
156
 
        if user and user != 'anonymous' and password is None:
157
 
            password = auth.get_password('ftp', self._host,
158
 
                                         user, port=self._port)
159
 
        connection.login(user=user, passwd=password)
 
134
        return connection, password
160
135
 
161
136
    def _reconnect(self):
162
137
        """Create a new connection with the previously used credentials"""
163
 
        credentials = self._get_credentials()
 
138
        credentials = self.get_credentials()
164
139
        connection, credentials = self._create_connection(credentials)
165
140
        self._set_connection(connection, credentials)
166
141
 
167
 
    def _translate_ftp_error(self, err, path, extra=None,
 
142
    def _translate_perm_error(self, err, path, extra=None,
168
143
                              unknown_exc=FtpPathError):
169
 
        """Try to translate an ftplib exception to a bzrlib exception.
 
144
        """Try to translate an ftplib.error_perm exception.
170
145
 
171
146
        :param err: The error to translate into a bzr error
172
147
        :param path: The path which had problems
174
149
        :param unknown_exc: If None, we will just raise the original exception
175
150
                    otherwise we raise unknown_exc(path, extra=extra)
176
151
        """
177
 
        # ftp error numbers are very generic, like "451: Requested action aborted,
178
 
        # local error in processing" so unfortunately we have to match by
179
 
        # strings.
180
152
        s = str(err).lower()
181
153
        if not extra:
182
154
            extra = str(err)
186
158
            or 'could not open' in s
187
159
            or 'no such dir' in s
188
160
            or 'could not create file' in s # vsftpd
189
 
            or 'file doesn\'t exist' in s
190
 
            or 'rnfr command failed.' in s # vsftpd RNFR reply if file not found
191
 
            or 'file/directory not found' in s # filezilla server
192
 
            # Microsoft FTP-Service RNFR reply if file not found
193
 
            or (s.startswith('550 ') and 'unable to rename to' in extra)
194
161
            ):
195
162
            raise errors.NoSuchFile(path, extra=extra)
196
 
        elif ('file exists' in s):
 
163
        if ('file exists' in s):
197
164
            raise errors.FileExists(path, extra=extra)
198
 
        elif ('not a directory' in s):
 
165
        if ('not a directory' in s):
199
166
            raise errors.PathError(path, extra=extra)
200
 
        elif 'directory not empty' in s:
201
 
            raise errors.DirectoryNotEmpty(path, extra=extra)
202
167
 
203
168
        mutter('unable to understand error for path: %s: %s', path, err)
204
169
 
205
170
        if unknown_exc:
206
171
            raise unknown_exc(path, extra=extra)
207
 
        # TODO: jam 20060516 Consider re-raising the error wrapped in
 
172
        # TODO: jam 20060516 Consider re-raising the error wrapped in 
208
173
        #       something like TransportError, but this loses the traceback
209
174
        #       Also, 'sftp' has a generic 'Failure' mode, which we use failure_exc
210
175
        #       to handle. Consider doing something like that here.
211
176
        #raise TransportError(msg='Error for path: %s' % (path,), orig_error=e)
212
177
        raise
213
178
 
 
179
    def should_cache(self):
 
180
        """Return True if the data pulled across should be cached locally.
 
181
        """
 
182
        return True
 
183
 
 
184
    def _remote_path(self, relpath):
 
185
        # XXX: It seems that ftplib does not handle Unicode paths
 
186
        # at the same time, medusa won't handle utf8 paths So if
 
187
        # we .encode(utf8) here (see ConnectedTransport
 
188
        # implementation), then we get a Server failure.  while
 
189
        # if we use str(), we get a UnicodeError, and the test
 
190
        # suite just skips testing UnicodePaths.
 
191
        relative = str(urlutils.unescape(relpath))
 
192
        remote_path = self._combine_paths(self._path, relative)
 
193
        return remote_path
 
194
 
214
195
    def has(self, relpath):
215
196
        """Does the target location exist?"""
216
197
        # FIXME jam 20060516 We *do* ask about directories in the test suite
286
267
        abspath = self._remote_path(relpath)
287
268
        tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
288
269
                        os.getpid(), random.randint(0,0x7FFFFFFF))
289
 
        bytes = None
290
270
        if getattr(fp, 'read', None) is None:
291
 
            # hand in a string IO
292
 
            bytes = fp
293
 
            fp = StringIO(bytes)
294
 
        else:
295
 
            # capture the byte count; .read() may be read only so
296
 
            # decorate it.
297
 
            class byte_counter(object):
298
 
                def __init__(self, fp):
299
 
                    self.fp = fp
300
 
                    self.counted_bytes = 0
301
 
                def read(self, count):
302
 
                    result = self.fp.read(count)
303
 
                    self.counted_bytes += len(result)
304
 
                    return result
305
 
            fp = byte_counter(fp)
 
271
            fp = StringIO(fp)
306
272
        try:
307
273
            mutter("FTP put: %s", abspath)
308
274
            f = self._get_FTP()
309
275
            try:
310
276
                f.storbinary('STOR '+tmp_abspath, fp)
311
277
                self._rename_and_overwrite(tmp_abspath, abspath, f)
312
 
                self._setmode(relpath, mode)
313
 
                if bytes is not None:
314
 
                    return len(bytes)
315
 
                else:
316
 
                    return fp.counted_bytes
317
278
            except (ftplib.error_temp,EOFError), e:
318
279
                warning("Failure during ftp PUT. Deleting temporary file.")
319
280
                try:
324
285
                    raise e
325
286
                raise
326
287
        except ftplib.error_perm, e:
327
 
            self._translate_ftp_error(e, abspath, extra='could not store',
328
 
                                       unknown_exc=errors.NoSuchFile)
 
288
            self._translate_perm_error(e, abspath, extra='could not store')
329
289
        except ftplib.error_temp, e:
330
290
            if retries > _number_of_retries:
331
291
                raise errors.TransportError("FTP temporary error during PUT %s. Aborting."
351
311
            mutter("FTP mkd: %s", abspath)
352
312
            f = self._get_FTP()
353
313
            f.mkd(abspath)
354
 
            self._setmode(relpath, mode)
355
314
        except ftplib.error_perm, e:
356
 
            self._translate_ftp_error(e, abspath,
 
315
            self._translate_perm_error(e, abspath,
357
316
                unknown_exc=errors.FileExists)
358
317
 
359
 
    def open_write_stream(self, relpath, mode=None):
360
 
        """See Transport.open_write_stream."""
361
 
        self.put_bytes(relpath, "", mode)
362
 
        result = AppendBasedFileStream(self, relpath)
363
 
        _file_streams[self.abspath(relpath)] = result
364
 
        return result
365
 
 
366
 
    def recommended_page_size(self):
367
 
        """See Transport.recommended_page_size().
368
 
 
369
 
        For FTP we suggest a large page size to reduce the overhead
370
 
        introduced by latency.
371
 
        """
372
 
        return 64 * 1024
373
 
 
374
318
    def rmdir(self, rel_path):
375
319
        """Delete the directory at rel_path"""
376
320
        abspath = self._remote_path(rel_path)
379
323
            f = self._get_FTP()
380
324
            f.rmd(abspath)
381
325
        except ftplib.error_perm, e:
382
 
            self._translate_ftp_error(e, abspath, unknown_exc=errors.PathError)
 
326
            self._translate_perm_error(e, abspath, unknown_exc=errors.PathError)
383
327
 
384
328
    def append_file(self, relpath, f, mode=None):
385
329
        """Append the text in the file-like object into the final
386
330
        location.
387
331
        """
388
 
        text = f.read()
389
332
        abspath = self._remote_path(relpath)
390
333
        if self.has(relpath):
391
334
            ftp = self._get_FTP()
393
336
        else:
394
337
            result = 0
395
338
 
396
 
        if self._has_append:
397
 
            mutter("FTP appe to %s", abspath)
398
 
            self._try_append(relpath, text, mode)
399
 
        else:
400
 
            self._fallback_append(relpath, text, mode)
 
339
        mutter("FTP appe to %s", abspath)
 
340
        self._try_append(relpath, f.read(), mode)
401
341
 
402
342
        return result
403
343
 
404
344
    def _try_append(self, relpath, text, mode=None, retries=0):
405
345
        """Try repeatedly to append the given text to the file at relpath.
406
 
 
 
346
        
407
347
        This is a recursive function. On errors, it will be called until the
408
348
        number of retries is exceeded.
409
349
        """
411
351
            abspath = self._remote_path(relpath)
412
352
            mutter("FTP appe (try %d) to %s", retries, abspath)
413
353
            ftp = self._get_FTP()
 
354
            ftp.voidcmd("TYPE I")
414
355
            cmd = "APPE %s" % abspath
415
356
            conn = ftp.transfercmd(cmd)
416
357
            conn.sendall(text)
417
358
            conn.close()
418
 
            self._setmode(relpath, mode)
 
359
            if mode:
 
360
                self._setmode(relpath, mode)
419
361
            ftp.getresp()
420
362
        except ftplib.error_perm, e:
421
 
            # Check whether the command is not supported (reply code 502)
422
 
            if str(e).startswith('502 '):
423
 
                warning("FTP server does not support file appending natively. "
424
 
                        "Performance may be severely degraded! (%s)", e)
425
 
                self._has_append = False
426
 
                self._fallback_append(relpath, text, mode)
427
 
            else:
428
 
                self._translate_ftp_error(e, abspath, extra='error appending',
429
 
                    unknown_exc=errors.NoSuchFile)
 
363
            self._translate_perm_error(e, abspath, extra='error appending',
 
364
                unknown_exc=errors.NoSuchFile)
430
365
        except ftplib.error_temp, e:
431
366
            if retries > _number_of_retries:
432
 
                raise errors.TransportError(
433
 
                    "FTP temporary error during APPEND %s. Aborting."
434
 
                    % abspath, orig_error=e)
 
367
                raise errors.TransportError("FTP temporary error during APPEND %s." \
 
368
                        "Aborting." % abspath, orig_error=e)
435
369
            else:
436
370
                warning("FTP temporary error: %s. Retrying.", str(e))
437
371
                self._reconnect()
438
372
                self._try_append(relpath, text, mode, retries+1)
439
373
 
440
 
    def _fallback_append(self, relpath, text, mode = None):
441
 
        remote = self.get(relpath)
442
 
        remote.seek(0, os.SEEK_END)
443
 
        remote.write(text)
444
 
        remote.seek(0)
445
 
        return self.put_file(relpath, remote, mode)
446
 
 
447
374
    def _setmode(self, relpath, mode):
448
375
        """Set permissions on a path.
449
376
 
450
377
        Only set permissions if the FTP server supports the 'SITE CHMOD'
451
378
        extension.
452
379
        """
453
 
        if mode:
454
 
            try:
455
 
                mutter("FTP site chmod: setting permissions to %s on %s",
456
 
                       oct(mode), self._remote_path(relpath))
457
 
                ftp = self._get_FTP()
458
 
                cmd = "SITE CHMOD %s %s" % (oct(mode),
459
 
                                            self._remote_path(relpath))
460
 
                ftp.sendcmd(cmd)
461
 
            except ftplib.error_perm, e:
462
 
                # Command probably not available on this server
463
 
                warning("FTP Could not set permissions to %s on %s. %s",
464
 
                        oct(mode), self._remote_path(relpath), str(e))
 
380
        try:
 
381
            mutter("FTP site chmod: setting permissions to %s on %s",
 
382
                str(mode), self._remote_path(relpath))
 
383
            ftp = self._get_FTP()
 
384
            cmd = "SITE CHMOD %s %s" % (self._remote_path(relpath), str(mode))
 
385
            ftp.sendcmd(cmd)
 
386
        except ftplib.error_perm, e:
 
387
            # Command probably not available on this server
 
388
            warning("FTP Could not set permissions to %s on %s. %s",
 
389
                    str(mode), self._remote_path(relpath), str(e))
465
390
 
466
391
    # TODO: jam 20060516 I believe ftp allows you to tell an ftp server
467
392
    #       to copy something to another machine. And you may be able
478
403
    def _rename(self, abs_from, abs_to, f):
479
404
        try:
480
405
            f.rename(abs_from, abs_to)
481
 
        except (ftplib.error_temp, ftplib.error_perm), e:
482
 
            self._translate_ftp_error(e, abs_from,
 
406
        except ftplib.error_perm, e:
 
407
            self._translate_perm_error(e, abs_from,
483
408
                ': unable to rename to %r' % (abs_to))
484
409
 
485
410
    def move(self, rel_from, rel_to):
491
416
            f = self._get_FTP()
492
417
            self._rename_and_overwrite(abs_from, abs_to, f)
493
418
        except ftplib.error_perm, e:
494
 
            self._translate_ftp_error(e, abs_from,
495
 
                extra='unable to rename to %r' % (rel_to,),
 
419
            self._translate_perm_error(e, abs_from,
 
420
                extra='unable to rename to %r' % (rel_to,), 
496
421
                unknown_exc=errors.PathError)
497
422
 
498
423
    def _rename_and_overwrite(self, abs_from, abs_to, f):
515
440
            mutter("FTP rm: %s", abspath)
516
441
            f.delete(abspath)
517
442
        except ftplib.error_perm, e:
518
 
            self._translate_ftp_error(e, abspath, 'error deleting',
 
443
            self._translate_perm_error(e, abspath, 'error deleting',
519
444
                unknown_exc=errors.NoSuchFile)
520
445
 
521
 
    def external_url(self):
522
 
        """See bzrlib.transport.Transport.external_url."""
523
 
        # FTP URL's are externally usable.
524
 
        return self.base
525
 
 
526
446
    def listable(self):
527
447
        """See Transport.listable."""
528
448
        return True
533
453
        mutter("FTP nlst: %s", basepath)
534
454
        f = self._get_FTP()
535
455
        try:
536
 
            try:
537
 
                paths = f.nlst(basepath)
538
 
            except ftplib.error_perm, e:
539
 
                self._translate_ftp_error(e, relpath,
540
 
                                           extra='error with list_dir')
541
 
            except ftplib.error_temp, e:
542
 
                # xs4all's ftp server raises a 450 temp error when listing an
543
 
                # empty directory. Check for that and just return an empty list
544
 
                # in that case. See bug #215522
545
 
                if str(e).lower().startswith('450 no files found'):
546
 
                    mutter('FTP Server returned "%s" for nlst.'
547
 
                           ' Assuming it means empty directory',
548
 
                           str(e))
549
 
                    return []
550
 
                raise
551
 
        finally:
552
 
            # Restore binary mode as nlst switch to ascii mode to retrieve file
553
 
            # list
554
 
            f.voidcmd('TYPE I')
555
 
 
 
456
            paths = f.nlst(basepath)
 
457
        except ftplib.error_perm, e:
 
458
            self._translate_perm_error(e, relpath, extra='error with list_dir')
556
459
        # If FTP.nlst returns paths prefixed by relpath, strip 'em
557
460
        if paths and paths[0].startswith(basepath):
558
461
            entries = [path[len(basepath)+1:] for path in paths]
585
488
            f = self._get_FTP()
586
489
            return FtpStatResult(f, abspath)
587
490
        except ftplib.error_perm, e:
588
 
            self._translate_ftp_error(e, abspath, extra='error w/ stat')
 
491
            self._translate_perm_error(e, abspath, extra='error w/ stat')
589
492
 
590
493
    def lock_read(self, relpath):
591
494
        """Lock the given file for shared (read) access.
609
512
        return self.lock_read(relpath)
610
513
 
611
514
 
 
515
class FtpServer(Server):
 
516
    """Common code for SFTP server facilities."""
 
517
 
 
518
    def __init__(self):
 
519
        self._root = None
 
520
        self._ftp_server = None
 
521
        self._port = None
 
522
        self._async_thread = None
 
523
        # ftp server logs
 
524
        self.logs = []
 
525
 
 
526
    def get_url(self):
 
527
        """Calculate an ftp url to this server."""
 
528
        return 'ftp://foo:bar@localhost:%d/' % (self._port)
 
529
 
 
530
#    def get_bogus_url(self):
 
531
#        """Return a URL which cannot be connected to."""
 
532
#        return 'ftp://127.0.0.1:1'
 
533
 
 
534
    def log(self, message):
 
535
        """This is used by medusa.ftp_server to log connections, etc."""
 
536
        self.logs.append(message)
 
537
 
 
538
    def setUp(self, vfs_server=None):
 
539
        if not _have_medusa:
 
540
            raise RuntimeError('Must have medusa to run the FtpServer')
 
541
 
 
542
        assert vfs_server is None or isinstance(vfs_server, LocalURLServer), \
 
543
            "FtpServer currently assumes local transport, got %s" % vfs_server
 
544
 
 
545
        self._root = os.getcwdu()
 
546
        self._ftp_server = _ftp_server(
 
547
            authorizer=_test_authorizer(root=self._root),
 
548
            ip='localhost',
 
549
            port=0, # bind to a random port
 
550
            resolver=None,
 
551
            logger_object=self # Use FtpServer.log() for messages
 
552
            )
 
553
        self._port = self._ftp_server.getsockname()[1]
 
554
        # Don't let it loop forever, or handle an infinite number of requests.
 
555
        # In this case it will run for 1000s, or 10000 requests
 
556
        self._async_thread = threading.Thread(
 
557
                target=FtpServer._asyncore_loop_ignore_EBADF,
 
558
                kwargs={'timeout':0.1, 'count':10000})
 
559
        self._async_thread.setDaemon(True)
 
560
        self._async_thread.start()
 
561
 
 
562
    def tearDown(self):
 
563
        """See bzrlib.transport.Server.tearDown."""
 
564
        # have asyncore release the channel
 
565
        self._ftp_server.del_channel()
 
566
        asyncore.close_all()
 
567
        self._async_thread.join()
 
568
 
 
569
    @staticmethod
 
570
    def _asyncore_loop_ignore_EBADF(*args, **kwargs):
 
571
        """Ignore EBADF during server shutdown.
 
572
 
 
573
        We close the socket to get the server to shutdown, but this causes
 
574
        select.select() to raise EBADF.
 
575
        """
 
576
        try:
 
577
            asyncore.loop(*args, **kwargs)
 
578
            # FIXME: If we reach that point, we should raise an exception
 
579
            # explaining that the 'count' parameter in setUp is too low or
 
580
            # testers may wonder why their test just sits there waiting for a
 
581
            # server that is already dead. Note that if the tester waits too
 
582
            # long under pdb the server will also die.
 
583
        except select.error, e:
 
584
            if e.args[0] != errno.EBADF:
 
585
                raise
 
586
 
 
587
 
 
588
_ftp_channel = None
 
589
_ftp_server = None
 
590
_test_authorizer = None
 
591
 
 
592
 
 
593
def _setup_medusa():
 
594
    global _have_medusa, _ftp_channel, _ftp_server, _test_authorizer
 
595
    try:
 
596
        import medusa
 
597
        import medusa.filesys
 
598
        import medusa.ftp_server
 
599
    except ImportError:
 
600
        return False
 
601
 
 
602
    _have_medusa = True
 
603
 
 
604
    class test_authorizer(object):
 
605
        """A custom Authorizer object for running the test suite.
 
606
 
 
607
        The reason we cannot use dummy_authorizer, is because it sets the
 
608
        channel to readonly, which we don't always want to do.
 
609
        """
 
610
 
 
611
        def __init__(self, root):
 
612
            self.root = root
 
613
 
 
614
        def authorize(self, channel, username, password):
 
615
            """Return (success, reply_string, filesystem)"""
 
616
            if not _have_medusa:
 
617
                return 0, 'No Medusa.', None
 
618
 
 
619
            channel.persona = -1, -1
 
620
            if username == 'anonymous':
 
621
                channel.read_only = 1
 
622
            else:
 
623
                channel.read_only = 0
 
624
 
 
625
            return 1, 'OK.', medusa.filesys.os_filesystem(self.root)
 
626
 
 
627
 
 
628
    class ftp_channel(medusa.ftp_server.ftp_channel):
 
629
        """Customized ftp channel"""
 
630
 
 
631
        def log(self, message):
 
632
            """Redirect logging requests."""
 
633
            mutter('_ftp_channel: %s', message)
 
634
 
 
635
        def log_info(self, message, type='info'):
 
636
            """Redirect logging requests."""
 
637
            mutter('_ftp_channel %s: %s', type, message)
 
638
 
 
639
        def cmd_rnfr(self, line):
 
640
            """Prepare for renaming a file."""
 
641
            self._renaming = line[1]
 
642
            self.respond('350 Ready for RNTO')
 
643
            # TODO: jam 20060516 in testing, the ftp server seems to
 
644
            #       check that the file already exists, or it sends
 
645
            #       550 RNFR command failed
 
646
 
 
647
        def cmd_rnto(self, line):
 
648
            """Rename a file based on the target given.
 
649
 
 
650
            rnto must be called after calling rnfr.
 
651
            """
 
652
            if not self._renaming:
 
653
                self.respond('503 RNFR required first.')
 
654
            pfrom = self.filesystem.translate(self._renaming)
 
655
            self._renaming = None
 
656
            pto = self.filesystem.translate(line[1])
 
657
            if os.path.exists(pto):
 
658
                self.respond('550 RNTO failed: file exists')
 
659
                return
 
660
            try:
 
661
                os.rename(pfrom, pto)
 
662
            except (IOError, OSError), e:
 
663
                # TODO: jam 20060516 return custom responses based on
 
664
                #       why the command failed
 
665
                # (bialix 20070418) str(e) on Python 2.5 @ Windows
 
666
                # sometimes don't provide expected error message;
 
667
                # so we obtain such message via os.strerror()
 
668
                self.respond('550 RNTO failed: %s' % os.strerror(e.errno))
 
669
            except:
 
670
                self.respond('550 RNTO failed')
 
671
                # For a test server, we will go ahead and just die
 
672
                raise
 
673
            else:
 
674
                self.respond('250 Rename successful.')
 
675
 
 
676
        def cmd_size(self, line):
 
677
            """Return the size of a file
 
678
 
 
679
            This is overloaded to help the test suite determine if the 
 
680
            target is a directory.
 
681
            """
 
682
            filename = line[1]
 
683
            if not self.filesystem.isfile(filename):
 
684
                if self.filesystem.isdir(filename):
 
685
                    self.respond('550 "%s" is a directory' % (filename,))
 
686
                else:
 
687
                    self.respond('550 "%s" is not a file' % (filename,))
 
688
            else:
 
689
                self.respond('213 %d' 
 
690
                    % (self.filesystem.stat(filename)[stat.ST_SIZE]),)
 
691
 
 
692
        def cmd_mkd(self, line):
 
693
            """Create a directory.
 
694
 
 
695
            Overloaded because default implementation does not distinguish
 
696
            *why* it cannot make a directory.
 
697
            """
 
698
            if len (line) != 2:
 
699
                self.command_not_understood(''.join(line))
 
700
            else:
 
701
                path = line[1]
 
702
                try:
 
703
                    self.filesystem.mkdir (path)
 
704
                    self.respond ('257 MKD command successful.')
 
705
                except (IOError, OSError), e:
 
706
                    # (bialix 20070418) str(e) on Python 2.5 @ Windows
 
707
                    # sometimes don't provide expected error message;
 
708
                    # so we obtain such message via os.strerror()
 
709
                    self.respond ('550 error creating directory: %s' %
 
710
                                  os.strerror(e.errno))
 
711
                except:
 
712
                    self.respond ('550 error creating directory.')
 
713
 
 
714
 
 
715
    class ftp_server(medusa.ftp_server.ftp_server):
 
716
        """Customize the behavior of the Medusa ftp_server.
 
717
 
 
718
        There are a few warts on the ftp_server, based on how it expects
 
719
        to be used.
 
720
        """
 
721
        _renaming = None
 
722
        ftp_channel_class = ftp_channel
 
723
 
 
724
        def __init__(self, *args, **kwargs):
 
725
            mutter('Initializing _ftp_server: %r, %r', args, kwargs)
 
726
            medusa.ftp_server.ftp_server.__init__(self, *args, **kwargs)
 
727
 
 
728
        def log(self, message):
 
729
            """Redirect logging requests."""
 
730
            mutter('_ftp_server: %s', message)
 
731
 
 
732
        def log_info(self, message, type='info'):
 
733
            """Override the asyncore.log_info so we don't stipple the screen."""
 
734
            mutter('_ftp_server %s: %s', type, message)
 
735
 
 
736
    _test_authorizer = test_authorizer
 
737
    _ftp_channel = ftp_channel
 
738
    _ftp_server = ftp_server
 
739
 
 
740
    return True
 
741
 
 
742
 
612
743
def get_test_permutations():
613
744
    """Return the permutations to be used in testing."""
614
 
    from bzrlib.tests import ftp_server
615
 
    return [(FtpTransport, ftp_server.FTPTestServer)]
 
745
    if not _setup_medusa():
 
746
        warn("You must install medusa (http://www.amk.ca/python/code/medusa.html) for FTP tests")
 
747
        return []
 
748
    else:
 
749
        return [(FtpTransport, FtpServer)]