/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: Alexander Belchenko
  • Date: 2007-11-02 08:45:10 UTC
  • mto: This revision was merged to the branch mainline in revision 2968.
  • Revision ID: bialix@ukr.net-20071102084510-ngqdd24hjhfdkgw3
start 0.93 development cycle; deprecate osutils.backup_file

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 errno
29
29
import ftplib
30
 
import getpass
31
30
import os
32
 
import random
33
 
import socket
 
31
import os.path
 
32
import urlparse
34
33
import stat
35
34
import time
 
35
import random
 
36
from warnings import warn
36
37
 
37
38
from bzrlib import (
38
 
    config,
39
39
    errors,
40
40
    osutils,
41
41
    urlutils,
43
43
from bzrlib.trace import mutter, warning
44
44
from bzrlib.transport import (
45
45
    AppendBasedFileStream,
46
 
    ConnectedTransport,
47
46
    _file_streams,
48
 
    register_urlparse_netloc_protocol,
49
47
    Server,
 
48
    ConnectedTransport,
50
49
    )
51
 
 
52
 
 
53
 
register_urlparse_netloc_protocol('aftp')
 
50
from bzrlib.transport.local import LocalURLServer
 
51
import bzrlib.ui
 
52
 
 
53
_have_medusa = False
54
54
 
55
55
 
56
56
class FtpPathError(errors.PathError):
58
58
 
59
59
 
60
60
class FtpStatResult(object):
61
 
 
62
 
    def __init__(self, f, abspath):
 
61
    def __init__(self, f, relpath):
63
62
        try:
64
 
            self.st_size = f.size(abspath)
 
63
            self.st_size = f.size(relpath)
65
64
            self.st_mode = stat.S_IFREG
66
65
        except ftplib.error_perm:
67
66
            pwd = f.pwd()
68
67
            try:
69
 
                f.cwd(abspath)
 
68
                f.cwd(relpath)
70
69
                self.st_mode = stat.S_IFDIR
71
70
            finally:
72
71
                f.cwd(pwd)
85
84
 
86
85
    def __init__(self, base, _from_transport=None):
87
86
        """Set the base path where files will be stored."""
88
 
        if not (base.startswith('ftp://') or base.startswith('aftp://')):
89
 
            raise ValueError(base)
 
87
        assert base.startswith('ftp://') or base.startswith('aftp://')
90
88
        super(FtpTransport, self).__init__(base,
91
89
                                           _from_transport=_from_transport)
92
90
        self._unqualified_scheme = 'ftp'
95
93
        else:
96
94
            self.is_active = False
97
95
 
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
96
    def _get_FTP(self):
103
97
        """Return the ftplib.FTP instance for this object."""
104
98
        # Ensures that a connection is established
109
103
            self._set_connection(connection, credentials)
110
104
        return connection
111
105
 
112
 
    connection_class = ftplib.FTP
113
 
 
114
106
    def _create_connection(self, credentials=None):
115
107
        """Create a new connection with the provided credentials.
116
108
 
118
110
 
119
111
        :return: The created connection and its associated credentials.
120
112
 
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.
 
113
        The credentials are only the password as it may have been entered
 
114
        interactively by the user and may be different from the one provided
 
115
        in base url at transport creation time.
125
116
        """
126
117
        if credentials is None:
127
 
            user, password = self._user, self._password
 
118
            password = self._password
128
119
        else:
129
 
            user, password = credentials
 
120
            password = credentials
130
121
 
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
122
        mutter("Constructing FTP instance against %r" %
136
 
               ((self._host, self._port, user, '********',
 
123
               ((self._host, self._port, self._user, '********',
137
124
                self.is_active),))
138
125
        try:
139
 
            connection = self.connection_class()
 
126
            connection = ftplib.FTP()
140
127
            connection.connect(host=self._host, port=self._port)
141
 
            self._login(connection, auth, user, password)
 
128
            if self._user and self._user != 'anonymous' and \
 
129
                    password is None: # '' is a valid password
 
130
                get_password = bzrlib.ui.ui_factory.get_password
 
131
                password = get_password(prompt='FTP %(user)s@%(host)s password',
 
132
                                        user=self._user, host=self._host)
 
133
            connection.login(user=self._user, passwd=password)
142
134
            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
135
        except ftplib.error_perm, e:
150
136
            raise errors.TransportError(msg="Error setting up connection:"
151
137
                                        " %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)
 
138
        return connection, password
160
139
 
161
140
    def _reconnect(self):
162
141
        """Create a new connection with the previously used credentials"""
164
143
        connection, credentials = self._create_connection(credentials)
165
144
        self._set_connection(connection, credentials)
166
145
 
167
 
    def _translate_ftp_error(self, err, path, extra=None,
 
146
    def _translate_perm_error(self, err, path, extra=None,
168
147
                              unknown_exc=FtpPathError):
169
 
        """Try to translate an ftplib exception to a bzrlib exception.
 
148
        """Try to translate an ftplib.error_perm exception.
170
149
 
171
150
        :param err: The error to translate into a bzr error
172
151
        :param path: The path which had problems
174
153
        :param unknown_exc: If None, we will just raise the original exception
175
154
                    otherwise we raise unknown_exc(path, extra=extra)
176
155
        """
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
156
        s = str(err).lower()
181
157
        if not extra:
182
158
            extra = str(err)
187
163
            or 'no such dir' in s
188
164
            or 'could not create file' in s # vsftpd
189
165
            or 'file doesn\'t exist' in s
190
 
            or 'rnfr command failed.' in s # vsftpd RNFR reply if file not found
191
166
            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
167
            ):
195
168
            raise errors.NoSuchFile(path, extra=extra)
196
 
        elif ('file exists' in s):
 
169
        if ('file exists' in s):
197
170
            raise errors.FileExists(path, extra=extra)
198
 
        elif ('not a directory' in s):
 
171
        if ('not a directory' in s):
199
172
            raise errors.PathError(path, extra=extra)
200
 
        elif 'directory not empty' in s:
201
 
            raise errors.DirectoryNotEmpty(path, extra=extra)
202
173
 
203
174
        mutter('unable to understand error for path: %s: %s', path, err)
204
175
 
205
176
        if unknown_exc:
206
177
            raise unknown_exc(path, extra=extra)
207
 
        # TODO: jam 20060516 Consider re-raising the error wrapped in
 
178
        # TODO: jam 20060516 Consider re-raising the error wrapped in 
208
179
        #       something like TransportError, but this loses the traceback
209
180
        #       Also, 'sftp' has a generic 'Failure' mode, which we use failure_exc
210
181
        #       to handle. Consider doing something like that here.
211
182
        #raise TransportError(msg='Error for path: %s' % (path,), orig_error=e)
212
183
        raise
213
184
 
 
185
    def _remote_path(self, relpath):
 
186
        # XXX: It seems that ftplib does not handle Unicode paths
 
187
        # at the same time, medusa won't handle utf8 paths So if
 
188
        # we .encode(utf8) here (see ConnectedTransport
 
189
        # implementation), then we get a Server failure.  while
 
190
        # if we use str(), we get a UnicodeError, and the test
 
191
        # suite just skips testing UnicodePaths.
 
192
        relative = str(urlutils.unescape(relpath))
 
193
        remote_path = self._combine_paths(self._path, relative)
 
194
        return remote_path
 
195
 
214
196
    def has(self, relpath):
215
197
        """Does the target location exist?"""
216
198
        # FIXME jam 20060516 We *do* ask about directories in the test suite
309
291
            try:
310
292
                f.storbinary('STOR '+tmp_abspath, fp)
311
293
                self._rename_and_overwrite(tmp_abspath, abspath, f)
312
 
                self._setmode(relpath, mode)
313
294
                if bytes is not None:
314
295
                    return len(bytes)
315
296
                else:
324
305
                    raise e
325
306
                raise
326
307
        except ftplib.error_perm, e:
327
 
            self._translate_ftp_error(e, abspath, extra='could not store',
 
308
            self._translate_perm_error(e, abspath, extra='could not store',
328
309
                                       unknown_exc=errors.NoSuchFile)
329
310
        except ftplib.error_temp, e:
330
311
            if retries > _number_of_retries:
351
332
            mutter("FTP mkd: %s", abspath)
352
333
            f = self._get_FTP()
353
334
            f.mkd(abspath)
354
 
            self._setmode(relpath, mode)
355
335
        except ftplib.error_perm, e:
356
 
            self._translate_ftp_error(e, abspath,
 
336
            self._translate_perm_error(e, abspath,
357
337
                unknown_exc=errors.FileExists)
358
338
 
359
339
    def open_write_stream(self, relpath, mode=None):
379
359
            f = self._get_FTP()
380
360
            f.rmd(abspath)
381
361
        except ftplib.error_perm, e:
382
 
            self._translate_ftp_error(e, abspath, unknown_exc=errors.PathError)
 
362
            self._translate_perm_error(e, abspath, unknown_exc=errors.PathError)
383
363
 
384
364
    def append_file(self, relpath, f, mode=None):
385
365
        """Append the text in the file-like object into the final
386
366
        location.
387
367
        """
388
 
        text = f.read()
389
368
        abspath = self._remote_path(relpath)
390
369
        if self.has(relpath):
391
370
            ftp = self._get_FTP()
393
372
        else:
394
373
            result = 0
395
374
 
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)
 
375
        mutter("FTP appe to %s", abspath)
 
376
        self._try_append(relpath, f.read(), mode)
401
377
 
402
378
        return result
403
379
 
404
380
    def _try_append(self, relpath, text, mode=None, retries=0):
405
381
        """Try repeatedly to append the given text to the file at relpath.
406
 
 
 
382
        
407
383
        This is a recursive function. On errors, it will be called until the
408
384
        number of retries is exceeded.
409
385
        """
411
387
            abspath = self._remote_path(relpath)
412
388
            mutter("FTP appe (try %d) to %s", retries, abspath)
413
389
            ftp = self._get_FTP()
 
390
            ftp.voidcmd("TYPE I")
414
391
            cmd = "APPE %s" % abspath
415
392
            conn = ftp.transfercmd(cmd)
416
393
            conn.sendall(text)
417
394
            conn.close()
418
 
            self._setmode(relpath, mode)
 
395
            if mode:
 
396
                self._setmode(relpath, mode)
419
397
            ftp.getresp()
420
398
        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)
 
399
            self._translate_perm_error(e, abspath, extra='error appending',
 
400
                unknown_exc=errors.NoSuchFile)
430
401
        except ftplib.error_temp, e:
431
402
            if retries > _number_of_retries:
432
 
                raise errors.TransportError(
433
 
                    "FTP temporary error during APPEND %s. Aborting."
434
 
                    % abspath, orig_error=e)
 
403
                raise errors.TransportError("FTP temporary error during APPEND %s." \
 
404
                        "Aborting." % abspath, orig_error=e)
435
405
            else:
436
406
                warning("FTP temporary error: %s. Retrying.", str(e))
437
407
                self._reconnect()
438
408
                self._try_append(relpath, text, mode, retries+1)
439
409
 
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
410
    def _setmode(self, relpath, mode):
448
411
        """Set permissions on a path.
449
412
 
450
413
        Only set permissions if the FTP server supports the 'SITE CHMOD'
451
414
        extension.
452
415
        """
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))
 
416
        try:
 
417
            mutter("FTP site chmod: setting permissions to %s on %s",
 
418
                str(mode), self._remote_path(relpath))
 
419
            ftp = self._get_FTP()
 
420
            cmd = "SITE CHMOD %s %s" % (self._remote_path(relpath), str(mode))
 
421
            ftp.sendcmd(cmd)
 
422
        except ftplib.error_perm, e:
 
423
            # Command probably not available on this server
 
424
            warning("FTP Could not set permissions to %s on %s. %s",
 
425
                    str(mode), self._remote_path(relpath), str(e))
465
426
 
466
427
    # TODO: jam 20060516 I believe ftp allows you to tell an ftp server
467
428
    #       to copy something to another machine. And you may be able
478
439
    def _rename(self, abs_from, abs_to, f):
479
440
        try:
480
441
            f.rename(abs_from, abs_to)
481
 
        except (ftplib.error_temp, ftplib.error_perm), e:
482
 
            self._translate_ftp_error(e, abs_from,
 
442
        except ftplib.error_perm, e:
 
443
            self._translate_perm_error(e, abs_from,
483
444
                ': unable to rename to %r' % (abs_to))
484
445
 
485
446
    def move(self, rel_from, rel_to):
491
452
            f = self._get_FTP()
492
453
            self._rename_and_overwrite(abs_from, abs_to, f)
493
454
        except ftplib.error_perm, e:
494
 
            self._translate_ftp_error(e, abs_from,
495
 
                extra='unable to rename to %r' % (rel_to,),
 
455
            self._translate_perm_error(e, abs_from,
 
456
                extra='unable to rename to %r' % (rel_to,), 
496
457
                unknown_exc=errors.PathError)
497
458
 
498
459
    def _rename_and_overwrite(self, abs_from, abs_to, f):
515
476
            mutter("FTP rm: %s", abspath)
516
477
            f.delete(abspath)
517
478
        except ftplib.error_perm, e:
518
 
            self._translate_ftp_error(e, abspath, 'error deleting',
 
479
            self._translate_perm_error(e, abspath, 'error deleting',
519
480
                unknown_exc=errors.NoSuchFile)
520
481
 
521
482
    def external_url(self):
533
494
        mutter("FTP nlst: %s", basepath)
534
495
        f = self._get_FTP()
535
496
        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
 
 
 
497
            paths = f.nlst(basepath)
 
498
        except ftplib.error_perm, e:
 
499
            self._translate_perm_error(e, relpath, extra='error with list_dir')
556
500
        # If FTP.nlst returns paths prefixed by relpath, strip 'em
557
501
        if paths and paths[0].startswith(basepath):
558
502
            entries = [path[len(basepath)+1:] for path in paths]
585
529
            f = self._get_FTP()
586
530
            return FtpStatResult(f, abspath)
587
531
        except ftplib.error_perm, e:
588
 
            self._translate_ftp_error(e, abspath, extra='error w/ stat')
 
532
            self._translate_perm_error(e, abspath, extra='error w/ stat')
589
533
 
590
534
    def lock_read(self, relpath):
591
535
        """Lock the given file for shared (read) access.
611
555
 
612
556
def get_test_permutations():
613
557
    """Return the permutations to be used in testing."""
614
 
    from bzrlib.tests import ftp_server
615
 
    return [(FtpTransport, ftp_server.FTPTestServer)]
 
558
    from bzrlib import tests
 
559
    if tests.FTPServerFeature.available():
 
560
        from bzrlib.tests import ftp_server
 
561
        return [(FtpTransport, ftp_server.FTPServer)]
 
562
    else:
 
563
        # Dummy server to have the test suite report the number of tests
 
564
        # needing that feature.
 
565
        class UnavailableFTPServer(object):
 
566
            def setUp(self):
 
567
                raise tests.UnavailableFeature(tests.FTPServerFeature)
 
568
 
 
569
        return [(FtpTransport, UnavailableFTPServer)]