~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/ftp.py

  • Committer: Robert Collins
  • Date: 2006-04-19 23:32:08 UTC
  • mto: (1711.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 1674.
  • Revision ID: robertc@robertcollins.net-20060419233208-2ed6906796994316
Make knit the default format.
Adjust affect tests to either have knit specific values or to be more generic,
as appropriate.
Disable all SFTP prefetching for known paramikos - direct readv support is now
a TODO.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
27
27
from cStringIO import StringIO
28
28
import errno
29
29
import ftplib
30
 
import getpass
31
30
import os
32
 
import os.path
 
31
import urllib
33
32
import urlparse
34
 
import socket
35
33
import stat
36
34
import time
37
35
import random
38
36
from warnings import warn
39
37
 
40
 
from bzrlib import (
41
 
    config,
42
 
    errors,
43
 
    osutils,
44
 
    urlutils,
45
 
    )
 
38
 
 
39
from bzrlib.transport import Transport
 
40
from bzrlib.errors import (TransportNotPossible, TransportError,
 
41
                           NoSuchFile, FileExists, DirectoryNotEmpty)
46
42
from bzrlib.trace import mutter, warning
47
 
from bzrlib.transport import (
48
 
    AppendBasedFileStream,
49
 
    ConnectedTransport,
50
 
    _file_streams,
51
 
    register_urlparse_netloc_protocol,
52
 
    Server,
53
 
    )
54
 
from bzrlib.transport.local import LocalURLServer
55
 
import bzrlib.ui
56
 
 
57
 
 
58
 
register_urlparse_netloc_protocol('aftp')
59
 
 
60
 
 
61
 
class FtpPathError(errors.PathError):
62
 
    """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
63
58
 
64
59
 
65
60
class FtpStatResult(object):
79
74
_number_of_retries = 2
80
75
_sleep_between_retries = 5
81
76
 
82
 
# FIXME: there are inconsistencies in the way temporary errors are
83
 
# handled. Sometimes we reconnect, sometimes we raise an exception. Care should
84
 
# be taken to analyze the implications for write operations (read operations
85
 
# are safe to retry). Overall even some read operations are never
86
 
# retried. --vila 20070720 (Bug #127164)
87
 
class FtpTransport(ConnectedTransport):
 
77
class FtpTransport(Transport):
88
78
    """This is the transport agent for ftp:// access."""
89
79
 
90
 
    def __init__(self, base, _from_transport=None):
 
80
    def __init__(self, base, _provided_instance=None):
91
81
        """Set the base path where files will be stored."""
92
 
        if not (base.startswith('ftp://') or base.startswith('aftp://')):
93
 
            raise ValueError(base)
94
 
        super(FtpTransport, self).__init__(base,
95
 
                                           _from_transport=_from_transport)
96
 
        self._unqualified_scheme = 'ftp'
97
 
        if self._scheme == 'aftp':
98
 
            self.is_active = True
99
 
        else:
100
 
            self.is_active = False
 
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
 
    def _create_connection(self, credentials=None):
113
 
        """Create a new connection with the provided credentials.
114
 
 
115
 
        :param credentials: The credentials needed to establish the connection.
116
 
 
117
 
        :return: The created connection and its associated credentials.
118
 
 
119
 
        The input credentials are only the password as it may have been
120
 
        entered interactively by the user and may be different from the one
121
 
        provided in base url at transport creation time.  The returned
122
 
        credentials are username, password.
123
 
        """
124
 
        if credentials is None:
125
 
            user, password = self._user, self._password
126
 
        else:
127
 
            user, password = credentials
128
 
 
129
 
        auth = config.AuthenticationConfig()
130
 
        if user is None:
131
 
            user = auth.get_user('ftp', self._host, port=self._port)
132
 
            if user is None:
133
 
                # Default to local user
134
 
                user = getpass.getuser()
135
 
 
136
 
        mutter("Constructing FTP instance against %r" %
137
 
               ((self._host, self._port, user, '********',
138
 
                self.is_active),))
 
94
        if self._FTP_instance is not None:
 
95
            return self._FTP_instance
 
96
        
139
97
        try:
140
 
            connection = ftplib.FTP()
141
 
            connection.connect(host=self._host, port=self._port)
142
 
            if user and user != 'anonymous' and \
143
 
                    password is None: # '' is a valid password
144
 
                password = auth.get_password('ftp', self._host, user,
145
 
                                             port=self._port)
146
 
            connection.login(user=user, passwd=password)
147
 
            connection.set_pasv(not self.is_active)
148
 
        except socket.error, e:
149
 
            raise errors.SocketConnectionError(self._host, self._port,
150
 
                                               msg='Unable to connect to',
151
 
                                               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
152
109
        except ftplib.error_perm, e:
153
 
            raise errors.TransportError(msg="Error setting up connection:"
154
 
                                        " %s" % str(e), orig_error=e)
155
 
        return connection, (user, password)
156
 
 
157
 
    def _reconnect(self):
158
 
        """Create a new connection with the previously used credentials"""
159
 
        credentials = self._get_credentials()
160
 
        connection, credentials = self._create_connection(credentials)
161
 
        self._set_connection(connection, credentials)
162
 
 
163
 
    def _translate_perm_error(self, err, path, extra=None,
164
 
                              unknown_exc=FtpPathError):
165
 
        """Try to translate an ftplib.error_perm exception.
166
 
 
167
 
        :param err: The error to translate into a bzr error
168
 
        :param path: The path which had problems
169
 
        :param extra: Extra information which can be included
170
 
        :param unknown_exc: If None, we will just raise the original exception
171
 
                    otherwise we raise unknown_exc(path, extra=extra)
172
 
        """
173
 
        s = str(err).lower()
174
 
        if not extra:
175
 
            extra = str(err)
176
 
        else:
177
 
            extra += ': ' + str(err)
178
 
        if ('no such file' in s
179
 
            or 'could not open' in s
180
 
            or 'no such dir' in s
181
 
            or 'could not create file' in s # vsftpd
182
 
            or 'file doesn\'t exist' in s
183
 
            or 'rnfr command failed.' in s # vsftpd RNFR reply if file not found
184
 
            or 'file/directory not found' in s # filezilla server
185
 
            # Microsoft FTP-Service RNFR reply if file not found
186
 
            or (s.startswith('550 ') and 'unable to rename to' in extra)
187
 
            ):
188
 
            raise errors.NoSuchFile(path, extra=extra)
189
 
        if ('file exists' in s):
190
 
            raise errors.FileExists(path, extra=extra)
191
 
        if ('not a directory' in s):
192
 
            raise errors.PathError(path, extra=extra)
193
 
 
194
 
        mutter('unable to understand error for path: %s: %s', path, err)
195
 
 
196
 
        if unknown_exc:
197
 
            raise unknown_exc(path, extra=extra)
198
 
        # TODO: jam 20060516 Consider re-raising the error wrapped in 
199
 
        #       something like TransportError, but this loses the traceback
200
 
        #       Also, 'sftp' has a generic 'Failure' mode, which we use failure_exc
201
 
        #       to handle. Consider doing something like that here.
202
 
        #raise TransportError(msg='Error for path: %s' % (path,), orig_error=e)
203
 
        raise
204
 
 
205
 
    def _remote_path(self, relpath):
206
 
        # XXX: It seems that ftplib does not handle Unicode paths
207
 
        # at the same time, medusa won't handle utf8 paths So if
208
 
        # we .encode(utf8) here (see ConnectedTransport
209
 
        # implementation), then we get a Server failure.  while
210
 
        # if we use str(), we get a UnicodeError, and the test
211
 
        # suite just skips testing UnicodePaths.
212
 
        relative = str(urlutils.unescape(relpath))
213
 
        remote_path = self._combine_paths(self._path, relative)
214
 
        return remote_path
 
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, '', '', ''))
215
165
 
216
166
    def has(self, relpath):
217
 
        """Does the target location exist?"""
218
 
        # FIXME jam 20060516 We *do* ask about directories in the test suite
219
 
        #       We don't seem to in the actual codebase
220
 
        # XXX: I assume we're never asked has(dirname) and thus I use
221
 
        # the FTP size command and assume that if it doesn't raise,
222
 
        # all is good.
223
 
        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
        """
224
173
        try:
225
174
            f = self._get_FTP()
226
 
            mutter('FTP has check: %s => %s', relpath, abspath)
227
 
            s = f.size(abspath)
228
 
            mutter("FTP has: %s", abspath)
 
175
            s = f.size(self._abspath(relpath))
 
176
            mutter("FTP has: %s" % self._abspath(relpath))
229
177
            return True
230
 
        except ftplib.error_perm, e:
231
 
            if ('is a directory' in str(e).lower()):
232
 
                mutter("FTP has dir: %s: %s", abspath, e)
233
 
                return True
234
 
            mutter("FTP has not: %s: %s", abspath, e)
 
178
        except ftplib.error_perm:
 
179
            mutter("FTP has not: %s" % self._abspath(relpath))
235
180
            return False
236
181
 
237
182
    def get(self, relpath, decode=False, retries=0):
246
191
        """
247
192
        # TODO: decode should be deprecated
248
193
        try:
249
 
            mutter("FTP get: %s", self._remote_path(relpath))
 
194
            mutter("FTP get: %s" % self._abspath(relpath))
250
195
            f = self._get_FTP()
251
196
            ret = StringIO()
252
 
            f.retrbinary('RETR '+self._remote_path(relpath), ret.write, 8192)
 
197
            f.retrbinary('RETR '+self._abspath(relpath), ret.write, 8192)
253
198
            ret.seek(0)
254
199
            return ret
255
200
        except ftplib.error_perm, e:
256
 
            raise errors.NoSuchFile(self.abspath(relpath), extra=str(e))
 
201
            raise NoSuchFile(self.abspath(relpath), extra=str(e))
257
202
        except ftplib.error_temp, e:
258
203
            if retries > _number_of_retries:
259
 
                raise errors.TransportError(msg="FTP temporary error during GET %s. Aborting."
 
204
                raise TransportError(msg="FTP temporary error during GET %s. Aborting."
260
205
                                     % self.abspath(relpath),
261
206
                                     orig_error=e)
262
207
            else:
263
 
                warning("FTP temporary error: %s. Retrying.", str(e))
264
 
                self._reconnect()
 
208
                warning("FTP temporary error: %s. Retrying." % str(e))
 
209
                self._FTP_instance = None
265
210
                return self.get(relpath, decode, retries+1)
266
211
        except EOFError, e:
267
212
            if retries > _number_of_retries:
268
 
                raise errors.TransportError("FTP control connection closed during GET %s."
 
213
                raise TransportError("FTP control connection closed during GET %s."
269
214
                                     % self.abspath(relpath),
270
215
                                     orig_error=e)
271
216
            else:
272
217
                warning("FTP control connection closed. Trying to reopen.")
273
218
                time.sleep(_sleep_between_retries)
274
 
                self._reconnect()
 
219
                self._FTP_instance = None
275
220
                return self.get(relpath, decode, retries+1)
276
221
 
277
 
    def put_file(self, relpath, fp, mode=None, retries=0):
 
222
    def put(self, relpath, fp, mode=None, retries=0):
278
223
        """Copy the file-like or string object into the location.
279
224
 
280
225
        :param relpath: Location to put the contents, relative to base.
282
227
        :param retries: Number of retries after temporary failures so far
283
228
                        for this operation.
284
229
 
285
 
        TODO: jam 20051215 ftp as a protocol seems to support chmod, but
286
 
        ftplib does not
 
230
        TODO: jam 20051215 ftp as a protocol seems to support chmod, but ftplib does not
287
231
        """
288
 
        abspath = self._remote_path(relpath)
289
 
        tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
 
232
        tmp_abspath = '%s.tmp.%.9f.%d.%d' % (self._abspath(relpath), time.time(),
290
233
                        os.getpid(), random.randint(0,0x7FFFFFFF))
291
 
        bytes = None
292
 
        if getattr(fp, 'read', None) is None:
293
 
            # hand in a string IO
294
 
            bytes = fp
295
 
            fp = StringIO(bytes)
296
 
        else:
297
 
            # capture the byte count; .read() may be read only so
298
 
            # decorate it.
299
 
            class byte_counter(object):
300
 
                def __init__(self, fp):
301
 
                    self.fp = fp
302
 
                    self.counted_bytes = 0
303
 
                def read(self, count):
304
 
                    result = self.fp.read(count)
305
 
                    self.counted_bytes += len(result)
306
 
                    return result
307
 
            fp = byte_counter(fp)
 
234
        if not hasattr(fp, 'read'):
 
235
            fp = StringIO(fp)
308
236
        try:
309
 
            mutter("FTP put: %s", abspath)
 
237
            mutter("FTP put: %s" % self._abspath(relpath))
310
238
            f = self._get_FTP()
311
239
            try:
312
240
                f.storbinary('STOR '+tmp_abspath, fp)
313
 
                self._rename_and_overwrite(tmp_abspath, abspath, f)
314
 
                self._setmode(relpath, mode)
315
 
                if bytes is not None:
316
 
                    return len(bytes)
317
 
                else:
318
 
                    return fp.counted_bytes
 
241
                f.rename(tmp_abspath, self._abspath(relpath))
319
242
            except (ftplib.error_temp,EOFError), e:
320
243
                warning("Failure during ftp PUT. Deleting temporary file.")
321
244
                try:
322
245
                    f.delete(tmp_abspath)
323
246
                except:
324
 
                    warning("Failed to delete temporary file on the"
325
 
                            " server.\nFile: %s", tmp_abspath)
 
247
                    warning("Failed to delete temporary file on the server.\nFile: %s"
 
248
                            % tmp_abspath)
326
249
                    raise e
327
250
                raise
328
251
        except ftplib.error_perm, e:
329
 
            self._translate_perm_error(e, abspath, extra='could not store',
330
 
                                       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)
331
257
        except ftplib.error_temp, e:
332
258
            if retries > _number_of_retries:
333
 
                raise errors.TransportError("FTP temporary error during PUT %s. Aborting."
 
259
                raise TransportError("FTP temporary error during PUT %s. Aborting."
334
260
                                     % self.abspath(relpath), orig_error=e)
335
261
            else:
336
 
                warning("FTP temporary error: %s. Retrying.", str(e))
337
 
                self._reconnect()
338
 
                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)
339
265
        except EOFError:
340
266
            if retries > _number_of_retries:
341
 
                raise errors.TransportError("FTP control connection closed during PUT %s."
 
267
                raise TransportError("FTP control connection closed during PUT %s."
342
268
                                     % self.abspath(relpath), orig_error=e)
343
269
            else:
344
270
                warning("FTP control connection closed. Trying to reopen.")
345
271
                time.sleep(_sleep_between_retries)
346
 
                self._reconnect()
347
 
                self.put_file(relpath, fp, mode, retries+1)
 
272
                self._FTP_instance = None
 
273
                self.put(relpath, fp, mode, retries+1)
 
274
 
348
275
 
349
276
    def mkdir(self, relpath, mode=None):
350
277
        """Create a directory at the given path."""
351
 
        abspath = self._remote_path(relpath)
352
278
        try:
353
 
            mutter("FTP mkd: %s", abspath)
 
279
            mutter("FTP mkd: %s" % self._abspath(relpath))
354
280
            f = self._get_FTP()
355
 
            f.mkd(abspath)
356
 
            self._setmode(relpath, mode)
 
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
357
289
        except ftplib.error_perm, e:
358
 
            self._translate_perm_error(e, abspath,
359
 
                unknown_exc=errors.FileExists)
360
 
 
361
 
    def open_write_stream(self, relpath, mode=None):
362
 
        """See Transport.open_write_stream."""
363
 
        self.put_bytes(relpath, "", mode)
364
 
        result = AppendBasedFileStream(self, relpath)
365
 
        _file_streams[self.abspath(relpath)] = result
366
 
        return result
367
 
 
368
 
    def recommended_page_size(self):
369
 
        """See Transport.recommended_page_size().
370
 
 
371
 
        For FTP we suggest a large page size to reduce the overhead
372
 
        introduced by latency.
373
 
        """
374
 
        return 64 * 1024
 
290
            raise TransportError(orig_error=e)
375
291
 
376
292
    def rmdir(self, rel_path):
377
293
        """Delete the directory at rel_path"""
378
 
        abspath = self._remote_path(rel_path)
379
294
        try:
380
 
            mutter("FTP rmd: %s", abspath)
 
295
            mutter("FTP rmd: %s" % self._abspath(rel_path))
 
296
 
381
297
            f = self._get_FTP()
382
 
            f.rmd(abspath)
 
298
            f.rmd(self._abspath(rel_path))
383
299
        except ftplib.error_perm, e:
384
 
            self._translate_perm_error(e, abspath, unknown_exc=errors.PathError)
 
300
            if str(e).endswith("Directory not empty"):
 
301
                raise DirectoryNotEmpty(self._abspath(rel_path), extra=str(e))
 
302
            else:
 
303
                raise TransportError(msg="Cannot remove directory at %s" % \
 
304
                        self._abspath(rel_path), extra=str(e))
385
305
 
386
 
    def append_file(self, relpath, f, mode=None):
 
306
    def append(self, relpath, f):
387
307
        """Append the text in the file-like object into the final
388
308
        location.
389
309
        """
390
 
        abspath = self._remote_path(relpath)
391
 
        if self.has(relpath):
392
 
            ftp = self._get_FTP()
393
 
            result = ftp.size(abspath)
394
 
        else:
395
 
            result = 0
396
 
 
397
 
        mutter("FTP appe to %s", abspath)
398
 
        self._try_append(relpath, f.read(), mode)
399
 
 
400
 
        return result
401
 
 
402
 
    def _try_append(self, relpath, text, mode=None, retries=0):
403
 
        """Try repeatedly to append the given text to the file at relpath.
404
 
        
405
 
        This is a recursive function. On errors, it will be called until the
406
 
        number of retries is exceeded.
407
 
        """
408
 
        try:
409
 
            abspath = self._remote_path(relpath)
410
 
            mutter("FTP appe (try %d) to %s", retries, abspath)
411
 
            ftp = self._get_FTP()
412
 
            ftp.voidcmd("TYPE I")
413
 
            cmd = "APPE %s" % abspath
414
 
            conn = ftp.transfercmd(cmd)
415
 
            conn.sendall(text)
416
 
            conn.close()
417
 
            self._setmode(relpath, mode)
418
 
            ftp.getresp()
419
 
        except ftplib.error_perm, e:
420
 
            self._translate_perm_error(e, abspath, extra='error appending',
421
 
                unknown_exc=errors.NoSuchFile)
422
 
        except ftplib.error_temp, e:
423
 
            if retries > _number_of_retries:
424
 
                raise errors.TransportError("FTP temporary error during APPEND %s." \
425
 
                        "Aborting." % abspath, orig_error=e)
426
 
            else:
427
 
                warning("FTP temporary error: %s. Retrying.", str(e))
428
 
                self._reconnect()
429
 
                self._try_append(relpath, text, mode, retries+1)
430
 
 
431
 
    def _setmode(self, relpath, mode):
432
 
        """Set permissions on a path.
433
 
 
434
 
        Only set permissions if the FTP server supports the 'SITE CHMOD'
435
 
        extension.
436
 
        """
437
 
        if mode:
438
 
            try:
439
 
                mutter("FTP site chmod: setting permissions to %s on %s",
440
 
                    str(mode), self._remote_path(relpath))
441
 
                ftp = self._get_FTP()
442
 
                cmd = "SITE CHMOD %s %s" % (oct(mode),
443
 
                                            self._remote_path(relpath))
444
 
                ftp.sendcmd(cmd)
445
 
            except ftplib.error_perm, e:
446
 
                # Command probably not available on this server
447
 
                warning("FTP Could not set permissions to %s on %s. %s",
448
 
                        str(mode), self._remote_path(relpath), str(e))
449
 
 
450
 
    # TODO: jam 20060516 I believe ftp allows you to tell an ftp server
451
 
    #       to copy something to another machine. And you may be able
452
 
    #       to give it its own address as the 'to' location.
453
 
    #       So implement a fancier 'copy()'
454
 
 
455
 
    def rename(self, rel_from, rel_to):
456
 
        abs_from = self._remote_path(rel_from)
457
 
        abs_to = self._remote_path(rel_to)
458
 
        mutter("FTP rename: %s => %s", abs_from, abs_to)
459
 
        f = self._get_FTP()
460
 
        return self._rename(abs_from, abs_to, f)
461
 
 
462
 
    def _rename(self, abs_from, abs_to, f):
463
 
        try:
464
 
            f.rename(abs_from, abs_to)
465
 
        except ftplib.error_perm, e:
466
 
            self._translate_perm_error(e, abs_from,
467
 
                ': unable to rename to %r' % (abs_to))
 
310
        raise TransportNotPossible('ftp does not support append()')
 
311
 
 
312
    def copy(self, rel_from, rel_to):
 
313
        """Copy the item at rel_from to the location at rel_to"""
 
314
        raise TransportNotPossible('ftp does not (yet) support copy()')
468
315
 
469
316
    def move(self, rel_from, rel_to):
470
317
        """Move the item at rel_from to the location at rel_to"""
471
 
        abs_from = self._remote_path(rel_from)
472
 
        abs_to = self._remote_path(rel_to)
473
318
        try:
474
 
            mutter("FTP mv: %s => %s", abs_from, abs_to)
 
319
            mutter("FTP mv: %s => %s" % (self._abspath(rel_from),
 
320
                                         self._abspath(rel_to)))
475
321
            f = self._get_FTP()
476
 
            self._rename_and_overwrite(abs_from, abs_to, f)
 
322
            f.rename(self._abspath(rel_from), self._abspath(rel_to))
477
323
        except ftplib.error_perm, e:
478
 
            self._translate_perm_error(e, abs_from,
479
 
                extra='unable to rename to %r' % (rel_to,), 
480
 
                unknown_exc=errors.PathError)
481
 
 
482
 
    def _rename_and_overwrite(self, abs_from, abs_to, f):
483
 
        """Do a fancy rename on the remote server.
484
 
 
485
 
        Using the implementation provided by osutils.
486
 
        """
487
 
        osutils.fancy_rename(abs_from, abs_to,
488
 
            rename_func=lambda p1, p2: self._rename(p1, p2, f),
489
 
            unlink_func=lambda p: self._delete(p, f))
 
324
            raise TransportError(orig_error=e)
 
325
 
 
326
    rename = move
490
327
 
491
328
    def delete(self, relpath):
492
329
        """Delete the item at relpath"""
493
 
        abspath = self._remote_path(relpath)
494
 
        f = self._get_FTP()
495
 
        self._delete(abspath, f)
496
 
 
497
 
    def _delete(self, abspath, f):
498
330
        try:
499
 
            mutter("FTP rm: %s", abspath)
500
 
            f.delete(abspath)
 
331
            mutter("FTP rm: %s" % self._abspath(relpath))
 
332
            f = self._get_FTP()
 
333
            f.delete(self._abspath(relpath))
501
334
        except ftplib.error_perm, e:
502
 
            self._translate_perm_error(e, abspath, 'error deleting',
503
 
                unknown_exc=errors.NoSuchFile)
504
 
 
505
 
    def external_url(self):
506
 
        """See bzrlib.transport.Transport.external_url."""
507
 
        # FTP URL's are externally usable.
508
 
        return self.base
 
335
            if str(e).endswith("No such file or directory"):
 
336
                raise NoSuchFile(self._abspath(relpath), extra=str(e))
 
337
            else:
 
338
                raise TransportError(orig_error=e)
509
339
 
510
340
    def listable(self):
511
341
        """See Transport.listable."""
513
343
 
514
344
    def list_dir(self, relpath):
515
345
        """See Transport.list_dir."""
516
 
        basepath = self._remote_path(relpath)
517
 
        mutter("FTP nlst: %s", basepath)
518
 
        f = self._get_FTP()
519
346
        try:
520
 
            paths = f.nlst(basepath)
 
347
            mutter("FTP nlst: %s" % self._abspath(relpath))
 
348
            f = self._get_FTP()
 
349
            basepath = self._abspath(relpath)
 
350
            # FTP.nlst returns paths prefixed by relpath, strip 'em
 
351
            the_list = f.nlst(basepath)
 
352
            stripped = [path[len(basepath)+1:] for path in the_list]
 
353
            # Remove . and .. if present, and return
 
354
            return [path for path in stripped if path not in (".", "..")]
521
355
        except ftplib.error_perm, e:
522
 
            self._translate_perm_error(e, relpath, extra='error with list_dir')
523
 
        except ftplib.error_temp, e:
524
 
            # xs4all's ftp server raises a 450 temp error when listing an empty
525
 
            # directory. Check for that and just return an empty list in that
526
 
            # case. See bug #215522
527
 
            if str(e).lower().startswith('450 no files found'):
528
 
                mutter('FTP Server returned "%s" for nlst.'
529
 
                       ' Assuming it means empty directory',
530
 
                       str(e))
531
 
                return []
532
 
            raise
533
 
        # If FTP.nlst returns paths prefixed by relpath, strip 'em
534
 
        if paths and paths[0].startswith(basepath):
535
 
            entries = [path[len(basepath)+1:] for path in paths]
536
 
        else:
537
 
            entries = paths
538
 
        # Remove . and .. if present
539
 
        return [urlutils.escape(entry) for entry in entries
540
 
                if entry not in ('.', '..')]
 
356
            raise TransportError(orig_error=e)
541
357
 
542
358
    def iter_files_recursive(self):
543
359
        """See Transport.iter_files_recursive.
546
362
        mutter("FTP iter_files_recursive")
547
363
        queue = list(self.list_dir("."))
548
364
        while queue:
549
 
            relpath = queue.pop(0)
 
365
            relpath = urllib.quote(queue.pop(0))
550
366
            st = self.stat(relpath)
551
367
            if stat.S_ISDIR(st.st_mode):
552
368
                for i, basename in enumerate(self.list_dir(relpath)):
555
371
                yield relpath
556
372
 
557
373
    def stat(self, relpath):
558
 
        """Return the stat information for a file."""
559
 
        abspath = self._remote_path(relpath)
 
374
        """Return the stat information for a file.
 
375
        """
560
376
        try:
561
 
            mutter("FTP stat: %s", abspath)
 
377
            mutter("FTP stat: %s" % self._abspath(relpath))
562
378
            f = self._get_FTP()
563
 
            return FtpStatResult(f, abspath)
 
379
            return FtpStatResult(f, self._abspath(relpath))
564
380
        except ftplib.error_perm, e:
565
 
            self._translate_perm_error(e, abspath, extra='error w/ stat')
 
381
            if "no such file" in str(e).lower():
 
382
                raise NoSuchFile("Error storing %s: %s"
 
383
                                 % (self.abspath(relpath), str(e)), extra=e)
 
384
            else:
 
385
                raise FtpTransportError(orig_error=e)
566
386
 
567
387
    def lock_read(self, relpath):
568
388
        """Lock the given file for shared (read) access.
588
408
 
589
409
def get_test_permutations():
590
410
    """Return the permutations to be used in testing."""
591
 
    from bzrlib import tests
592
 
    if tests.FTPServerFeature.available():
593
 
        from bzrlib.tests import ftp_server
594
 
        return [(FtpTransport, ftp_server.FTPServer)]
595
 
    else:
596
 
        # Dummy server to have the test suite report the number of tests
597
 
        # needing that feature. We raise UnavailableFeature from methods before
598
 
        # the test server is being used. Doing so in the setUp method has bad
599
 
        # side-effects (tearDown is never called).
600
 
        class UnavailableFTPServer(object):
601
 
 
602
 
            def setUp(self):
603
 
                pass
604
 
 
605
 
            def tearDown(self):
606
 
                pass
607
 
 
608
 
            def get_url(self):
609
 
                raise tests.UnavailableFeature(tests.FTPServerFeature)
610
 
 
611
 
            def get_bogus_url(self):
612
 
                raise tests.UnavailableFeature(tests.FTPServerFeature)
613
 
 
614
 
        return [(FtpTransport, UnavailableFTPServer)]
 
411
    warn("There are no FTP transport provider tests yet.")
 
412
    return []