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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
16
"""Implementation of Transport over ftp.
19
18
Written by Daniel Silverstone <dsilvers@digital-scurf.org> with serious
119
114
:return: The created connection and its associated credentials.
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.
116
The credentials are only the password as it may have been entered
117
interactively by the user and may be different from the one provided
118
in base url at transport creation time.
126
120
if credentials is None:
127
121
user, password = self._user, self._password
131
125
auth = config.AuthenticationConfig()
133
user = auth.get_user('ftp', self._host, port=self._port,
134
default=getpass.getuser())
127
user = auth.get_user('ftp', self._host, port=self._port)
129
# Default to local user
130
user = getpass.getuser()
135
132
mutter("Constructing FTP instance against %r" %
136
133
((self._host, self._port, user, '********',
137
134
self.is_active),))
139
connection = self.connection_class()
136
connection = ftplib.FTP()
140
137
connection.connect(host=self._host, port=self._port)
141
self._login(connection, auth, user, password)
138
if user and user != 'anonymous' and \
139
password is None: # '' is a valid password
140
password = auth.get_password('ftp', self._host, user,
142
connection.login(user=user, passwd=password)
142
143
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',
149
144
except ftplib.error_perm, e:
150
145
raise errors.TransportError(msg="Error setting up connection:"
151
146
" %s" % str(e), orig_error=e)
152
147
return connection, (user, password)
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)
161
149
def _reconnect(self):
162
150
"""Create a new connection with the previously used credentials"""
163
151
credentials = self._get_credentials()
164
152
connection, credentials = self._create_connection(credentials)
165
153
self._set_connection(connection, credentials)
167
def _translate_ftp_error(self, err, path, extra=None,
155
def _translate_perm_error(self, err, path, extra=None,
168
156
unknown_exc=FtpPathError):
169
"""Try to translate an ftplib exception to a bzrlib exception.
157
"""Try to translate an ftplib.error_perm exception.
171
159
:param err: The error to translate into a bzr error
172
160
:param path: The path which had problems
187
172
or 'no such dir' in s
188
173
or 'could not create file' in s # vsftpd
189
174
or 'file doesn\'t exist' in s
190
or 'rnfr command failed.' in s # vsftpd RNFR reply if file not found
191
175
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)
195
177
raise errors.NoSuchFile(path, extra=extra)
196
elif ('file exists' in s):
178
if ('file exists' in s):
197
179
raise errors.FileExists(path, extra=extra)
198
elif ('not a directory' in s):
180
if ('not a directory' in s):
199
181
raise errors.PathError(path, extra=extra)
200
elif 'directory not empty' in s:
201
raise errors.DirectoryNotEmpty(path, extra=extra)
203
183
mutter('unable to understand error for path: %s: %s', path, err)
206
186
raise unknown_exc(path, extra=extra)
207
# TODO: jam 20060516 Consider re-raising the error wrapped in
187
# TODO: jam 20060516 Consider re-raising the error wrapped in
208
188
# something like TransportError, but this loses the traceback
209
189
# Also, 'sftp' has a generic 'Failure' mode, which we use failure_exc
210
190
# to handle. Consider doing something like that here.
211
191
#raise TransportError(msg='Error for path: %s' % (path,), orig_error=e)
194
def _remote_path(self, relpath):
195
# XXX: It seems that ftplib does not handle Unicode paths
196
# at the same time, medusa won't handle utf8 paths So if
197
# we .encode(utf8) here (see ConnectedTransport
198
# implementation), then we get a Server failure. while
199
# if we use str(), we get a UnicodeError, and the test
200
# suite just skips testing UnicodePaths.
201
relative = str(urlutils.unescape(relpath))
202
remote_path = self._combine_paths(self._path, relative)
214
205
def has(self, relpath):
215
206
"""Does the target location exist?"""
216
207
# FIXME jam 20060516 We *do* ask about directories in the test suite
351
341
mutter("FTP mkd: %s", abspath)
352
342
f = self._get_FTP()
354
self._setmode(relpath, mode)
355
344
except ftplib.error_perm, e:
356
self._translate_ftp_error(e, abspath,
345
self._translate_perm_error(e, abspath,
357
346
unknown_exc=errors.FileExists)
359
348
def open_write_stream(self, relpath, mode=None):
397
mutter("FTP appe to %s", abspath)
398
self._try_append(relpath, text, mode)
400
self._fallback_append(relpath, text, mode)
384
mutter("FTP appe to %s", abspath)
385
self._try_append(relpath, f.read(), mode)
404
389
def _try_append(self, relpath, text, mode=None, retries=0):
405
390
"""Try repeatedly to append the given text to the file at relpath.
407
392
This is a recursive function. On errors, it will be called until the
408
393
number of retries is exceeded.
411
396
abspath = self._remote_path(relpath)
412
397
mutter("FTP appe (try %d) to %s", retries, abspath)
413
398
ftp = self._get_FTP()
399
ftp.voidcmd("TYPE I")
414
400
cmd = "APPE %s" % abspath
415
401
conn = ftp.transfercmd(cmd)
416
402
conn.sendall(text)
418
self._setmode(relpath, mode)
405
self._setmode(relpath, mode)
420
407
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)
428
self._translate_ftp_error(e, abspath, extra='error appending',
429
unknown_exc=errors.NoSuchFile)
408
self._translate_perm_error(e, abspath, extra='error appending',
409
unknown_exc=errors.NoSuchFile)
430
410
except ftplib.error_temp, e:
431
411
if retries > _number_of_retries:
432
raise errors.TransportError(
433
"FTP temporary error during APPEND %s. Aborting."
434
% abspath, orig_error=e)
412
raise errors.TransportError("FTP temporary error during APPEND %s." \
413
"Aborting." % abspath, orig_error=e)
436
415
warning("FTP temporary error: %s. Retrying.", str(e))
437
416
self._reconnect()
438
417
self._try_append(relpath, text, mode, retries+1)
440
def _fallback_append(self, relpath, text, mode = None):
441
remote = self.get(relpath)
442
remote.seek(0, os.SEEK_END)
445
return self.put_file(relpath, remote, mode)
447
419
def _setmode(self, relpath, mode):
448
420
"""Set permissions on a path.
450
422
Only set permissions if the FTP server supports the 'SITE CHMOD'
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))
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))
426
mutter("FTP site chmod: setting permissions to %s on %s",
427
str(mode), self._remote_path(relpath))
428
ftp = self._get_FTP()
429
cmd = "SITE CHMOD %s %s" % (self._remote_path(relpath), str(mode))
431
except ftplib.error_perm, e:
432
# Command probably not available on this server
433
warning("FTP Could not set permissions to %s on %s. %s",
434
str(mode), self._remote_path(relpath), str(e))
466
436
# TODO: jam 20060516 I believe ftp allows you to tell an ftp server
467
437
# to copy something to another machine. And you may be able
478
448
def _rename(self, abs_from, abs_to, f):
480
450
f.rename(abs_from, abs_to)
481
except (ftplib.error_temp, ftplib.error_perm), e:
482
self._translate_ftp_error(e, abs_from,
451
except ftplib.error_perm, e:
452
self._translate_perm_error(e, abs_from,
483
453
': unable to rename to %r' % (abs_to))
485
455
def move(self, rel_from, rel_to):
491
461
f = self._get_FTP()
492
462
self._rename_and_overwrite(abs_from, abs_to, f)
493
463
except ftplib.error_perm, e:
494
self._translate_ftp_error(e, abs_from,
495
extra='unable to rename to %r' % (rel_to,),
464
self._translate_perm_error(e, abs_from,
465
extra='unable to rename to %r' % (rel_to,),
496
466
unknown_exc=errors.PathError)
498
468
def _rename_and_overwrite(self, abs_from, abs_to, f):
533
503
mutter("FTP nlst: %s", basepath)
534
504
f = self._get_FTP()
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',
552
# Restore binary mode as nlst switch to ascii mode to retrieve file
506
paths = f.nlst(basepath)
507
except ftplib.error_perm, e:
508
self._translate_perm_error(e, relpath, extra='error with list_dir')
556
509
# If FTP.nlst returns paths prefixed by relpath, strip 'em
557
510
if paths and paths[0].startswith(basepath):
558
511
entries = [path[len(basepath)+1:] for path in paths]
612
565
def get_test_permutations():
613
566
"""Return the permutations to be used in testing."""
614
from bzrlib.tests import ftp_server
615
return [(FtpTransport, ftp_server.FTPTestServer)]
567
from bzrlib import tests
568
if tests.FTPServerFeature.available():
569
from bzrlib.tests import ftp_server
570
return [(FtpTransport, ftp_server.FTPServer)]
572
# Dummy server to have the test suite report the number of tests
573
# needing that feature.
574
class UnavailableFTPServer(object):
576
raise tests.UnavailableFeature(tests.FTPServerFeature)
578
return [(FtpTransport, UnavailableFTPServer)]