/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: Olaf Conradi
  • Date: 2006-03-15 13:59:19 UTC
  • mto: (1558.4.9 Aaron's integration)
  • mto: This revision was merged to the branch mainline in revision 1612.
  • Revision ID: olaf@conradi.org-20060315135919-cf48fa226c66646e
Add parent location to info command (Closes feature bug #33364).

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
2
 
#
 
1
# Copyright (C) 2005 Canonical Ltd
 
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
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 urllib
 
32
import urlparse
34
33
import stat
35
34
import time
36
 
 
37
 
from bzrlib import (
38
 
    config,
39
 
    errors,
40
 
    osutils,
41
 
    urlutils,
42
 
    )
 
35
import random
 
36
from warnings import warn
 
37
 
 
38
 
 
39
from bzrlib.transport import Transport
 
40
from bzrlib.errors import (TransportNotPossible, TransportError,
 
41
                           NoSuchFile, FileExists)
43
42
from bzrlib.trace import mutter, warning
44
 
from bzrlib.transport import (
45
 
    AppendBasedFileStream,
46
 
    ConnectedTransport,
47
 
    _file_streams,
48
 
    register_urlparse_netloc_protocol,
49
 
    Server,
50
 
    )
51
 
 
52
 
 
53
 
register_urlparse_netloc_protocol('aftp')
54
 
 
55
 
 
56
 
class FtpPathError(errors.PathError):
57
 
    """FTP failed for path: %(path)s%(extra)s"""
 
43
 
 
44
 
 
45
_FTP_cache = {}
 
46
def _find_FTP(hostname, username, password, is_active):
 
47
    """Find an ftplib.FTP instance attached to this triplet."""
 
48
    key = "%s|%s|%s|%s" % (hostname, username, password, is_active)
 
49
    if key not in _FTP_cache:
 
50
        mutter("Constructing FTP instance against %r" % key)
 
51
        _FTP_cache[key] = ftplib.FTP(hostname, username, password)
 
52
        _FTP_cache[key].set_pasv(not is_active)
 
53
    return _FTP_cache[key]    
 
54
 
 
55
 
 
56
class FtpTransportError(TransportError):
 
57
    pass
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)
75
74
_number_of_retries = 2
76
75
_sleep_between_retries = 5
77
76
 
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
 
class FtpTransport(ConnectedTransport):
 
77
class FtpTransport(Transport):
84
78
    """This is the transport agent for ftp:// access."""
85
79
 
86
 
    def __init__(self, base, _from_transport=None):
 
80
    def __init__(self, base, _provided_instance=None):
87
81
        """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)
92
 
        self._unqualified_scheme = 'ftp'
93
 
        if self._scheme == 'aftp':
94
 
            self.is_active = True
95
 
        else:
96
 
            self.is_active = False
97
 
 
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
 
82
        assert base.startswith('ftp://') or base.startswith('aftp://')
 
83
        super(FtpTransport, self).__init__(base)
 
84
        self.is_active = base.startswith('aftp://')
 
85
        if self.is_active:
 
86
            base = base[1:]
 
87
        (self._proto, self._host,
 
88
            self._path, self._parameters,
 
89
            self._query, self._fragment) = urlparse.urlparse(self.base)
 
90
        self._FTP_instance = _provided_instance
101
91
 
102
92
    def _get_FTP(self):
103
93
        """Return the ftplib.FTP instance for this object."""
104
 
        # Ensures that a connection is established
105
 
        connection = self._get_connection()
106
 
        if connection is None:
107
 
            # First connection ever
108
 
            connection, credentials = self._create_connection()
109
 
            self._set_connection(connection, credentials)
110
 
        return connection
111
 
 
112
 
    connection_class = ftplib.FTP
113
 
 
114
 
    def _create_connection(self, credentials=None):
115
 
        """Create a new connection with the provided credentials.
116
 
 
117
 
        :param credentials: The credentials needed to establish the connection.
118
 
 
119
 
        :return: The created connection and its associated credentials.
120
 
 
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.
125
 
        """
126
 
        if credentials is None:
127
 
            user, password = self._user, self._password
128
 
        else:
129
 
            user, password = credentials
130
 
 
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
 
        mutter("Constructing FTP instance against %r" %
136
 
               ((self._host, self._port, user, '********',
137
 
                self.is_active),))
 
94
        if self._FTP_instance is not None:
 
95
            return self._FTP_instance
 
96
        
138
97
        try:
139
 
            connection = self.connection_class()
140
 
            connection.connect(host=self._host, port=self._port)
141
 
            self._login(connection, auth, user, password)
142
 
            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)
 
98
            username = ''
 
99
            password = ''
 
100
            hostname = self._host
 
101
            if '@' in hostname:
 
102
                username, hostname = hostname.split("@", 1)
 
103
            if ':' in username:
 
104
                username, password = username.split(":", 1)
 
105
 
 
106
            self._FTP_instance = _find_FTP(hostname, username, password,
 
107
                                           self.is_active)
 
108
            return self._FTP_instance
149
109
        except ftplib.error_perm, e:
150
 
            raise errors.TransportError(msg="Error setting up connection:"
151
 
                                        " %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)
160
 
 
161
 
    def _reconnect(self):
162
 
        """Create a new connection with the previously used credentials"""
163
 
        credentials = self._get_credentials()
164
 
        connection, credentials = self._create_connection(credentials)
165
 
        self._set_connection(connection, credentials)
166
 
 
167
 
    def _translate_ftp_error(self, err, path, extra=None,
168
 
                              unknown_exc=FtpPathError):
169
 
        """Try to translate an ftplib exception to a bzrlib exception.
170
 
 
171
 
        :param err: The error to translate into a bzr error
172
 
        :param path: The path which had problems
173
 
        :param extra: Extra information which can be included
174
 
        :param unknown_exc: If None, we will just raise the original exception
175
 
                    otherwise we raise unknown_exc(path, extra=extra)
176
 
        """
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
 
        s = str(err).lower()
181
 
        if not extra:
182
 
            extra = str(err)
183
 
        else:
184
 
            extra += ': ' + str(err)
185
 
        if ('no such file' in s
186
 
            or 'could not open' in s
187
 
            or 'no such dir' in s
188
 
            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
 
            ):
195
 
            raise errors.NoSuchFile(path, extra=extra)
196
 
        elif ('file exists' in s):
197
 
            raise errors.FileExists(path, extra=extra)
198
 
        elif ('not a directory' in s):
199
 
            raise errors.PathError(path, extra=extra)
200
 
        elif 'directory not empty' in s:
201
 
            raise errors.DirectoryNotEmpty(path, extra=extra)
202
 
 
203
 
        mutter('unable to understand error for path: %s: %s', path, err)
204
 
 
205
 
        if unknown_exc:
206
 
            raise unknown_exc(path, extra=extra)
207
 
        # TODO: jam 20060516 Consider re-raising the error wrapped in
208
 
        #       something like TransportError, but this loses the traceback
209
 
        #       Also, 'sftp' has a generic 'Failure' mode, which we use failure_exc
210
 
        #       to handle. Consider doing something like that here.
211
 
        #raise TransportError(msg='Error for path: %s' % (path,), orig_error=e)
212
 
        raise
 
110
            raise TransportError(msg="Error setting up connection: %s"
 
111
                                    % str(e), orig_error=e)
 
112
 
 
113
    def should_cache(self):
 
114
        """Return True if the data pulled across should be cached locally.
 
115
        """
 
116
        return True
 
117
 
 
118
    def clone(self, offset=None):
 
119
        """Return a new FtpTransport with root at self.base + offset.
 
120
        """
 
121
        mutter("FTP clone")
 
122
        if offset is None:
 
123
            return FtpTransport(self.base, self._FTP_instance)
 
124
        else:
 
125
            return FtpTransport(self.abspath(offset), self._FTP_instance)
 
126
 
 
127
    def _abspath(self, relpath):
 
128
        assert isinstance(relpath, basestring)
 
129
        relpath = urllib.unquote(relpath)
 
130
        if isinstance(relpath, basestring):
 
131
            relpath_parts = relpath.split('/')
 
132
        else:
 
133
            # TODO: Don't call this with an array - no magic interfaces
 
134
            relpath_parts = relpath[:]
 
135
        if len(relpath_parts) > 1:
 
136
            if relpath_parts[0] == '':
 
137
                raise ValueError("path %r within branch %r seems to be absolute"
 
138
                                 % (relpath, self._path))
 
139
        basepath = self._path.split('/')
 
140
        if len(basepath) > 0 and basepath[-1] == '':
 
141
            basepath = basepath[:-1]
 
142
        for p in relpath_parts:
 
143
            if p == '..':
 
144
                if len(basepath) == 0:
 
145
                    # In most filesystems, a request for the parent
 
146
                    # of root, just returns root.
 
147
                    continue
 
148
                basepath.pop()
 
149
            elif p == '.' or p == '':
 
150
                continue # No-op
 
151
            else:
 
152
                basepath.append(p)
 
153
        # Possibly, we could use urlparse.urljoin() here, but
 
154
        # I'm concerned about when it chooses to strip the last
 
155
        # portion of the path, and when it doesn't.
 
156
        return '/'.join(basepath)
 
157
    
 
158
    def abspath(self, relpath):
 
159
        """Return the full url to the given relative path.
 
160
        This can be supplied with a string or a list
 
161
        """
 
162
        path = self._abspath(relpath)
 
163
        return urlparse.urlunparse((self._proto,
 
164
                self._host, path, '', '', ''))
213
165
 
214
166
    def has(self, relpath):
215
 
        """Does the target location exist?"""
216
 
        # FIXME jam 20060516 We *do* ask about directories in the test suite
217
 
        #       We don't seem to in the actual codebase
218
 
        # XXX: I assume we're never asked has(dirname) and thus I use
219
 
        # the FTP size command and assume that if it doesn't raise,
220
 
        # all is good.
221
 
        abspath = self._remote_path(relpath)
 
167
        """Does the target location exist?
 
168
 
 
169
        XXX: I assume we're never asked has(dirname) and thus I use
 
170
        the FTP size command and assume that if it doesn't raise,
 
171
        all is good.
 
172
        """
222
173
        try:
223
174
            f = self._get_FTP()
224
 
            mutter('FTP has check: %s => %s', relpath, abspath)
225
 
            s = f.size(abspath)
226
 
            mutter("FTP has: %s", abspath)
 
175
            s = f.size(self._abspath(relpath))
 
176
            mutter("FTP has: %s" % self._abspath(relpath))
227
177
            return True
228
 
        except ftplib.error_perm, e:
229
 
            if ('is a directory' in str(e).lower()):
230
 
                mutter("FTP has dir: %s: %s", abspath, e)
231
 
                return True
232
 
            mutter("FTP has not: %s: %s", abspath, e)
 
178
        except ftplib.error_perm:
 
179
            mutter("FTP has not: %s" % self._abspath(relpath))
233
180
            return False
234
181
 
235
182
    def get(self, relpath, decode=False, retries=0):
244
191
        """
245
192
        # TODO: decode should be deprecated
246
193
        try:
247
 
            mutter("FTP get: %s", self._remote_path(relpath))
 
194
            mutter("FTP get: %s" % self._abspath(relpath))
248
195
            f = self._get_FTP()
249
196
            ret = StringIO()
250
 
            f.retrbinary('RETR '+self._remote_path(relpath), ret.write, 8192)
 
197
            f.retrbinary('RETR '+self._abspath(relpath), ret.write, 8192)
251
198
            ret.seek(0)
252
199
            return ret
253
200
        except ftplib.error_perm, e:
254
 
            raise errors.NoSuchFile(self.abspath(relpath), extra=str(e))
 
201
            raise NoSuchFile(self.abspath(relpath), extra=str(e))
255
202
        except ftplib.error_temp, e:
256
203
            if retries > _number_of_retries:
257
 
                raise errors.TransportError(msg="FTP temporary error during GET %s. Aborting."
 
204
                raise TransportError(msg="FTP temporary error during GET %s. Aborting."
258
205
                                     % self.abspath(relpath),
259
206
                                     orig_error=e)
260
207
            else:
261
 
                warning("FTP temporary error: %s. Retrying.", str(e))
262
 
                self._reconnect()
 
208
                warning("FTP temporary error: %s. Retrying." % str(e))
 
209
                self._FTP_instance = None
263
210
                return self.get(relpath, decode, retries+1)
264
211
        except EOFError, e:
265
212
            if retries > _number_of_retries:
266
 
                raise errors.TransportError("FTP control connection closed during GET %s."
 
213
                raise TransportError("FTP control connection closed during GET %s."
267
214
                                     % self.abspath(relpath),
268
215
                                     orig_error=e)
269
216
            else:
270
217
                warning("FTP control connection closed. Trying to reopen.")
271
218
                time.sleep(_sleep_between_retries)
272
 
                self._reconnect()
 
219
                self._FTP_instance = None
273
220
                return self.get(relpath, decode, retries+1)
274
221
 
275
 
    def put_file(self, relpath, fp, mode=None, retries=0):
 
222
    def put(self, relpath, fp, mode=None, retries=0):
276
223
        """Copy the file-like or string object into the location.
277
224
 
278
225
        :param relpath: Location to put the contents, relative to base.
280
227
        :param retries: Number of retries after temporary failures so far
281
228
                        for this operation.
282
229
 
283
 
        TODO: jam 20051215 ftp as a protocol seems to support chmod, but
284
 
        ftplib does not
 
230
        TODO: jam 20051215 ftp as a protocol seems to support chmod, but ftplib does not
285
231
        """
286
 
        abspath = self._remote_path(relpath)
287
 
        tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
 
232
        tmp_abspath = '%s.tmp.%.9f.%d.%d' % (self._abspath(relpath), time.time(),
288
233
                        os.getpid(), random.randint(0,0x7FFFFFFF))
289
 
        bytes = None
290
 
        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)
 
234
        if not hasattr(fp, 'read'):
 
235
            fp = StringIO(fp)
306
236
        try:
307
 
            mutter("FTP put: %s", abspath)
 
237
            mutter("FTP put: %s" % self._abspath(relpath))
308
238
            f = self._get_FTP()
309
239
            try:
310
240
                f.storbinary('STOR '+tmp_abspath, fp)
311
 
                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
 
241
                f.rename(tmp_abspath, self._abspath(relpath))
317
242
            except (ftplib.error_temp,EOFError), e:
318
243
                warning("Failure during ftp PUT. Deleting temporary file.")
319
244
                try:
320
245
                    f.delete(tmp_abspath)
321
246
                except:
322
 
                    warning("Failed to delete temporary file on the"
323
 
                            " server.\nFile: %s", tmp_abspath)
 
247
                    warning("Failed to delete temporary file on the server.\nFile: %s"
 
248
                            % tmp_abspath)
324
249
                    raise e
325
250
                raise
326
251
        except ftplib.error_perm, e:
327
 
            self._translate_ftp_error(e, abspath, extra='could not store',
328
 
                                       unknown_exc=errors.NoSuchFile)
 
252
            if "no such file" in str(e).lower():
 
253
                raise NoSuchFile("Error storing %s: %s"
 
254
                                 % (self.abspath(relpath), str(e)), extra=e)
 
255
            else:
 
256
                raise FtpTransportError(orig_error=e)
329
257
        except ftplib.error_temp, e:
330
258
            if retries > _number_of_retries:
331
 
                raise errors.TransportError("FTP temporary error during PUT %s. Aborting."
 
259
                raise TransportError("FTP temporary error during PUT %s. Aborting."
332
260
                                     % self.abspath(relpath), orig_error=e)
333
261
            else:
334
 
                warning("FTP temporary error: %s. Retrying.", str(e))
335
 
                self._reconnect()
336
 
                self.put_file(relpath, fp, mode, retries+1)
 
262
                warning("FTP temporary error: %s. Retrying." % str(e))
 
263
                self._FTP_instance = None
 
264
                self.put(relpath, fp, mode, retries+1)
337
265
        except EOFError:
338
266
            if retries > _number_of_retries:
339
 
                raise errors.TransportError("FTP control connection closed during PUT %s."
 
267
                raise TransportError("FTP control connection closed during PUT %s."
340
268
                                     % self.abspath(relpath), orig_error=e)
341
269
            else:
342
270
                warning("FTP control connection closed. Trying to reopen.")
343
271
                time.sleep(_sleep_between_retries)
344
 
                self._reconnect()
345
 
                self.put_file(relpath, fp, mode, retries+1)
 
272
                self._FTP_instance = None
 
273
                self.put(relpath, fp, mode, retries+1)
 
274
 
346
275
 
347
276
    def mkdir(self, relpath, mode=None):
348
277
        """Create a directory at the given path."""
349
 
        abspath = self._remote_path(relpath)
350
 
        try:
351
 
            mutter("FTP mkd: %s", abspath)
352
 
            f = self._get_FTP()
353
 
            f.mkd(abspath)
354
 
            self._setmode(relpath, mode)
355
 
        except ftplib.error_perm, e:
356
 
            self._translate_ftp_error(e, abspath,
357
 
                unknown_exc=errors.FileExists)
358
 
 
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
 
    def rmdir(self, rel_path):
375
 
        """Delete the directory at rel_path"""
376
 
        abspath = self._remote_path(rel_path)
377
 
        try:
378
 
            mutter("FTP rmd: %s", abspath)
379
 
            f = self._get_FTP()
380
 
            f.rmd(abspath)
381
 
        except ftplib.error_perm, e:
382
 
            self._translate_ftp_error(e, abspath, unknown_exc=errors.PathError)
383
 
 
384
 
    def append_file(self, relpath, f, mode=None):
 
278
        try:
 
279
            mutter("FTP mkd: %s" % self._abspath(relpath))
 
280
            f = self._get_FTP()
 
281
            try:
 
282
                f.mkd(self._abspath(relpath))
 
283
            except ftplib.error_perm, e:
 
284
                s = str(e)
 
285
                if 'File exists' in s:
 
286
                    raise FileExists(self.abspath(relpath), extra=s)
 
287
                else:
 
288
                    raise
 
289
        except ftplib.error_perm, e:
 
290
            raise TransportError(orig_error=e)
 
291
 
 
292
    def append(self, relpath, f):
385
293
        """Append the text in the file-like object into the final
386
294
        location.
387
295
        """
388
 
        text = f.read()
389
 
        abspath = self._remote_path(relpath)
390
 
        if self.has(relpath):
391
 
            ftp = self._get_FTP()
392
 
            result = ftp.size(abspath)
393
 
        else:
394
 
            result = 0
395
 
 
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)
401
 
 
402
 
        return result
403
 
 
404
 
    def _try_append(self, relpath, text, mode=None, retries=0):
405
 
        """Try repeatedly to append the given text to the file at relpath.
406
 
 
407
 
        This is a recursive function. On errors, it will be called until the
408
 
        number of retries is exceeded.
409
 
        """
410
 
        try:
411
 
            abspath = self._remote_path(relpath)
412
 
            mutter("FTP appe (try %d) to %s", retries, abspath)
413
 
            ftp = self._get_FTP()
414
 
            cmd = "APPE %s" % abspath
415
 
            conn = ftp.transfercmd(cmd)
416
 
            conn.sendall(text)
417
 
            conn.close()
418
 
            self._setmode(relpath, mode)
419
 
            ftp.getresp()
420
 
        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)
430
 
        except ftplib.error_temp, e:
431
 
            if retries > _number_of_retries:
432
 
                raise errors.TransportError(
433
 
                    "FTP temporary error during APPEND %s. Aborting."
434
 
                    % abspath, orig_error=e)
435
 
            else:
436
 
                warning("FTP temporary error: %s. Retrying.", str(e))
437
 
                self._reconnect()
438
 
                self._try_append(relpath, text, mode, retries+1)
439
 
 
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
 
    def _setmode(self, relpath, mode):
448
 
        """Set permissions on a path.
449
 
 
450
 
        Only set permissions if the FTP server supports the 'SITE CHMOD'
451
 
        extension.
452
 
        """
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))
465
 
 
466
 
    # TODO: jam 20060516 I believe ftp allows you to tell an ftp server
467
 
    #       to copy something to another machine. And you may be able
468
 
    #       to give it its own address as the 'to' location.
469
 
    #       So implement a fancier 'copy()'
470
 
 
471
 
    def rename(self, rel_from, rel_to):
472
 
        abs_from = self._remote_path(rel_from)
473
 
        abs_to = self._remote_path(rel_to)
474
 
        mutter("FTP rename: %s => %s", abs_from, abs_to)
475
 
        f = self._get_FTP()
476
 
        return self._rename(abs_from, abs_to, f)
477
 
 
478
 
    def _rename(self, abs_from, abs_to, f):
479
 
        try:
480
 
            f.rename(abs_from, abs_to)
481
 
        except (ftplib.error_temp, ftplib.error_perm), e:
482
 
            self._translate_ftp_error(e, abs_from,
483
 
                ': unable to rename to %r' % (abs_to))
 
296
        raise TransportNotPossible('ftp does not support append()')
 
297
 
 
298
    def copy(self, rel_from, rel_to):
 
299
        """Copy the item at rel_from to the location at rel_to"""
 
300
        raise TransportNotPossible('ftp does not (yet) support copy()')
484
301
 
485
302
    def move(self, rel_from, rel_to):
486
303
        """Move the item at rel_from to the location at rel_to"""
487
 
        abs_from = self._remote_path(rel_from)
488
 
        abs_to = self._remote_path(rel_to)
489
304
        try:
490
 
            mutter("FTP mv: %s => %s", abs_from, abs_to)
 
305
            mutter("FTP mv: %s => %s" % (self._abspath(rel_from),
 
306
                                         self._abspath(rel_to)))
491
307
            f = self._get_FTP()
492
 
            self._rename_and_overwrite(abs_from, abs_to, f)
 
308
            f.rename(self._abspath(rel_from), self._abspath(rel_to))
493
309
        except ftplib.error_perm, e:
494
 
            self._translate_ftp_error(e, abs_from,
495
 
                extra='unable to rename to %r' % (rel_to,),
496
 
                unknown_exc=errors.PathError)
497
 
 
498
 
    def _rename_and_overwrite(self, abs_from, abs_to, f):
499
 
        """Do a fancy rename on the remote server.
500
 
 
501
 
        Using the implementation provided by osutils.
502
 
        """
503
 
        osutils.fancy_rename(abs_from, abs_to,
504
 
            rename_func=lambda p1, p2: self._rename(p1, p2, f),
505
 
            unlink_func=lambda p: self._delete(p, f))
 
310
            raise TransportError(orig_error=e)
506
311
 
507
312
    def delete(self, relpath):
508
313
        """Delete the item at relpath"""
509
 
        abspath = self._remote_path(relpath)
510
 
        f = self._get_FTP()
511
 
        self._delete(abspath, f)
512
 
 
513
 
    def _delete(self, abspath, f):
514
314
        try:
515
 
            mutter("FTP rm: %s", abspath)
516
 
            f.delete(abspath)
 
315
            mutter("FTP rm: %s" % self._abspath(relpath))
 
316
            f = self._get_FTP()
 
317
            f.delete(self._abspath(relpath))
517
318
        except ftplib.error_perm, e:
518
 
            self._translate_ftp_error(e, abspath, 'error deleting',
519
 
                unknown_exc=errors.NoSuchFile)
520
 
 
521
 
    def external_url(self):
522
 
        """See bzrlib.transport.Transport.external_url."""
523
 
        # FTP URL's are externally usable.
524
 
        return self.base
 
319
            raise TransportError(orig_error=e)
525
320
 
526
321
    def listable(self):
527
322
        """See Transport.listable."""
529
324
 
530
325
    def list_dir(self, relpath):
531
326
        """See Transport.list_dir."""
532
 
        basepath = self._remote_path(relpath)
533
 
        mutter("FTP nlst: %s", basepath)
534
 
        f = self._get_FTP()
535
327
        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
 
 
556
 
        # If FTP.nlst returns paths prefixed by relpath, strip 'em
557
 
        if paths and paths[0].startswith(basepath):
558
 
            entries = [path[len(basepath)+1:] for path in paths]
559
 
        else:
560
 
            entries = paths
561
 
        # Remove . and .. if present
562
 
        return [urlutils.escape(entry) for entry in entries
563
 
                if entry not in ('.', '..')]
 
328
            mutter("FTP nlst: %s" % self._abspath(relpath))
 
329
            f = self._get_FTP()
 
330
            basepath = self._abspath(relpath)
 
331
            # FTP.nlst returns paths prefixed by relpath, strip 'em
 
332
            the_list = f.nlst(basepath)
 
333
            stripped = [path[len(basepath)+1:] for path in the_list]
 
334
            # Remove . and .. if present, and return
 
335
            return [path for path in stripped if path not in (".", "..")]
 
336
        except ftplib.error_perm, e:
 
337
            raise TransportError(orig_error=e)
564
338
 
565
339
    def iter_files_recursive(self):
566
340
        """See Transport.iter_files_recursive.
569
343
        mutter("FTP iter_files_recursive")
570
344
        queue = list(self.list_dir("."))
571
345
        while queue:
572
 
            relpath = queue.pop(0)
 
346
            relpath = urllib.quote(queue.pop(0))
573
347
            st = self.stat(relpath)
574
348
            if stat.S_ISDIR(st.st_mode):
575
349
                for i, basename in enumerate(self.list_dir(relpath)):
578
352
                yield relpath
579
353
 
580
354
    def stat(self, relpath):
581
 
        """Return the stat information for a file."""
582
 
        abspath = self._remote_path(relpath)
 
355
        """Return the stat information for a file.
 
356
        """
583
357
        try:
584
 
            mutter("FTP stat: %s", abspath)
 
358
            mutter("FTP stat: %s" % self._abspath(relpath))
585
359
            f = self._get_FTP()
586
 
            return FtpStatResult(f, abspath)
 
360
            return FtpStatResult(f, self._abspath(relpath))
587
361
        except ftplib.error_perm, e:
588
 
            self._translate_ftp_error(e, abspath, extra='error w/ stat')
 
362
            if "no such file" in str(e).lower():
 
363
                raise NoSuchFile("Error storing %s: %s"
 
364
                                 % (self.abspath(relpath), str(e)), extra=e)
 
365
            else:
 
366
                raise FtpTransportError(orig_error=e)
589
367
 
590
368
    def lock_read(self, relpath):
591
369
        """Lock the given file for shared (read) access.
611
389
 
612
390
def get_test_permutations():
613
391
    """Return the permutations to be used in testing."""
614
 
    from bzrlib.tests import ftp_server
615
 
    return [(FtpTransport, ftp_server.FTPTestServer)]
 
392
    warn("There are no FTP transport provider tests yet.")
 
393
    return []