~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/transport/ftp.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-08-09 15:19:06 UTC
  • mfrom: (2681.1.7 send-bundle)
  • Revision ID: pqm@pqm.ubuntu.com-20070809151906-hdn9oyslf2qib2op
Allow omitting -o for bundle, add --format

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
"""Implementation of Transport over ftp.
17
17
 
18
18
Written by Daniel Silverstone <dsilvers@digital-scurf.org> with serious
25
25
"""
26
26
 
27
27
from cStringIO import StringIO
 
28
import asyncore
28
29
import errno
29
30
import ftplib
30
 
import getpass
31
31
import os
32
32
import os.path
 
33
import urllib
33
34
import urlparse
34
 
import random
35
 
import socket
 
35
import select
36
36
import stat
 
37
import threading
37
38
import time
 
39
import random
38
40
from warnings import warn
39
41
 
40
42
from bzrlib import (
41
 
    config,
42
43
    errors,
43
44
    osutils,
44
45
    urlutils,
45
46
    )
46
47
from bzrlib.trace import mutter, warning
47
48
from bzrlib.transport import (
48
 
    AppendBasedFileStream,
 
49
    Server,
49
50
    ConnectedTransport,
50
 
    _file_streams,
51
 
    register_urlparse_netloc_protocol,
52
 
    Server,
53
51
    )
54
52
from bzrlib.transport.local import LocalURLServer
55
53
import bzrlib.ui
56
54
 
57
 
 
58
 
register_urlparse_netloc_protocol('aftp')
 
55
_have_medusa = False
59
56
 
60
57
 
61
58
class FtpPathError(errors.PathError):
63
60
 
64
61
 
65
62
class FtpStatResult(object):
66
 
 
67
 
    def __init__(self, f, abspath):
 
63
    def __init__(self, f, relpath):
68
64
        try:
69
 
            self.st_size = f.size(abspath)
 
65
            self.st_size = f.size(relpath)
70
66
            self.st_mode = stat.S_IFREG
71
67
        except ftplib.error_perm:
72
68
            pwd = f.pwd()
73
69
            try:
74
 
                f.cwd(abspath)
 
70
                f.cwd(relpath)
75
71
                self.st_mode = stat.S_IFDIR
76
72
            finally:
77
73
                f.cwd(pwd)
90
86
 
91
87
    def __init__(self, base, _from_transport=None):
92
88
        """Set the base path where files will be stored."""
93
 
        if not (base.startswith('ftp://') or base.startswith('aftp://')):
94
 
            raise ValueError(base)
 
89
        assert base.startswith('ftp://') or base.startswith('aftp://')
95
90
        super(FtpTransport, self).__init__(base,
96
91
                                           _from_transport=_from_transport)
97
92
        self._unqualified_scheme = 'ftp'
117
112
 
118
113
        :return: The created connection and its associated credentials.
119
114
 
120
 
        The input credentials are only the password as it may have been
121
 
        entered interactively by the user and may be different from the one
122
 
        provided in base url at transport creation time.  The returned
123
 
        credentials are username, password.
 
115
        The credentials are only the password as it may have been entered
 
116
        interactively by the user and may be different from the one provided
 
117
        in base url at transport creation time.
124
118
        """
125
119
        if credentials is None:
126
 
            user, password = self._user, self._password
 
120
            password = self._password
127
121
        else:
128
 
            user, password = credentials
129
 
 
130
 
        auth = config.AuthenticationConfig()
131
 
        if user is None:
132
 
            user = auth.get_user('ftp', self._host, port=self._port)
133
 
            if user is None:
134
 
                # Default to local user
135
 
                user = getpass.getuser()
 
122
            password = credentials
136
123
 
137
124
        mutter("Constructing FTP instance against %r" %
138
 
               ((self._host, self._port, user, '********',
 
125
               ((self._host, self._port, self._user, '********',
139
126
                self.is_active),))
140
127
        try:
141
128
            connection = ftplib.FTP()
142
129
            connection.connect(host=self._host, port=self._port)
143
 
            if user and user != 'anonymous' and \
144
 
                    password is None: # '' is a valid password
145
 
                password = auth.get_password('ftp', self._host, user,
146
 
                                             port=self._port)
147
 
            connection.login(user=user, passwd=password)
 
130
            if self._user and self._user != 'anonymous' and \
 
131
                    password is not None: # '' is a valid password
 
132
                get_password = bzrlib.ui.ui_factory.get_password
 
133
                password = get_password(prompt='FTP %(user)s@%(host)s password',
 
134
                                        user=self._user, host=self._host)
 
135
            connection.login(user=self._user, passwd=password)
148
136
            connection.set_pasv(not self.is_active)
149
 
            # binary mode is the default
150
 
            connection.voidcmd('TYPE I')
151
 
        except socket.error, e:
152
 
            raise errors.SocketConnectionError(self._host, self._port,
153
 
                                               msg='Unable to connect to',
154
 
                                               orig_error= e)
155
137
        except ftplib.error_perm, e:
156
138
            raise errors.TransportError(msg="Error setting up connection:"
157
139
                                        " %s" % str(e), orig_error=e)
158
 
        return connection, (user, password)
 
140
        return connection, password
159
141
 
160
142
    def _reconnect(self):
161
143
        """Create a new connection with the previously used credentials"""
162
 
        credentials = self._get_credentials()
 
144
        credentials = self.get_credentials()
163
145
        connection, credentials = self._create_connection(credentials)
164
146
        self._set_connection(connection, credentials)
165
147
 
183
165
            or 'no such dir' in s
184
166
            or 'could not create file' in s # vsftpd
185
167
            or 'file doesn\'t exist' in s
186
 
            or 'rnfr command failed.' in s # vsftpd RNFR reply if file not found
187
 
            or 'file/directory not found' in s # filezilla server
188
 
            # Microsoft FTP-Service RNFR reply if file not found
189
 
            or (s.startswith('550 ') and 'unable to rename to' in extra)
190
168
            ):
191
169
            raise errors.NoSuchFile(path, extra=extra)
192
170
        if ('file exists' in s):
198
176
 
199
177
        if unknown_exc:
200
178
            raise unknown_exc(path, extra=extra)
201
 
        # TODO: jam 20060516 Consider re-raising the error wrapped in
 
179
        # TODO: jam 20060516 Consider re-raising the error wrapped in 
202
180
        #       something like TransportError, but this loses the traceback
203
181
        #       Also, 'sftp' has a generic 'Failure' mode, which we use failure_exc
204
182
        #       to handle. Consider doing something like that here.
205
183
        #raise TransportError(msg='Error for path: %s' % (path,), orig_error=e)
206
184
        raise
207
185
 
 
186
    def should_cache(self):
 
187
        """Return True if the data pulled across should be cached locally.
 
188
        """
 
189
        return True
 
190
 
208
191
    def _remote_path(self, relpath):
209
192
        # XXX: It seems that ftplib does not handle Unicode paths
210
193
        # at the same time, medusa won't handle utf8 paths So if
291
274
        abspath = self._remote_path(relpath)
292
275
        tmp_abspath = '%s.tmp.%.9f.%d.%d' % (abspath, time.time(),
293
276
                        os.getpid(), random.randint(0,0x7FFFFFFF))
294
 
        bytes = None
295
277
        if getattr(fp, 'read', None) is None:
296
 
            # hand in a string IO
297
 
            bytes = fp
298
 
            fp = StringIO(bytes)
299
 
        else:
300
 
            # capture the byte count; .read() may be read only so
301
 
            # decorate it.
302
 
            class byte_counter(object):
303
 
                def __init__(self, fp):
304
 
                    self.fp = fp
305
 
                    self.counted_bytes = 0
306
 
                def read(self, count):
307
 
                    result = self.fp.read(count)
308
 
                    self.counted_bytes += len(result)
309
 
                    return result
310
 
            fp = byte_counter(fp)
 
278
            fp = StringIO(fp)
311
279
        try:
312
280
            mutter("FTP put: %s", abspath)
313
281
            f = self._get_FTP()
314
282
            try:
315
283
                f.storbinary('STOR '+tmp_abspath, fp)
316
284
                self._rename_and_overwrite(tmp_abspath, abspath, f)
317
 
                self._setmode(relpath, mode)
318
 
                if bytes is not None:
319
 
                    return len(bytes)
320
 
                else:
321
 
                    return fp.counted_bytes
322
285
            except (ftplib.error_temp,EOFError), e:
323
286
                warning("Failure during ftp PUT. Deleting temporary file.")
324
287
                try:
356
319
            mutter("FTP mkd: %s", abspath)
357
320
            f = self._get_FTP()
358
321
            f.mkd(abspath)
359
 
            self._setmode(relpath, mode)
360
322
        except ftplib.error_perm, e:
361
323
            self._translate_perm_error(e, abspath,
362
324
                unknown_exc=errors.FileExists)
363
325
 
364
 
    def open_write_stream(self, relpath, mode=None):
365
 
        """See Transport.open_write_stream."""
366
 
        self.put_bytes(relpath, "", mode)
367
 
        result = AppendBasedFileStream(self, relpath)
368
 
        _file_streams[self.abspath(relpath)] = result
369
 
        return result
370
 
 
371
 
    def recommended_page_size(self):
372
 
        """See Transport.recommended_page_size().
373
 
 
374
 
        For FTP we suggest a large page size to reduce the overhead
375
 
        introduced by latency.
376
 
        """
377
 
        return 64 * 1024
378
 
 
379
326
    def rmdir(self, rel_path):
380
327
        """Delete the directory at rel_path"""
381
328
        abspath = self._remote_path(rel_path)
404
351
 
405
352
    def _try_append(self, relpath, text, mode=None, retries=0):
406
353
        """Try repeatedly to append the given text to the file at relpath.
407
 
 
 
354
        
408
355
        This is a recursive function. On errors, it will be called until the
409
356
        number of retries is exceeded.
410
357
        """
412
359
            abspath = self._remote_path(relpath)
413
360
            mutter("FTP appe (try %d) to %s", retries, abspath)
414
361
            ftp = self._get_FTP()
 
362
            ftp.voidcmd("TYPE I")
415
363
            cmd = "APPE %s" % abspath
416
364
            conn = ftp.transfercmd(cmd)
417
365
            conn.sendall(text)
418
366
            conn.close()
419
 
            self._setmode(relpath, mode)
 
367
            if mode:
 
368
                self._setmode(relpath, mode)
420
369
            ftp.getresp()
421
370
        except ftplib.error_perm, e:
422
371
            self._translate_perm_error(e, abspath, extra='error appending',
436
385
        Only set permissions if the FTP server supports the 'SITE CHMOD'
437
386
        extension.
438
387
        """
439
 
        if mode:
440
 
            try:
441
 
                mutter("FTP site chmod: setting permissions to %s on %s",
442
 
                       oct(mode), self._remote_path(relpath))
443
 
                ftp = self._get_FTP()
444
 
                cmd = "SITE CHMOD %s %s" % (oct(mode),
445
 
                                            self._remote_path(relpath))
446
 
                ftp.sendcmd(cmd)
447
 
            except ftplib.error_perm, e:
448
 
                # Command probably not available on this server
449
 
                warning("FTP Could not set permissions to %s on %s. %s",
450
 
                        oct(mode), self._remote_path(relpath), str(e))
 
388
        try:
 
389
            mutter("FTP site chmod: setting permissions to %s on %s",
 
390
                str(mode), self._remote_path(relpath))
 
391
            ftp = self._get_FTP()
 
392
            cmd = "SITE CHMOD %s %s" % (self._remote_path(relpath), str(mode))
 
393
            ftp.sendcmd(cmd)
 
394
        except ftplib.error_perm, e:
 
395
            # Command probably not available on this server
 
396
            warning("FTP Could not set permissions to %s on %s. %s",
 
397
                    str(mode), self._remote_path(relpath), str(e))
451
398
 
452
399
    # TODO: jam 20060516 I believe ftp allows you to tell an ftp server
453
400
    #       to copy something to another machine. And you may be able
478
425
            self._rename_and_overwrite(abs_from, abs_to, f)
479
426
        except ftplib.error_perm, e:
480
427
            self._translate_perm_error(e, abs_from,
481
 
                extra='unable to rename to %r' % (rel_to,),
 
428
                extra='unable to rename to %r' % (rel_to,), 
482
429
                unknown_exc=errors.PathError)
483
430
 
484
431
    def _rename_and_overwrite(self, abs_from, abs_to, f):
519
466
        mutter("FTP nlst: %s", basepath)
520
467
        f = self._get_FTP()
521
468
        try:
522
 
            try:
523
 
                paths = f.nlst(basepath)
524
 
            except ftplib.error_perm, e:
525
 
                self._translate_perm_error(e, relpath,
526
 
                                           extra='error with list_dir')
527
 
            except ftplib.error_temp, e:
528
 
                # xs4all's ftp server raises a 450 temp error when listing an
529
 
                # empty directory. Check for that and just return an empty list
530
 
                # in that case. See bug #215522
531
 
                if str(e).lower().startswith('450 no files found'):
532
 
                    mutter('FTP Server returned "%s" for nlst.'
533
 
                           ' Assuming it means empty directory',
534
 
                           str(e))
535
 
                    return []
536
 
                raise
537
 
        finally:
538
 
            # Restore binary mode as nlst switch to ascii mode to retrieve file
539
 
            # list
540
 
            f.voidcmd('TYPE I')
541
 
 
 
469
            paths = f.nlst(basepath)
 
470
        except ftplib.error_perm, e:
 
471
            self._translate_perm_error(e, relpath, extra='error with list_dir')
542
472
        # If FTP.nlst returns paths prefixed by relpath, strip 'em
543
473
        if paths and paths[0].startswith(basepath):
544
474
            entries = [path[len(basepath)+1:] for path in paths]
595
525
        return self.lock_read(relpath)
596
526
 
597
527
 
 
528
class FtpServer(Server):
 
529
    """Common code for FTP server facilities."""
 
530
 
 
531
    def __init__(self):
 
532
        self._root = None
 
533
        self._ftp_server = None
 
534
        self._port = None
 
535
        self._async_thread = None
 
536
        # ftp server logs
 
537
        self.logs = []
 
538
 
 
539
    def get_url(self):
 
540
        """Calculate an ftp url to this server."""
 
541
        return 'ftp://foo:bar@localhost:%d/' % (self._port)
 
542
 
 
543
#    def get_bogus_url(self):
 
544
#        """Return a URL which cannot be connected to."""
 
545
#        return 'ftp://127.0.0.1:1'
 
546
 
 
547
    def log(self, message):
 
548
        """This is used by medusa.ftp_server to log connections, etc."""
 
549
        self.logs.append(message)
 
550
 
 
551
    def setUp(self, vfs_server=None):
 
552
        if not _have_medusa:
 
553
            raise RuntimeError('Must have medusa to run the FtpServer')
 
554
 
 
555
        assert vfs_server is None or isinstance(vfs_server, LocalURLServer), \
 
556
            "FtpServer currently assumes local transport, got %s" % vfs_server
 
557
 
 
558
        self._root = os.getcwdu()
 
559
        self._ftp_server = _ftp_server(
 
560
            authorizer=_test_authorizer(root=self._root),
 
561
            ip='localhost',
 
562
            port=0, # bind to a random port
 
563
            resolver=None,
 
564
            logger_object=self # Use FtpServer.log() for messages
 
565
            )
 
566
        self._port = self._ftp_server.getsockname()[1]
 
567
        # Don't let it loop forever, or handle an infinite number of requests.
 
568
        # In this case it will run for 1000s, or 10000 requests
 
569
        self._async_thread = threading.Thread(
 
570
                target=FtpServer._asyncore_loop_ignore_EBADF,
 
571
                kwargs={'timeout':0.1, 'count':10000})
 
572
        self._async_thread.setDaemon(True)
 
573
        self._async_thread.start()
 
574
 
 
575
    def tearDown(self):
 
576
        """See bzrlib.transport.Server.tearDown."""
 
577
        # have asyncore release the channel
 
578
        self._ftp_server.del_channel()
 
579
        asyncore.close_all()
 
580
        self._async_thread.join()
 
581
 
 
582
    @staticmethod
 
583
    def _asyncore_loop_ignore_EBADF(*args, **kwargs):
 
584
        """Ignore EBADF during server shutdown.
 
585
 
 
586
        We close the socket to get the server to shutdown, but this causes
 
587
        select.select() to raise EBADF.
 
588
        """
 
589
        try:
 
590
            asyncore.loop(*args, **kwargs)
 
591
            # FIXME: If we reach that point, we should raise an exception
 
592
            # explaining that the 'count' parameter in setUp is too low or
 
593
            # testers may wonder why their test just sits there waiting for a
 
594
            # server that is already dead. Note that if the tester waits too
 
595
            # long under pdb the server will also die.
 
596
        except select.error, e:
 
597
            if e.args[0] != errno.EBADF:
 
598
                raise
 
599
 
 
600
 
 
601
_ftp_channel = None
 
602
_ftp_server = None
 
603
_test_authorizer = None
 
604
 
 
605
 
 
606
def _setup_medusa():
 
607
    global _have_medusa, _ftp_channel, _ftp_server, _test_authorizer
 
608
    try:
 
609
        import medusa
 
610
        import medusa.filesys
 
611
        import medusa.ftp_server
 
612
    except ImportError:
 
613
        return False
 
614
 
 
615
    _have_medusa = True
 
616
 
 
617
    class test_authorizer(object):
 
618
        """A custom Authorizer object for running the test suite.
 
619
 
 
620
        The reason we cannot use dummy_authorizer, is because it sets the
 
621
        channel to readonly, which we don't always want to do.
 
622
        """
 
623
 
 
624
        def __init__(self, root):
 
625
            self.root = root
 
626
 
 
627
        def authorize(self, channel, username, password):
 
628
            """Return (success, reply_string, filesystem)"""
 
629
            if not _have_medusa:
 
630
                return 0, 'No Medusa.', None
 
631
 
 
632
            channel.persona = -1, -1
 
633
            if username == 'anonymous':
 
634
                channel.read_only = 1
 
635
            else:
 
636
                channel.read_only = 0
 
637
 
 
638
            return 1, 'OK.', medusa.filesys.os_filesystem(self.root)
 
639
 
 
640
 
 
641
    class ftp_channel(medusa.ftp_server.ftp_channel):
 
642
        """Customized ftp channel"""
 
643
 
 
644
        def log(self, message):
 
645
            """Redirect logging requests."""
 
646
            mutter('_ftp_channel: %s', message)
 
647
 
 
648
        def log_info(self, message, type='info'):
 
649
            """Redirect logging requests."""
 
650
            mutter('_ftp_channel %s: %s', type, message)
 
651
 
 
652
        def cmd_rnfr(self, line):
 
653
            """Prepare for renaming a file."""
 
654
            self._renaming = line[1]
 
655
            self.respond('350 Ready for RNTO')
 
656
            # TODO: jam 20060516 in testing, the ftp server seems to
 
657
            #       check that the file already exists, or it sends
 
658
            #       550 RNFR command failed
 
659
 
 
660
        def cmd_rnto(self, line):
 
661
            """Rename a file based on the target given.
 
662
 
 
663
            rnto must be called after calling rnfr.
 
664
            """
 
665
            if not self._renaming:
 
666
                self.respond('503 RNFR required first.')
 
667
            pfrom = self.filesystem.translate(self._renaming)
 
668
            self._renaming = None
 
669
            pto = self.filesystem.translate(line[1])
 
670
            if os.path.exists(pto):
 
671
                self.respond('550 RNTO failed: file exists')
 
672
                return
 
673
            try:
 
674
                os.rename(pfrom, pto)
 
675
            except (IOError, OSError), e:
 
676
                # TODO: jam 20060516 return custom responses based on
 
677
                #       why the command failed
 
678
                # (bialix 20070418) str(e) on Python 2.5 @ Windows
 
679
                # sometimes don't provide expected error message;
 
680
                # so we obtain such message via os.strerror()
 
681
                self.respond('550 RNTO failed: %s' % os.strerror(e.errno))
 
682
            except:
 
683
                self.respond('550 RNTO failed')
 
684
                # For a test server, we will go ahead and just die
 
685
                raise
 
686
            else:
 
687
                self.respond('250 Rename successful.')
 
688
 
 
689
        def cmd_size(self, line):
 
690
            """Return the size of a file
 
691
 
 
692
            This is overloaded to help the test suite determine if the 
 
693
            target is a directory.
 
694
            """
 
695
            filename = line[1]
 
696
            if not self.filesystem.isfile(filename):
 
697
                if self.filesystem.isdir(filename):
 
698
                    self.respond('550 "%s" is a directory' % (filename,))
 
699
                else:
 
700
                    self.respond('550 "%s" is not a file' % (filename,))
 
701
            else:
 
702
                self.respond('213 %d' 
 
703
                    % (self.filesystem.stat(filename)[stat.ST_SIZE]),)
 
704
 
 
705
        def cmd_mkd(self, line):
 
706
            """Create a directory.
 
707
 
 
708
            Overloaded because default implementation does not distinguish
 
709
            *why* it cannot make a directory.
 
710
            """
 
711
            if len (line) != 2:
 
712
                self.command_not_understood(''.join(line))
 
713
            else:
 
714
                path = line[1]
 
715
                try:
 
716
                    self.filesystem.mkdir (path)
 
717
                    self.respond ('257 MKD command successful.')
 
718
                except (IOError, OSError), e:
 
719
                    # (bialix 20070418) str(e) on Python 2.5 @ Windows
 
720
                    # sometimes don't provide expected error message;
 
721
                    # so we obtain such message via os.strerror()
 
722
                    self.respond ('550 error creating directory: %s' %
 
723
                                  os.strerror(e.errno))
 
724
                except:
 
725
                    self.respond ('550 error creating directory.')
 
726
 
 
727
 
 
728
    class ftp_server(medusa.ftp_server.ftp_server):
 
729
        """Customize the behavior of the Medusa ftp_server.
 
730
 
 
731
        There are a few warts on the ftp_server, based on how it expects
 
732
        to be used.
 
733
        """
 
734
        _renaming = None
 
735
        ftp_channel_class = ftp_channel
 
736
 
 
737
        def __init__(self, *args, **kwargs):
 
738
            mutter('Initializing _ftp_server: %r, %r', args, kwargs)
 
739
            medusa.ftp_server.ftp_server.__init__(self, *args, **kwargs)
 
740
 
 
741
        def log(self, message):
 
742
            """Redirect logging requests."""
 
743
            mutter('_ftp_server: %s', message)
 
744
 
 
745
        def log_info(self, message, type='info'):
 
746
            """Override the asyncore.log_info so we don't stipple the screen."""
 
747
            mutter('_ftp_server %s: %s', type, message)
 
748
 
 
749
    _test_authorizer = test_authorizer
 
750
    _ftp_channel = ftp_channel
 
751
    _ftp_server = ftp_server
 
752
 
 
753
    return True
 
754
 
 
755
 
598
756
def get_test_permutations():
599
757
    """Return the permutations to be used in testing."""
600
 
    from bzrlib.tests import ftp_server
601
 
    return [(FtpTransport, ftp_server.FTPTestServer)]
 
758
    if not _setup_medusa():
 
759
        warn("You must install medusa (http://www.amk.ca/python/code/medusa.html) for FTP tests")
 
760
        return []
 
761
    else:
 
762
        return [(FtpTransport, FtpServer)]