57
class FtpTransport(Transport):
79
_number_of_retries = 2
80
_sleep_between_retries = 5
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):
58
88
"""This is the transport agent for ftp:// access."""
60
def __init__(self, base, _provided_instance=None):
90
def __init__(self, base, _from_transport=None):
61
91
"""Set the base path where files will be stored."""
62
92
assert base.startswith('ftp://') or base.startswith('aftp://')
63
super(FtpTransport, self).__init__(base)
64
self.is_active = base.startswith('aftp://')
67
(self._proto, self._host,
68
self._path, self._parameters,
69
self._query, self._fragment) = urlparse.urlparse(self.base)
70
self._FTP_instance = _provided_instance
93
super(FtpTransport, self).__init__(base,
94
_from_transport=_from_transport)
95
self._unqualified_scheme = 'ftp'
96
if self._scheme == 'aftp':
99
self.is_active = False
73
101
def _get_FTP(self):
74
102
"""Return the ftplib.FTP instance for this object."""
75
if self._FTP_instance is not None:
76
return self._FTP_instance
103
# Ensures that a connection is established
104
connection = self._get_connection()
105
if connection is None:
106
# First connection ever
107
connection, credentials = self._create_connection()
108
self._set_connection(connection, credentials)
111
def _create_connection(self, credentials=None):
112
"""Create a new connection with the provided credentials.
114
:param credentials: The credentials needed to establish the connection.
116
:return: The created connection and its associated credentials.
118
The credentials are only the password as it may have been entered
119
interactively by the user and may be different from the one provided
120
in base url at transport creation time.
122
if credentials is None:
123
user, password = self._user, self._password
125
user, password = credentials
127
auth = config.AuthenticationConfig()
129
user = auth.get_user('ftp', self._host, port=self._port)
131
# Default to local user
132
user = getpass.getuser()
134
mutter("Constructing FTP instance against %r" %
135
((self._host, self._port, user, '********',
83
username, hostname = hostname.split("@", 1)
85
username, password = username.split(":", 1)
87
mutter("Constructing FTP instance")
88
self._FTP_instance = ftplib.FTP(hostname, username, password)
89
self._FTP_instance.set_pasv(not self.is_active)
90
return self._FTP_instance
138
connection = ftplib.FTP()
139
connection.connect(host=self._host, port=self._port)
140
if user and user != 'anonymous' and \
141
password is None: # '' is a valid password
142
password = auth.get_password('ftp', self._host, user,
144
connection.login(user=user, passwd=password)
145
connection.set_pasv(not self.is_active)
146
except socket.error, e:
147
raise errors.SocketConnectionError(self._host, self._port,
148
msg='Unable to connect to',
91
150
except ftplib.error_perm, e:
92
raise TransportError(msg="Error setting up connection: %s"
93
% str(e), orig_error=e)
95
def should_cache(self):
96
"""Return True if the data pulled across should be cached locally.
100
def clone(self, offset=None):
101
"""Return a new FtpTransport with root at self.base + offset.
105
return FtpTransport(self.base, self._FTP_instance)
107
return FtpTransport(self.abspath(offset), self._FTP_instance)
109
def _abspath(self, relpath):
110
assert isinstance(relpath, basestring)
111
relpath = urllib.unquote(relpath)
112
if isinstance(relpath, basestring):
113
relpath_parts = relpath.split('/')
115
# TODO: Don't call this with an array - no magic interfaces
116
relpath_parts = relpath[:]
117
if len(relpath_parts) > 1:
118
if relpath_parts[0] == '':
119
raise ValueError("path %r within branch %r seems to be absolute"
120
% (relpath, self._path))
121
basepath = self._path.split('/')
122
if len(basepath) > 0 and basepath[-1] == '':
123
basepath = basepath[:-1]
124
for p in relpath_parts:
126
if len(basepath) == 0:
127
# In most filesystems, a request for the parent
128
# of root, just returns root.
131
elif p == '.' or p == '':
135
# Possibly, we could use urlparse.urljoin() here, but
136
# I'm concerned about when it chooses to strip the last
137
# portion of the path, and when it doesn't.
138
return '/'.join(basepath)
140
def abspath(self, relpath):
141
"""Return the full url to the given relative path.
142
This can be supplied with a string or a list
144
path = self._abspath(relpath)
145
return urlparse.urlunparse((self._proto,
146
self._host, path, '', '', ''))
151
raise errors.TransportError(msg="Error setting up connection:"
152
" %s" % str(e), orig_error=e)
153
return connection, (user, password)
155
def _reconnect(self):
156
"""Create a new connection with the previously used credentials"""
157
credentials = self._get_credentials()
158
connection, credentials = self._create_connection(credentials)
159
self._set_connection(connection, credentials)
161
def _translate_perm_error(self, err, path, extra=None,
162
unknown_exc=FtpPathError):
163
"""Try to translate an ftplib.error_perm exception.
165
:param err: The error to translate into a bzr error
166
:param path: The path which had problems
167
:param extra: Extra information which can be included
168
:param unknown_exc: If None, we will just raise the original exception
169
otherwise we raise unknown_exc(path, extra=extra)
175
extra += ': ' + str(err)
176
if ('no such file' in s
177
or 'could not open' in s
178
or 'no such dir' in s
179
or 'could not create file' in s # vsftpd
180
or 'file doesn\'t exist' in s
181
or 'file/directory not found' in s # filezilla server
183
raise errors.NoSuchFile(path, extra=extra)
184
if ('file exists' in s):
185
raise errors.FileExists(path, extra=extra)
186
if ('not a directory' in s):
187
raise errors.PathError(path, extra=extra)
189
mutter('unable to understand error for path: %s: %s', path, err)
192
raise unknown_exc(path, extra=extra)
193
# TODO: jam 20060516 Consider re-raising the error wrapped in
194
# something like TransportError, but this loses the traceback
195
# Also, 'sftp' has a generic 'Failure' mode, which we use failure_exc
196
# to handle. Consider doing something like that here.
197
#raise TransportError(msg='Error for path: %s' % (path,), orig_error=e)
200
def _remote_path(self, relpath):
201
# XXX: It seems that ftplib does not handle Unicode paths
202
# at the same time, medusa won't handle utf8 paths So if
203
# we .encode(utf8) here (see ConnectedTransport
204
# implementation), then we get a Server failure. while
205
# if we use str(), we get a UnicodeError, and the test
206
# suite just skips testing UnicodePaths.
207
relative = str(urlutils.unescape(relpath))
208
remote_path = self._combine_paths(self._path, relative)
148
211
def has(self, relpath):
149
"""Does the target location exist?
151
XXX: I assume we're never asked has(dirname) and thus I use
152
the FTP size command and assume that if it doesn't raise,
212
"""Does the target location exist?"""
213
# FIXME jam 20060516 We *do* ask about directories in the test suite
214
# We don't seem to in the actual codebase
215
# XXX: I assume we're never asked has(dirname) and thus I use
216
# the FTP size command and assume that if it doesn't raise,
218
abspath = self._remote_path(relpath)
156
220
f = self._get_FTP()
157
s = f.size(self._abspath(relpath))
158
mutter("FTP has: %s" % self._abspath(relpath))
221
mutter('FTP has check: %s => %s', relpath, abspath)
223
mutter("FTP has: %s", abspath)
160
except ftplib.error_perm:
161
mutter("FTP has not: %s" % self._abspath(relpath))
225
except ftplib.error_perm, e:
226
if ('is a directory' in str(e).lower()):
227
mutter("FTP has dir: %s: %s", abspath, e)
229
mutter("FTP has not: %s: %s", abspath, e)
164
def get(self, relpath, decode=False):
232
def get(self, relpath, decode=False, retries=0):
165
233
"""Get the file at the given relative path.
167
235
:param relpath: The relative path to the file
236
:param retries: Number of retries after temporary failures so far
169
239
We're meant to return a file-like object which bzr will
170
240
then read from. For now we do this via the magic of StringIO
242
# TODO: decode should be deprecated
173
mutter("FTP get: %s" % self._abspath(relpath))
244
mutter("FTP get: %s", self._remote_path(relpath))
174
245
f = self._get_FTP()
176
f.retrbinary('RETR '+self._abspath(relpath), ret.write, 8192)
247
f.retrbinary('RETR '+self._remote_path(relpath), ret.write, 8192)
179
250
except ftplib.error_perm, e:
180
raise NoSuchFile(self.abspath(relpath), extra=extra)
251
raise errors.NoSuchFile(self.abspath(relpath), extra=str(e))
252
except ftplib.error_temp, e:
253
if retries > _number_of_retries:
254
raise errors.TransportError(msg="FTP temporary error during GET %s. Aborting."
255
% self.abspath(relpath),
258
warning("FTP temporary error: %s. Retrying.", str(e))
260
return self.get(relpath, decode, retries+1)
262
if retries > _number_of_retries:
263
raise errors.TransportError("FTP control connection closed during GET %s."
264
% self.abspath(relpath),
267
warning("FTP control connection closed. Trying to reopen.")
268
time.sleep(_sleep_between_retries)
270
return self.get(relpath, decode, retries+1)
182
def put(self, relpath, fp, mode=None):
272
def put_file(self, relpath, fp, mode=None, retries=0):
183
273
"""Copy the file-like or string object into the location.
185
275
:param relpath: Location to put the contents, relative to base.
186
:param f: File-like or string object.
187
TODO: jam 20051215 This should be an atomic put, not overwritting files in place
188
TODO: jam 20051215 ftp as a protocol seems to support chmod, but ftplib does not
276
:param fp: File-like or string object.
277
:param retries: Number of retries after temporary failures so far
280
TODO: jam 20051215 ftp as a protocol seems to support chmod, but
190
if not hasattr(fp, 'read'):
283
abspath = self._remote_path(relpath)
284
tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
285
os.getpid(), random.randint(0,0x7FFFFFFF))
287
if getattr(fp, 'read', None) is None:
288
# hand in a string IO
292
# capture the byte count; .read() may be read only so
294
class byte_counter(object):
295
def __init__(self, fp):
297
self.counted_bytes = 0
298
def read(self, count):
299
result = self.fp.read(count)
300
self.counted_bytes += len(result)
302
fp = byte_counter(fp)
193
mutter("FTP put: %s" % self._abspath(relpath))
304
mutter("FTP put: %s", abspath)
194
305
f = self._get_FTP()
195
f.storbinary('STOR '+self._abspath(relpath), fp, 8192)
307
f.storbinary('STOR '+tmp_abspath, fp)
308
self._rename_and_overwrite(tmp_abspath, abspath, f)
309
if bytes is not None:
312
return fp.counted_bytes
313
except (ftplib.error_temp,EOFError), e:
314
warning("Failure during ftp PUT. Deleting temporary file.")
316
f.delete(tmp_abspath)
318
warning("Failed to delete temporary file on the"
319
" server.\nFile: %s", tmp_abspath)
196
322
except ftplib.error_perm, e:
197
raise TransportError(orig_error=e)
323
self._translate_perm_error(e, abspath, extra='could not store',
324
unknown_exc=errors.NoSuchFile)
325
except ftplib.error_temp, e:
326
if retries > _number_of_retries:
327
raise errors.TransportError("FTP temporary error during PUT %s. Aborting."
328
% self.abspath(relpath), orig_error=e)
330
warning("FTP temporary error: %s. Retrying.", str(e))
332
self.put_file(relpath, fp, mode, retries+1)
334
if retries > _number_of_retries:
335
raise errors.TransportError("FTP control connection closed during PUT %s."
336
% self.abspath(relpath), orig_error=e)
338
warning("FTP control connection closed. Trying to reopen.")
339
time.sleep(_sleep_between_retries)
341
self.put_file(relpath, fp, mode, retries+1)
199
343
def mkdir(self, relpath, mode=None):
200
344
"""Create a directory at the given path."""
202
mutter("FTP mkd: %s" % self._abspath(relpath))
205
f.mkd(self._abspath(relpath))
206
except ftplib.error_perm, e:
208
if 'File exists' in s:
209
raise FileExists(self.abspath(relpath), extra=s)
212
except ftplib.error_perm, e:
213
raise TransportError(orig_error=e)
215
def append(self, relpath, f):
345
abspath = self._remote_path(relpath)
347
mutter("FTP mkd: %s", abspath)
350
except ftplib.error_perm, e:
351
self._translate_perm_error(e, abspath,
352
unknown_exc=errors.FileExists)
354
def open_write_stream(self, relpath, mode=None):
355
"""See Transport.open_write_stream."""
356
self.put_bytes(relpath, "", mode)
357
result = AppendBasedFileStream(self, relpath)
358
_file_streams[self.abspath(relpath)] = result
361
def recommended_page_size(self):
362
"""See Transport.recommended_page_size().
364
For FTP we suggest a large page size to reduce the overhead
365
introduced by latency.
369
def rmdir(self, rel_path):
370
"""Delete the directory at rel_path"""
371
abspath = self._remote_path(rel_path)
373
mutter("FTP rmd: %s", abspath)
376
except ftplib.error_perm, e:
377
self._translate_perm_error(e, abspath, unknown_exc=errors.PathError)
379
def append_file(self, relpath, f, mode=None):
216
380
"""Append the text in the file-like object into the final
219
raise TransportNotPossible('ftp does not support append()')
221
def copy(self, rel_from, rel_to):
222
"""Copy the item at rel_from to the location at rel_to"""
223
raise TransportNotPossible('ftp does not (yet) support copy()')
383
abspath = self._remote_path(relpath)
384
if self.has(relpath):
385
ftp = self._get_FTP()
386
result = ftp.size(abspath)
390
mutter("FTP appe to %s", abspath)
391
self._try_append(relpath, f.read(), mode)
395
def _try_append(self, relpath, text, mode=None, retries=0):
396
"""Try repeatedly to append the given text to the file at relpath.
398
This is a recursive function. On errors, it will be called until the
399
number of retries is exceeded.
402
abspath = self._remote_path(relpath)
403
mutter("FTP appe (try %d) to %s", retries, abspath)
404
ftp = self._get_FTP()
405
ftp.voidcmd("TYPE I")
406
cmd = "APPE %s" % abspath
407
conn = ftp.transfercmd(cmd)
411
self._setmode(relpath, mode)
413
except ftplib.error_perm, e:
414
self._translate_perm_error(e, abspath, extra='error appending',
415
unknown_exc=errors.NoSuchFile)
416
except ftplib.error_temp, e:
417
if retries > _number_of_retries:
418
raise errors.TransportError("FTP temporary error during APPEND %s." \
419
"Aborting." % abspath, orig_error=e)
421
warning("FTP temporary error: %s. Retrying.", str(e))
423
self._try_append(relpath, text, mode, retries+1)
425
def _setmode(self, relpath, mode):
426
"""Set permissions on a path.
428
Only set permissions if the FTP server supports the 'SITE CHMOD'
432
mutter("FTP site chmod: setting permissions to %s on %s",
433
str(mode), self._remote_path(relpath))
434
ftp = self._get_FTP()
435
cmd = "SITE CHMOD %s %s" % (self._remote_path(relpath), str(mode))
437
except ftplib.error_perm, e:
438
# Command probably not available on this server
439
warning("FTP Could not set permissions to %s on %s. %s",
440
str(mode), self._remote_path(relpath), str(e))
442
# TODO: jam 20060516 I believe ftp allows you to tell an ftp server
443
# to copy something to another machine. And you may be able
444
# to give it its own address as the 'to' location.
445
# So implement a fancier 'copy()'
447
def rename(self, rel_from, rel_to):
448
abs_from = self._remote_path(rel_from)
449
abs_to = self._remote_path(rel_to)
450
mutter("FTP rename: %s => %s", abs_from, abs_to)
452
return self._rename(abs_from, abs_to, f)
454
def _rename(self, abs_from, abs_to, f):
456
f.rename(abs_from, abs_to)
457
except ftplib.error_perm, e:
458
self._translate_perm_error(e, abs_from,
459
': unable to rename to %r' % (abs_to))
225
461
def move(self, rel_from, rel_to):
226
462
"""Move the item at rel_from to the location at rel_to"""
463
abs_from = self._remote_path(rel_from)
464
abs_to = self._remote_path(rel_to)
228
mutter("FTP mv: %s => %s" % (self._abspath(rel_from),
229
self._abspath(rel_to)))
466
mutter("FTP mv: %s => %s", abs_from, abs_to)
230
467
f = self._get_FTP()
231
f.rename(self._abspath(rel_from), self._abspath(rel_to))
468
self._rename_and_overwrite(abs_from, abs_to, f)
232
469
except ftplib.error_perm, e:
233
raise TransportError(orig_error=e)
470
self._translate_perm_error(e, abs_from,
471
extra='unable to rename to %r' % (rel_to,),
472
unknown_exc=errors.PathError)
474
def _rename_and_overwrite(self, abs_from, abs_to, f):
475
"""Do a fancy rename on the remote server.
477
Using the implementation provided by osutils.
479
osutils.fancy_rename(abs_from, abs_to,
480
rename_func=lambda p1, p2: self._rename(p1, p2, f),
481
unlink_func=lambda p: self._delete(p, f))
235
483
def delete(self, relpath):
236
484
"""Delete the item at relpath"""
485
abspath = self._remote_path(relpath)
487
self._delete(abspath, f)
489
def _delete(self, abspath, f):
238
mutter("FTP rm: %s" % self._abspath(relpath))
240
f.delete(self._abspath(relpath))
491
mutter("FTP rm: %s", abspath)
241
493
except ftplib.error_perm, e:
242
raise TransportError(orig_error=e)
494
self._translate_perm_error(e, abspath, 'error deleting',
495
unknown_exc=errors.NoSuchFile)
497
def external_url(self):
498
"""See bzrlib.transport.Transport.external_url."""
499
# FTP URL's are externally usable.
244
502
def listable(self):
245
503
"""See Transport.listable."""