/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: Robert Collins
  • Date: 2007-10-04 04:59:43 UTC
  • mto: This revision was merged to the branch mainline in revision 2885.
  • Revision ID: robertc@robertcollins.net-20071004045943-1wxlrsr37yppwp64
Review feedback.

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,
43
47
from bzrlib.trace import mutter, warning
44
48
from bzrlib.transport import (
45
49
    AppendBasedFileStream,
46
 
    ConnectedTransport,
47
50
    _file_streams,
48
 
    register_urlparse_netloc_protocol,
49
51
    Server,
 
52
    ConnectedTransport,
50
53
    )
51
 
 
52
 
 
53
 
register_urlparse_netloc_protocol('aftp')
 
54
from bzrlib.transport.local import LocalURLServer
 
55
import bzrlib.ui
 
56
 
 
57
_have_medusa = False
54
58
 
55
59
 
56
60
class FtpPathError(errors.PathError):
58
62
 
59
63
 
60
64
class FtpStatResult(object):
61
 
 
62
 
    def __init__(self, f, abspath):
 
65
    def __init__(self, f, relpath):
63
66
        try:
64
 
            self.st_size = f.size(abspath)
 
67
            self.st_size = f.size(relpath)
65
68
            self.st_mode = stat.S_IFREG
66
69
        except ftplib.error_perm:
67
70
            pwd = f.pwd()
68
71
            try:
69
 
                f.cwd(abspath)
 
72
                f.cwd(relpath)
70
73
                self.st_mode = stat.S_IFDIR
71
74
            finally:
72
75
                f.cwd(pwd)
85
88
 
86
89
    def __init__(self, base, _from_transport=None):
87
90
        """Set the base path where files will be stored."""
88
 
        if not (base.startswith('ftp://') or base.startswith('aftp://')):
89
 
            raise ValueError(base)
 
91
        assert base.startswith('ftp://') or base.startswith('aftp://')
90
92
        super(FtpTransport, self).__init__(base,
91
93
                                           _from_transport=_from_transport)
92
94
        self._unqualified_scheme = 'ftp'
95
97
        else:
96
98
            self.is_active = False
97
99
 
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
100
    def _get_FTP(self):
103
101
        """Return the ftplib.FTP instance for this object."""
104
102
        # Ensures that a connection is established
109
107
            self._set_connection(connection, credentials)
110
108
        return connection
111
109
 
112
 
    connection_class = ftplib.FTP
113
 
 
114
110
    def _create_connection(self, credentials=None):
115
111
        """Create a new connection with the provided credentials.
116
112
 
118
114
 
119
115
        :return: The created connection and its associated credentials.
120
116
 
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.
 
117
        The credentials are only the password as it may have been entered
 
118
        interactively by the user and may be different from the one provided
 
119
        in base url at transport creation time.
125
120
        """
126
121
        if credentials is None:
127
 
            user, password = self._user, self._password
 
122
            password = self._password
128
123
        else:
129
 
            user, password = credentials
 
124
            password = credentials
130
125
 
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
126
        mutter("Constructing FTP instance against %r" %
136
 
               ((self._host, self._port, user, '********',
 
127
               ((self._host, self._port, self._user, '********',
137
128
                self.is_active),))
138
129
        try:
139
 
            connection = self.connection_class()
 
130
            connection = ftplib.FTP()
140
131
            connection.connect(host=self._host, port=self._port)
141
 
            self._login(connection, auth, user, password)
 
132
            if self._user and self._user != 'anonymous' and \
 
133
                    password is not None: # '' is a valid password
 
134
                get_password = bzrlib.ui.ui_factory.get_password
 
135
                password = get_password(prompt='FTP %(user)s@%(host)s password',
 
136
                                        user=self._user, host=self._host)
 
137
            connection.login(user=self._user, passwd=password)
142
138
            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
139
        except ftplib.error_perm, e:
150
140
            raise errors.TransportError(msg="Error setting up connection:"
151
141
                                        " %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)
 
142
        return connection, password
160
143
 
161
144
    def _reconnect(self):
162
145
        """Create a new connection with the previously used credentials"""
163
 
        credentials = self._get_credentials()
 
146
        credentials = self.get_credentials()
164
147
        connection, credentials = self._create_connection(credentials)
165
148
        self._set_connection(connection, credentials)
166
149
 
167
 
    def _translate_ftp_error(self, err, path, extra=None,
 
150
    def _translate_perm_error(self, err, path, extra=None,
168
151
                              unknown_exc=FtpPathError):
169
 
        """Try to translate an ftplib exception to a bzrlib exception.
 
152
        """Try to translate an ftplib.error_perm exception.
170
153
 
171
154
        :param err: The error to translate into a bzr error
172
155
        :param path: The path which had problems
174
157
        :param unknown_exc: If None, we will just raise the original exception
175
158
                    otherwise we raise unknown_exc(path, extra=extra)
176
159
        """
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
160
        s = str(err).lower()
181
161
        if not extra:
182
162
            extra = str(err)
187
167
            or 'no such dir' in s
188
168
            or 'could not create file' in s # vsftpd
189
169
            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
170
            ):
195
171
            raise errors.NoSuchFile(path, extra=extra)
196
 
        elif ('file exists' in s):
 
172
        if ('file exists' in s):
197
173
            raise errors.FileExists(path, extra=extra)
198
 
        elif ('not a directory' in s):
 
174
        if ('not a directory' in s):
199
175
            raise errors.PathError(path, extra=extra)
200
 
        elif 'directory not empty' in s:
201
 
            raise errors.DirectoryNotEmpty(path, extra=extra)
202
176
 
203
177
        mutter('unable to understand error for path: %s: %s', path, err)
204
178
 
205
179
        if unknown_exc:
206
180
            raise unknown_exc(path, extra=extra)
207
 
        # TODO: jam 20060516 Consider re-raising the error wrapped in
 
181
        # TODO: jam 20060516 Consider re-raising the error wrapped in 
208
182
        #       something like TransportError, but this loses the traceback
209
183
        #       Also, 'sftp' has a generic 'Failure' mode, which we use failure_exc
210
184
        #       to handle. Consider doing something like that here.
211
185
        #raise TransportError(msg='Error for path: %s' % (path,), orig_error=e)
212
186
        raise
213
187
 
 
188
    def _remote_path(self, relpath):
 
189
        # XXX: It seems that ftplib does not handle Unicode paths
 
190
        # at the same time, medusa won't handle utf8 paths So if
 
191
        # we .encode(utf8) here (see ConnectedTransport
 
192
        # implementation), then we get a Server failure.  while
 
193
        # if we use str(), we get a UnicodeError, and the test
 
194
        # suite just skips testing UnicodePaths.
 
195
        relative = str(urlutils.unescape(relpath))
 
196
        remote_path = self._combine_paths(self._path, relative)
 
197
        return remote_path
 
198
 
214
199
    def has(self, relpath):
215
200
        """Does the target location exist?"""
216
201
        # FIXME jam 20060516 We *do* ask about directories in the test suite
309
294
            try:
310
295
                f.storbinary('STOR '+tmp_abspath, fp)
311
296
                self._rename_and_overwrite(tmp_abspath, abspath, f)
312
 
                self._setmode(relpath, mode)
313
297
                if bytes is not None:
314
298
                    return len(bytes)
315
299
                else:
324
308
                    raise e
325
309
                raise
326
310
        except ftplib.error_perm, e:
327
 
            self._translate_ftp_error(e, abspath, extra='could not store',
 
311
            self._translate_perm_error(e, abspath, extra='could not store',
328
312
                                       unknown_exc=errors.NoSuchFile)
329
313
        except ftplib.error_temp, e:
330
314
            if retries > _number_of_retries:
351
335
            mutter("FTP mkd: %s", abspath)
352
336
            f = self._get_FTP()
353
337
            f.mkd(abspath)
354
 
            self._setmode(relpath, mode)
355
338
        except ftplib.error_perm, e:
356
 
            self._translate_ftp_error(e, abspath,
 
339
            self._translate_perm_error(e, abspath,
357
340
                unknown_exc=errors.FileExists)
358
341
 
359
342
    def open_write_stream(self, relpath, mode=None):
379
362
            f = self._get_FTP()
380
363
            f.rmd(abspath)
381
364
        except ftplib.error_perm, e:
382
 
            self._translate_ftp_error(e, abspath, unknown_exc=errors.PathError)
 
365
            self._translate_perm_error(e, abspath, unknown_exc=errors.PathError)
383
366
 
384
367
    def append_file(self, relpath, f, mode=None):
385
368
        """Append the text in the file-like object into the final
386
369
        location.
387
370
        """
388
 
        text = f.read()
389
371
        abspath = self._remote_path(relpath)
390
372
        if self.has(relpath):
391
373
            ftp = self._get_FTP()
393
375
        else:
394
376
            result = 0
395
377
 
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)
 
378
        mutter("FTP appe to %s", abspath)
 
379
        self._try_append(relpath, f.read(), mode)
401
380
 
402
381
        return result
403
382
 
404
383
    def _try_append(self, relpath, text, mode=None, retries=0):
405
384
        """Try repeatedly to append the given text to the file at relpath.
406
 
 
 
385
        
407
386
        This is a recursive function. On errors, it will be called until the
408
387
        number of retries is exceeded.
409
388
        """
411
390
            abspath = self._remote_path(relpath)
412
391
            mutter("FTP appe (try %d) to %s", retries, abspath)
413
392
            ftp = self._get_FTP()
 
393
            ftp.voidcmd("TYPE I")
414
394
            cmd = "APPE %s" % abspath
415
395
            conn = ftp.transfercmd(cmd)
416
396
            conn.sendall(text)
417
397
            conn.close()
418
 
            self._setmode(relpath, mode)
 
398
            if mode:
 
399
                self._setmode(relpath, mode)
419
400
            ftp.getresp()
420
401
        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)
 
402
            self._translate_perm_error(e, abspath, extra='error appending',
 
403
                unknown_exc=errors.NoSuchFile)
430
404
        except ftplib.error_temp, e:
431
405
            if retries > _number_of_retries:
432
 
                raise errors.TransportError(
433
 
                    "FTP temporary error during APPEND %s. Aborting."
434
 
                    % abspath, orig_error=e)
 
406
                raise errors.TransportError("FTP temporary error during APPEND %s." \
 
407
                        "Aborting." % abspath, orig_error=e)
435
408
            else:
436
409
                warning("FTP temporary error: %s. Retrying.", str(e))
437
410
                self._reconnect()
438
411
                self._try_append(relpath, text, mode, retries+1)
439
412
 
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
413
    def _setmode(self, relpath, mode):
448
414
        """Set permissions on a path.
449
415
 
450
416
        Only set permissions if the FTP server supports the 'SITE CHMOD'
451
417
        extension.
452
418
        """
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))
 
419
        try:
 
420
            mutter("FTP site chmod: setting permissions to %s on %s",
 
421
                str(mode), self._remote_path(relpath))
 
422
            ftp = self._get_FTP()
 
423
            cmd = "SITE CHMOD %s %s" % (self._remote_path(relpath), str(mode))
 
424
            ftp.sendcmd(cmd)
 
425
        except ftplib.error_perm, e:
 
426
            # Command probably not available on this server
 
427
            warning("FTP Could not set permissions to %s on %s. %s",
 
428
                    str(mode), self._remote_path(relpath), str(e))
465
429
 
466
430
    # TODO: jam 20060516 I believe ftp allows you to tell an ftp server
467
431
    #       to copy something to another machine. And you may be able
478
442
    def _rename(self, abs_from, abs_to, f):
479
443
        try:
480
444
            f.rename(abs_from, abs_to)
481
 
        except (ftplib.error_temp, ftplib.error_perm), e:
482
 
            self._translate_ftp_error(e, abs_from,
 
445
        except ftplib.error_perm, e:
 
446
            self._translate_perm_error(e, abs_from,
483
447
                ': unable to rename to %r' % (abs_to))
484
448
 
485
449
    def move(self, rel_from, rel_to):
491
455
            f = self._get_FTP()
492
456
            self._rename_and_overwrite(abs_from, abs_to, f)
493
457
        except ftplib.error_perm, e:
494
 
            self._translate_ftp_error(e, abs_from,
495
 
                extra='unable to rename to %r' % (rel_to,),
 
458
            self._translate_perm_error(e, abs_from,
 
459
                extra='unable to rename to %r' % (rel_to,), 
496
460
                unknown_exc=errors.PathError)
497
461
 
498
462
    def _rename_and_overwrite(self, abs_from, abs_to, f):
515
479
            mutter("FTP rm: %s", abspath)
516
480
            f.delete(abspath)
517
481
        except ftplib.error_perm, e:
518
 
            self._translate_ftp_error(e, abspath, 'error deleting',
 
482
            self._translate_perm_error(e, abspath, 'error deleting',
519
483
                unknown_exc=errors.NoSuchFile)
520
484
 
521
485
    def external_url(self):
533
497
        mutter("FTP nlst: %s", basepath)
534
498
        f = self._get_FTP()
535
499
        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
 
 
 
500
            paths = f.nlst(basepath)
 
501
        except ftplib.error_perm, e:
 
502
            self._translate_perm_error(e, relpath, extra='error with list_dir')
556
503
        # If FTP.nlst returns paths prefixed by relpath, strip 'em
557
504
        if paths and paths[0].startswith(basepath):
558
505
            entries = [path[len(basepath)+1:] for path in paths]
585
532
            f = self._get_FTP()
586
533
            return FtpStatResult(f, abspath)
587
534
        except ftplib.error_perm, e:
588
 
            self._translate_ftp_error(e, abspath, extra='error w/ stat')
 
535
            self._translate_perm_error(e, abspath, extra='error w/ stat')
589
536
 
590
537
    def lock_read(self, relpath):
591
538
        """Lock the given file for shared (read) access.
609
556
        return self.lock_read(relpath)
610
557
 
611
558
 
 
559
class FtpServer(Server):
 
560
    """Common code for FTP server facilities."""
 
561
 
 
562
    def __init__(self):
 
563
        self._root = None
 
564
        self._ftp_server = None
 
565
        self._port = None
 
566
        self._async_thread = None
 
567
        # ftp server logs
 
568
        self.logs = []
 
569
 
 
570
    def get_url(self):
 
571
        """Calculate an ftp url to this server."""
 
572
        return 'ftp://foo:bar@localhost:%d/' % (self._port)
 
573
 
 
574
#    def get_bogus_url(self):
 
575
#        """Return a URL which cannot be connected to."""
 
576
#        return 'ftp://127.0.0.1:1'
 
577
 
 
578
    def log(self, message):
 
579
        """This is used by medusa.ftp_server to log connections, etc."""
 
580
        self.logs.append(message)
 
581
 
 
582
    def setUp(self, vfs_server=None):
 
583
        if not _have_medusa:
 
584
            raise RuntimeError('Must have medusa to run the FtpServer')
 
585
 
 
586
        assert vfs_server is None or isinstance(vfs_server, LocalURLServer), \
 
587
            "FtpServer currently assumes local transport, got %s" % vfs_server
 
588
 
 
589
        self._root = os.getcwdu()
 
590
        self._ftp_server = _ftp_server(
 
591
            authorizer=_test_authorizer(root=self._root),
 
592
            ip='localhost',
 
593
            port=0, # bind to a random port
 
594
            resolver=None,
 
595
            logger_object=self # Use FtpServer.log() for messages
 
596
            )
 
597
        self._port = self._ftp_server.getsockname()[1]
 
598
        # Don't let it loop forever, or handle an infinite number of requests.
 
599
        # In this case it will run for 1000s, or 10000 requests
 
600
        self._async_thread = threading.Thread(
 
601
                target=FtpServer._asyncore_loop_ignore_EBADF,
 
602
                kwargs={'timeout':0.1, 'count':10000})
 
603
        self._async_thread.setDaemon(True)
 
604
        self._async_thread.start()
 
605
 
 
606
    def tearDown(self):
 
607
        """See bzrlib.transport.Server.tearDown."""
 
608
        # have asyncore release the channel
 
609
        self._ftp_server.del_channel()
 
610
        asyncore.close_all()
 
611
        self._async_thread.join()
 
612
 
 
613
    @staticmethod
 
614
    def _asyncore_loop_ignore_EBADF(*args, **kwargs):
 
615
        """Ignore EBADF during server shutdown.
 
616
 
 
617
        We close the socket to get the server to shutdown, but this causes
 
618
        select.select() to raise EBADF.
 
619
        """
 
620
        try:
 
621
            asyncore.loop(*args, **kwargs)
 
622
            # FIXME: If we reach that point, we should raise an exception
 
623
            # explaining that the 'count' parameter in setUp is too low or
 
624
            # testers may wonder why their test just sits there waiting for a
 
625
            # server that is already dead. Note that if the tester waits too
 
626
            # long under pdb the server will also die.
 
627
        except select.error, e:
 
628
            if e.args[0] != errno.EBADF:
 
629
                raise
 
630
 
 
631
 
 
632
_ftp_channel = None
 
633
_ftp_server = None
 
634
_test_authorizer = None
 
635
 
 
636
 
 
637
def _setup_medusa():
 
638
    global _have_medusa, _ftp_channel, _ftp_server, _test_authorizer
 
639
    try:
 
640
        import medusa
 
641
        import medusa.filesys
 
642
        import medusa.ftp_server
 
643
    except ImportError:
 
644
        return False
 
645
 
 
646
    _have_medusa = True
 
647
 
 
648
    class test_authorizer(object):
 
649
        """A custom Authorizer object for running the test suite.
 
650
 
 
651
        The reason we cannot use dummy_authorizer, is because it sets the
 
652
        channel to readonly, which we don't always want to do.
 
653
        """
 
654
 
 
655
        def __init__(self, root):
 
656
            self.root = root
 
657
 
 
658
        def authorize(self, channel, username, password):
 
659
            """Return (success, reply_string, filesystem)"""
 
660
            if not _have_medusa:
 
661
                return 0, 'No Medusa.', None
 
662
 
 
663
            channel.persona = -1, -1
 
664
            if username == 'anonymous':
 
665
                channel.read_only = 1
 
666
            else:
 
667
                channel.read_only = 0
 
668
 
 
669
            return 1, 'OK.', medusa.filesys.os_filesystem(self.root)
 
670
 
 
671
 
 
672
    class ftp_channel(medusa.ftp_server.ftp_channel):
 
673
        """Customized ftp channel"""
 
674
 
 
675
        def log(self, message):
 
676
            """Redirect logging requests."""
 
677
            mutter('_ftp_channel: %s', message)
 
678
 
 
679
        def log_info(self, message, type='info'):
 
680
            """Redirect logging requests."""
 
681
            mutter('_ftp_channel %s: %s', type, message)
 
682
 
 
683
        def cmd_rnfr(self, line):
 
684
            """Prepare for renaming a file."""
 
685
            self._renaming = line[1]
 
686
            self.respond('350 Ready for RNTO')
 
687
            # TODO: jam 20060516 in testing, the ftp server seems to
 
688
            #       check that the file already exists, or it sends
 
689
            #       550 RNFR command failed
 
690
 
 
691
        def cmd_rnto(self, line):
 
692
            """Rename a file based on the target given.
 
693
 
 
694
            rnto must be called after calling rnfr.
 
695
            """
 
696
            if not self._renaming:
 
697
                self.respond('503 RNFR required first.')
 
698
            pfrom = self.filesystem.translate(self._renaming)
 
699
            self._renaming = None
 
700
            pto = self.filesystem.translate(line[1])
 
701
            if os.path.exists(pto):
 
702
                self.respond('550 RNTO failed: file exists')
 
703
                return
 
704
            try:
 
705
                os.rename(pfrom, pto)
 
706
            except (IOError, OSError), e:
 
707
                # TODO: jam 20060516 return custom responses based on
 
708
                #       why the command failed
 
709
                # (bialix 20070418) str(e) on Python 2.5 @ Windows
 
710
                # sometimes don't provide expected error message;
 
711
                # so we obtain such message via os.strerror()
 
712
                self.respond('550 RNTO failed: %s' % os.strerror(e.errno))
 
713
            except:
 
714
                self.respond('550 RNTO failed')
 
715
                # For a test server, we will go ahead and just die
 
716
                raise
 
717
            else:
 
718
                self.respond('250 Rename successful.')
 
719
 
 
720
        def cmd_size(self, line):
 
721
            """Return the size of a file
 
722
 
 
723
            This is overloaded to help the test suite determine if the 
 
724
            target is a directory.
 
725
            """
 
726
            filename = line[1]
 
727
            if not self.filesystem.isfile(filename):
 
728
                if self.filesystem.isdir(filename):
 
729
                    self.respond('550 "%s" is a directory' % (filename,))
 
730
                else:
 
731
                    self.respond('550 "%s" is not a file' % (filename,))
 
732
            else:
 
733
                self.respond('213 %d' 
 
734
                    % (self.filesystem.stat(filename)[stat.ST_SIZE]),)
 
735
 
 
736
        def cmd_mkd(self, line):
 
737
            """Create a directory.
 
738
 
 
739
            Overloaded because default implementation does not distinguish
 
740
            *why* it cannot make a directory.
 
741
            """
 
742
            if len (line) != 2:
 
743
                self.command_not_understood(''.join(line))
 
744
            else:
 
745
                path = line[1]
 
746
                try:
 
747
                    self.filesystem.mkdir (path)
 
748
                    self.respond ('257 MKD command successful.')
 
749
                except (IOError, OSError), e:
 
750
                    # (bialix 20070418) str(e) on Python 2.5 @ Windows
 
751
                    # sometimes don't provide expected error message;
 
752
                    # so we obtain such message via os.strerror()
 
753
                    self.respond ('550 error creating directory: %s' %
 
754
                                  os.strerror(e.errno))
 
755
                except:
 
756
                    self.respond ('550 error creating directory.')
 
757
 
 
758
 
 
759
    class ftp_server(medusa.ftp_server.ftp_server):
 
760
        """Customize the behavior of the Medusa ftp_server.
 
761
 
 
762
        There are a few warts on the ftp_server, based on how it expects
 
763
        to be used.
 
764
        """
 
765
        _renaming = None
 
766
        ftp_channel_class = ftp_channel
 
767
 
 
768
        def __init__(self, *args, **kwargs):
 
769
            mutter('Initializing _ftp_server: %r, %r', args, kwargs)
 
770
            medusa.ftp_server.ftp_server.__init__(self, *args, **kwargs)
 
771
 
 
772
        def log(self, message):
 
773
            """Redirect logging requests."""
 
774
            mutter('_ftp_server: %s', message)
 
775
 
 
776
        def log_info(self, message, type='info'):
 
777
            """Override the asyncore.log_info so we don't stipple the screen."""
 
778
            mutter('_ftp_server %s: %s', type, message)
 
779
 
 
780
    _test_authorizer = test_authorizer
 
781
    _ftp_channel = ftp_channel
 
782
    _ftp_server = ftp_server
 
783
 
 
784
    return True
 
785
 
 
786
 
612
787
def get_test_permutations():
613
788
    """Return the permutations to be used in testing."""
614
 
    from bzrlib.tests import ftp_server
615
 
    return [(FtpTransport, ftp_server.FTPTestServer)]
 
789
    if not _setup_medusa():
 
790
        warn("You must install medusa (http://www.amk.ca/python/code/medusa.html) for FTP tests")
 
791
        return []
 
792
    else:
 
793
        return [(FtpTransport, FtpServer)]