/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4763.2.4 by John Arbash Meinel
merge bzr.2.1 in preparation for NEWS entry.
1
# Copyright (C) 2005-2010 Canonical Ltd
1540.3.18 by Martin Pool
Style review fixes (thanks robertc)
2
#
1185.11.19 by John Arbash Meinel
Testing put and append, also testing agaist file-like objects as well as strings.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1540.3.18 by Martin Pool
Style review fixes (thanks robertc)
7
#
1185.11.19 by John Arbash Meinel
Testing put and append, also testing agaist file-like objects as well as strings.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
1540.3.18 by Martin Pool
Style review fixes (thanks robertc)
12
#
1185.11.19 by John Arbash Meinel
Testing put and append, also testing agaist file-like objects as well as strings.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1540.3.3 by Martin Pool
Review updates of pycurl transport
16
17
"""Base implementation of Transport over http.
18
19
There are separate implementation modules for each http client implementation.
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
20
"""
21
6379.6.7 by Jelmer Vernooij
Move importing from future until after doc string, otherwise the doc string will disappear.
22
from __future__ import absolute_import
23
6450.2.1 by Vincent Ladeuil
Avoid invalid range access errors on whole files when using http transport
24
import os
1540.3.23 by Martin Pool
Allow urls like http+pycurl://host/ to use a particular impl
25
import re
1540.3.3 by Martin Pool
Review updates of pycurl transport
26
import urlparse
2172.3.2 by v.ladeuil+lp at free
Fix the missing import and typos in comments.
27
import sys
3734.2.3 by Vincent Ladeuil
Don't use multiple inheritance for http smart medium since we
28
import weakref
1786.1.6 by John Arbash Meinel
Missed a couple of imports
29
2485.8.24 by Vincent Ladeuil
Finish http refactoring. Test suite passing.
30
from bzrlib import (
3675.1.1 by Martin Pool
Merge and update log+ transport decorator
31
    debug,
2485.8.24 by Vincent Ladeuil
Finish http refactoring. Test suite passing.
32
    errors,
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
33
    transport,
2485.8.24 by Vincent Ladeuil
Finish http refactoring. Test suite passing.
34
    ui,
35
    urlutils,
36
    )
2400.1.3 by Andrew Bennetts
Split smart transport code into several separate modules.
37
from bzrlib.smart import medium
1185.11.1 by John Arbash Meinel
(broken) Transport work is merged in. Tests do not pass yet.
38
from bzrlib.trace import mutter
2018.2.2 by Andrew Bennetts
Implement HTTP smart server.
39
from bzrlib.transport import (
2485.8.16 by Vincent Ladeuil
Create a new, empty, ConnectedTransport class.
40
    ConnectedTransport,
2018.2.2 by Andrew Bennetts
Implement HTTP smart server.
41
    )
1540.3.6 by Martin Pool
[merge] update from bzr.dev
42
1185.50.83 by John Arbash Meinel
[merge] James Henstridge: Set Agent string in http headers, add tests for it.
43
3734.2.3 by Vincent Ladeuil
Don't use multiple inheritance for http smart medium since we
44
class HttpTransportBase(ConnectedTransport):
1540.3.1 by Martin Pool
First-cut implementation of pycurl. Substantially faster than using urllib.
45
    """Base class for http implementations.
46
1540.3.23 by Martin Pool
Allow urls like http+pycurl://host/ to use a particular impl
47
    Does URL parsing, etc, but not any network IO.
48
49
    The protocol can be given as e.g. http+urllib://host/ to use a particular
50
    implementation.
51
    """
52
2485.8.24 by Vincent Ladeuil
Finish http refactoring. Test suite passing.
53
    # _unqualified_scheme: "http" or "https"
54
    # _scheme: may have "+pycurl", etc
1540.3.24 by Martin Pool
Add new protocol 'http+pycurl' that always uses PyCurl.
55
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
56
    def __init__(self, base, _impl_name, _from_transport=None):
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
57
        """Set the base path where files will be stored."""
1540.3.23 by Martin Pool
Allow urls like http+pycurl://host/ to use a particular impl
58
        proto_match = re.match(r'^(https?)(\+\w+)?://', base)
59
        if not proto_match:
60
            raise AssertionError("not a http url: %r" % base)
2485.8.24 by Vincent Ladeuil
Finish http refactoring. Test suite passing.
61
        self._unqualified_scheme = proto_match.group(1)
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
62
        self._impl_name = _impl_name
2485.8.59 by Vincent Ladeuil
Update from review comments.
63
        super(HttpTransportBase, self).__init__(base,
64
                                                _from_transport=_from_transport)
3734.3.2 by Vincent Ladeuil
Fix another SmartHTTPMedium refactoring bit.
65
        self._medium = None
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
66
        # range hint is handled dynamically throughout the life
2363.4.9 by Vincent Ladeuil
Catch first succesful authentification to avoid further 401
67
        # of the transport object. We start by trying multi-range
68
        # requests and if the server returns bogus results, we
69
        # retry with single range requests and, finally, we
70
        # forget about range if the server really can't
71
        # understand. Once acquired, this piece of info is
72
        # propagated to clones.
2485.8.59 by Vincent Ladeuil
Update from review comments.
73
        if _from_transport is not None:
74
            self._range_hint = _from_transport._range_hint
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
75
        else:
76
            self._range_hint = 'multi'
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
77
78
    def has(self, relpath):
1540.3.15 by Martin Pool
[merge] large merge to sync with bzr.dev
79
        raise NotImplementedError("has() is abstract on %r" % self)
80
2164.2.15 by Vincent Ladeuil
Http redirections are not followed by default. Do not use hints
81
    def get(self, relpath):
1594.2.5 by Robert Collins
Readv patch from Johan Rydberg giving knits partial download support.
82
        """Get the file at the given relative path.
83
84
        :param relpath: The relative path to the file
85
        """
3945.1.5 by Vincent Ladeuil
Start implementing http activity reporting at socket level.
86
        code, response_file = self._get(relpath, None)
6352.4.1 by Jelmer Vernooij
Don't allow seeking backwards in get.
87
        return response_file
1540.3.26 by Martin Pool
[merge] bzr.dev; pycurl not updated for readv yet
88
2164.2.15 by Vincent Ladeuil
Http redirections are not followed by default. Do not use hints
89
    def _get(self, relpath, ranges, tail_amount=0):
1540.3.27 by Martin Pool
Integrate http range support for pycurl
90
        """Get a file, or part of a file.
91
92
        :param relpath: Path relative to transport base URL
2164.2.1 by v.ladeuil+lp at free
First rough http branch redirection implementation.
93
        :param ranges: None to get the whole file;
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
94
            or  a list of _CoalescedOffset to fetch parts of a file.
2164.2.26 by Vincent Ladeuil
Delete obsolete note in doc string.
95
        :param tail_amount: The amount to get from the end of the file.
1540.3.27 by Martin Pool
Integrate http range support for pycurl
96
97
        :returns: (http_code, result_file)
98
        """
1540.3.26 by Martin Pool
[merge] bzr.dev; pycurl not updated for readv yet
99
        raise NotImplementedError(self._get)
1594.2.5 by Robert Collins
Readv patch from Johan Rydberg giving knits partial download support.
100
3133.1.2 by Vincent Ladeuil
Fix #177643 by making pycurl handle url-embedded credentials again.
101
    def _remote_path(self, relpath):
102
        """See ConnectedTransport._remote_path.
103
104
        user and passwords are not embedded in the path provided to the server.
105
        """
5268.7.19 by Jelmer Vernooij
Use urlutils.URL in bzrlib.transport.http.
106
        url = self._parsed_url.clone(relpath)
107
        url.user = url.quoted_user = None
108
        url.password = url.quoted_password = None
109
        url.scheme = self._unqualified_scheme
110
        return str(url)
3133.1.2 by Vincent Ladeuil
Fix #177643 by making pycurl handle url-embedded credentials again.
111
112
    def _create_auth(self):
4795.4.4 by Vincent Ladeuil
Protect more access to 'user' and 'password' auth attributes.
113
        """Returns a dict containing the credentials provided at build time."""
6055.2.1 by Jelmer Vernooij
Add UnparsedUrl.
114
        auth = dict(host=self._parsed_url.host, port=self._parsed_url.port,
115
                    user=self._parsed_url.user, password=self._parsed_url.password,
3133.1.2 by Vincent Ladeuil
Fix #177643 by making pycurl handle url-embedded credentials again.
116
                    protocol=self._unqualified_scheme,
6055.2.1 by Jelmer Vernooij
Add UnparsedUrl.
117
                    path=self._parsed_url.path)
3133.1.2 by Vincent Ladeuil
Fix #177643 by making pycurl handle url-embedded credentials again.
118
        return auth
119
2018.2.3 by Andrew Bennetts
Starting factoring out the smart server client "medium" from the protocol.
120
    def get_smart_medium(self):
3734.2.3 by Vincent Ladeuil
Don't use multiple inheritance for http smart medium since we
121
        """See Transport.get_smart_medium."""
122
        if self._medium is None:
123
            # Since medium holds some state (smart server probing at least), we
124
            # need to keep it around. Note that this is needed because medium
125
            # has the same 'base' attribute as the transport so it can't be
126
            # shared between transports having different bases.
127
            self._medium = SmartClientHTTPMedium(self)
128
        return self._medium
2018.2.3 by Andrew Bennetts
Starting factoring out the smart server client "medium" from the protocol.
129
2520.2.2 by Vincent Ladeuil
Fix #115209 by issuing a single range request on 400: Bad Request
130
    def _degrade_range_hint(self, relpath, ranges, exc_info):
2000.3.9 by v.ladeuil+lp at free
The tests that would have help avoid bug #73948 and all that mess :)
131
        if self._range_hint == 'multi':
132
            self._range_hint = 'single'
2520.2.2 by Vincent Ladeuil
Fix #115209 by issuing a single range request on 400: Bad Request
133
            mutter('Retry "%s" with single range request' % relpath)
2000.3.9 by v.ladeuil+lp at free
The tests that would have help avoid bug #73948 and all that mess :)
134
        elif self._range_hint == 'single':
135
            self._range_hint = None
2520.2.2 by Vincent Ladeuil
Fix #115209 by issuing a single range request on 400: Bad Request
136
            mutter('Retry "%s" without ranges' % relpath)
2000.3.9 by v.ladeuil+lp at free
The tests that would have help avoid bug #73948 and all that mess :)
137
        else:
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
138
            # We tried all the tricks, but nothing worked. We re-raise the
139
            # original exception; the 'mutter' calls above will indicate that
140
            # further tries were unsuccessful
2172.3.1 by v.ladeuil+lp at free
Merge a recent bzr.dev (2172) and takes John's remarks into account.
141
            raise exc_info[0], exc_info[1], exc_info[2]
2000.3.9 by v.ladeuil+lp at free
The tests that would have help avoid bug #73948 and all that mess :)
142
2520.2.2 by Vincent Ladeuil
Fix #115209 by issuing a single range request on 400: Bad Request
143
    # _coalesce_offsets is a helper for readv, it try to combine ranges without
144
    # degrading readv performances. _bytes_to_read_before_seek is the value
145
    # used for the limit parameter and has been tuned for other transports. For
146
    # HTTP, the name is inappropriate but the parameter is still useful and
147
    # helps reduce the number of chunks in the response. The overhead for a
148
    # chunk (headers, length, footer around the data itself is variable but
149
    # around 50 bytes. We use 128 to reduce the range specifiers that appear in
150
    # the header, some servers (notably Apache) enforce a maximum length for a
151
    # header and issue a '400: Bad request' error when too much ranges are
152
    # specified.
153
    _bytes_to_read_before_seek = 128
154
    # No limit on the offset number that get combined into one, we are trying
3059.2.17 by Vincent Ladeuil
Limit GET requests by body size instead of number of ranges.
155
    # to avoid downloading the whole file.
3024.2.1 by Vincent Ladeuil
Fix 165061 by using the correct _max_readv_combine attribute.
156
    _max_readv_combine = 0
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
157
    # By default Apache has a limit of ~400 ranges before replying with a 400
158
    # Bad Request. So we go underneath that amount to be safe.
159
    _max_get_ranges = 200
3059.2.17 by Vincent Ladeuil
Limit GET requests by body size instead of number of ranges.
160
    # We impose no limit on the range size. But see _pycurl.py for a different
161
    # use.
162
    _get_max_size = 0
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
163
2745.5.1 by Robert Collins
* New parameter on ``bzrlib.transport.Transport.readv``
164
    def _readv(self, relpath, offsets):
1594.2.5 by Robert Collins
Readv patch from Johan Rydberg giving knits partial download support.
165
        """Get parts of the file at the given relative path.
166
1540.3.26 by Martin Pool
[merge] bzr.dev; pycurl not updated for readv yet
167
        :param offsets: A list of (offset, size) tuples.
1540.3.27 by Martin Pool
Integrate http range support for pycurl
168
        :param return: A list or generator of (offset, data) tuples
1594.2.5 by Robert Collins
Readv patch from Johan Rydberg giving knits partial download support.
169
        """
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
170
        # offsets may be a generator, we will iterate it several times, so
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
171
        # build a list
172
        offsets = list(offsets)
173
174
        try_again = True
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
175
        retried_offset = None
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
176
        while try_again:
177
            try_again = False
178
179
            # Coalesce the offsets to minimize the GET requests issued
180
            sorted_offsets = sorted(offsets)
181
            coalesced = self._coalesce_offsets(
182
                sorted_offsets, limit=self._max_readv_combine,
3059.2.17 by Vincent Ladeuil
Limit GET requests by body size instead of number of ranges.
183
                fudge_factor=self._bytes_to_read_before_seek,
184
                max_size=self._get_max_size)
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
185
186
            # Turn it into a list, we will iterate it several times
187
            coalesced = list(coalesced)
3675.1.1 by Martin Pool
Merge and update log+ transport decorator
188
            if 'http' in debug.debug_flags:
189
                mutter('http readv of %s  offsets => %s collapsed %s',
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
190
                    relpath, len(offsets), len(coalesced))
191
192
            # Cache the data read, but only until it's been used
193
            data_map = {}
194
            # We will iterate on the data received from the GET requests and
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
195
            # serve the corresponding offsets respecting the initial order. We
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
196
            # need an offset iterator for that.
197
            iter_offsets = iter(offsets)
198
            cur_offset_and_size = iter_offsets.next()
199
200
            try:
3059.2.10 by Vincent Ladeuil
Jam's review feedback.
201
                for cur_coal, rfile in self._coalesce_readv(relpath, coalesced):
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
202
                    # Split the received chunk
203
                    for offset, size in cur_coal.ranges:
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
204
                        start = cur_coal.start + offset
6450.2.1 by Vincent Ladeuil
Avoid invalid range access errors on whole files when using http transport
205
                        rfile.seek(start, os.SEEK_SET)
3059.2.10 by Vincent Ladeuil
Jam's review feedback.
206
                        data = rfile.read(size)
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
207
                        data_len = len(data)
208
                        if data_len != size:
209
                            raise errors.ShortReadvError(relpath, start, size,
210
                                                         actual=data_len)
3059.2.5 by Vincent Ladeuil
DAMN^64, the http test server is 1.0 not 1.1 :( Better pipe cleaning and less readv caching (since that's the point of the whole fix).
211
                        if (start, size) == cur_offset_and_size:
212
                            # The offset requested are sorted as the coalesced
3059.2.11 by Vincent Ladeuil
Fix typos mentioned by spiv.
213
                            # ones, no need to cache. Win !
3059.2.5 by Vincent Ladeuil
DAMN^64, the http test server is 1.0 not 1.1 :( Better pipe cleaning and less readv caching (since that's the point of the whole fix).
214
                            yield cur_offset_and_size[0], data
215
                            cur_offset_and_size = iter_offsets.next()
216
                        else:
217
                            # Different sorting. We need to cache.
218
                            data_map[(start, size)] = data
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
219
220
                    # Yield everything we can
221
                    while cur_offset_and_size in data_map:
222
                        # Clean the cached data since we use it
223
                        # XXX: will break if offsets contains duplicates --
224
                        # vila20071129
225
                        this_data = data_map.pop(cur_offset_and_size)
226
                        yield cur_offset_and_size[0], this_data
227
                        cur_offset_and_size = iter_offsets.next()
228
3059.2.2 by Vincent Ladeuil
Read http responses on demand without buffering the whole body
229
            except (errors.ShortReadvError, errors.InvalidRange,
5609.52.1 by Martin Pool
Cope with buggy squids interrupting the response before a mime multipart boundary
230
                    errors.InvalidHttpRange, errors.HttpBoundaryMissing), e:
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
231
                mutter('Exception %r: %s during http._readv',e, e)
232
                if (not isinstance(e, errors.ShortReadvError)
233
                    or retried_offset == cur_offset_and_size):
234
                    # We don't degrade the range hint for ShortReadvError since
235
                    # they do not indicate a problem with the server ability to
236
                    # handle ranges. Except when we fail to get back a required
237
                    # offset twice in a row. In that case, falling back to
238
                    # single range or whole file should help or end up in a
239
                    # fatal exception.
240
                    self._degrade_range_hint(relpath, coalesced, sys.exc_info())
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
241
                # Some offsets may have been already processed, so we retry
242
                # only the unsuccessful ones.
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
243
                offsets = [cur_offset_and_size] + [o for o in iter_offsets]
3146.3.2 by Vincent Ladeuil
Fix #179368 by keeping the current range hint on ShortReadvErrors.
244
                retried_offset = cur_offset_and_size
3052.3.2 by Vincent Ladeuil
Add tests and fix trivial bugs and other typos.
245
                try_again = True
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
246
247
    def _coalesce_readv(self, relpath, coalesced):
248
        """Issue several GET requests to satisfy the coalesced offsets"""
3059.2.17 by Vincent Ladeuil
Limit GET requests by body size instead of number of ranges.
249
250
        def get_and_yield(relpath, coalesced):
251
            if coalesced:
252
                # Note that the _get below may raise
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
253
                # errors.InvalidHttpRange. It's the caller's responsibility to
3059.2.17 by Vincent Ladeuil
Limit GET requests by body size instead of number of ranges.
254
                # decide how to retry since it may provide different coalesced
255
                # offsets.
256
                code, rfile = self._get(relpath, coalesced)
257
                for coal in coalesced:
258
                    yield coal, rfile
259
260
        if self._range_hint is None:
261
            # Download whole file
262
            for c, rfile in get_and_yield(relpath, coalesced):
263
                yield c, rfile
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
264
        else:
3059.2.17 by Vincent Ladeuil
Limit GET requests by body size instead of number of ranges.
265
            total = len(coalesced)
266
            if self._range_hint == 'multi':
267
                max_ranges = self._max_get_ranges
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
268
            elif self._range_hint == 'single':
3059.2.17 by Vincent Ladeuil
Limit GET requests by body size instead of number of ranges.
269
                max_ranges = total
3059.2.18 by Vincent Ladeuil
Take spiv review comments into account.
270
            else:
271
                raise AssertionError("Unknown _range_hint %r"
272
                                     % (self._range_hint,))
3059.2.17 by Vincent Ladeuil
Limit GET requests by body size instead of number of ranges.
273
            # TODO: Some web servers may ignore the range requests and return
274
            # the whole file, we may want to detect that and avoid further
275
            # requests.
276
            # Hint: test_readv_multiple_get_requests will fail once we do that
277
            cumul = 0
278
            ranges = []
279
            for coal in coalesced:
280
                if ((self._get_max_size > 0
281
                     and cumul + coal.length > self._get_max_size)
282
                    or len(ranges) >= max_ranges):
283
                    # Get that much and yield
284
                    for c, rfile in get_and_yield(relpath, ranges):
285
                        yield c, rfile
286
                    # Restart with the current offset
287
                    ranges = [coal]
288
                    cumul = coal.length
289
                else:
290
                    ranges.append(coal)
291
                    cumul += coal.length
292
            # Get the rest and yield
293
            for c, rfile in get_and_yield(relpath, ranges):
294
                yield c, rfile
1786.1.5 by John Arbash Meinel
Move the common Multipart stuff into plain http, and wrap pycurl response so that it matches the urllib response object.
295
2671.3.1 by Robert Collins
* New method ``bzrlib.transport.Transport.get_recommended_page_size``.
296
    def recommended_page_size(self):
297
        """See Transport.recommended_page_size().
298
299
        For HTTP we suggest a large page size to reduce the overhead
300
        introduced by latency.
301
        """
302
        return 64 * 1024
303
2018.2.10 by Andrew Bennetts
Tidy up TODOs, further testing and fixes for SmartServerRequestProtocolOne, and remove a read_bytes(1) call.
304
    def _post(self, body_bytes):
305
        """POST body_bytes to .bzr/smart on this transport.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
306
2018.2.10 by Andrew Bennetts
Tidy up TODOs, further testing and fixes for SmartServerRequestProtocolOne, and remove a read_bytes(1) call.
307
        :returns: (response code, response body file-like object).
308
        """
309
        # TODO: Requiring all the body_bytes to be available at the beginning of
310
        # the POST may require large client buffers.  It would be nice to have
311
        # an interface that allows streaming via POST when possible (and
312
        # degrades to a local buffer when not).
313
        raise NotImplementedError(self._post)
314
1955.3.6 by John Arbash Meinel
Lots of deprecation warnings, but no errors
315
    def put_file(self, relpath, f, mode=None):
316
        """Copy the file-like object into the location.
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
317
318
        :param relpath: Location to put the contents, relative to base.
1955.3.6 by John Arbash Meinel
Lots of deprecation warnings, but no errors
319
        :param f:       File-like object.
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
320
        """
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
321
        raise errors.TransportNotPossible('http PUT not supported')
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
322
1185.58.2 by John Arbash Meinel
Added mode to the appropriate transport functions, and tests to make sure they work.
323
    def mkdir(self, relpath, mode=None):
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
324
        """Create a directory at the given path."""
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
325
        raise errors.TransportNotPossible('http does not support mkdir()')
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
326
1534.4.15 by Robert Collins
Remove shutil dependency in upgrade - create a delete_tree method for transports.
327
    def rmdir(self, relpath):
328
        """See Transport.rmdir."""
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
329
        raise errors.TransportNotPossible('http does not support rmdir()')
1534.4.15 by Robert Collins
Remove shutil dependency in upgrade - create a delete_tree method for transports.
330
1955.3.15 by John Arbash Meinel
Deprecate 'Transport.append' in favor of Transport.append_file or Transport.append_bytes
331
    def append_file(self, relpath, f, mode=None):
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
332
        """Append the text in the file-like object into the final
333
        location.
334
        """
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
335
        raise errors.TransportNotPossible('http does not support append()')
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
336
337
    def copy(self, rel_from, rel_to):
338
        """Copy the item at rel_from to the location at rel_to"""
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
339
        raise errors.TransportNotPossible('http does not support copy()')
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
340
1185.58.2 by John Arbash Meinel
Added mode to the appropriate transport functions, and tests to make sure they work.
341
    def copy_to(self, relpaths, other, mode=None, pb=None):
907.1.28 by John Arbash Meinel
Added pb to function that were missing, implemented a basic double-dispatch copy_to function.
342
        """Copy a set of entries from self into another Transport.
343
344
        :param relpaths: A list/generator of entries to be copied.
907.1.50 by John Arbash Meinel
Removed encode/decode from Transport.put/get, added more exceptions that can be thrown.
345
346
        TODO: if other is LocalTransport, is it possible to
347
              do better than put(get())?
907.1.28 by John Arbash Meinel
Added pb to function that were missing, implemented a basic double-dispatch copy_to function.
348
        """
907.1.29 by John Arbash Meinel
Fixing small bug in HttpTransport.copy_to
349
        # At this point HttpTransport might be able to check and see if
350
        # the remote location is the same, and rather than download, and
351
        # then upload, it could just issue a remote copy_this command.
1540.3.6 by Martin Pool
[merge] update from bzr.dev
352
        if isinstance(other, HttpTransportBase):
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
353
            raise errors.TransportNotPossible(
354
                'http cannot be the target of copy_to()')
907.1.28 by John Arbash Meinel
Added pb to function that were missing, implemented a basic double-dispatch copy_to function.
355
        else:
1540.3.26 by Martin Pool
[merge] bzr.dev; pycurl not updated for readv yet
356
            return super(HttpTransportBase, self).\
357
                    copy_to(relpaths, other, mode=mode, pb=pb)
907.1.28 by John Arbash Meinel
Added pb to function that were missing, implemented a basic double-dispatch copy_to function.
358
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
359
    def move(self, rel_from, rel_to):
360
        """Move the item at rel_from to the location at rel_to"""
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
361
        raise errors.TransportNotPossible('http does not support move()')
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
362
363
    def delete(self, relpath):
364
        """Delete the item at relpath"""
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
365
        raise errors.TransportNotPossible('http does not support delete()')
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
366
2634.1.1 by Robert Collins
(robertc) Reinstate the accidentally backed out external_url patch.
367
    def external_url(self):
368
        """See bzrlib.transport.Transport.external_url."""
3878.4.6 by Vincent Ladeuil
Fix bug #270863 by preserving 'bzr+http[s]' decorator.
369
        # HTTP URL's are externally usable as long as they don't mention their
370
        # implementation qualifier
5268.7.18 by Jelmer Vernooij
Use urlutils.URL in bzrlib.transport.http.
371
        url = self._parsed_url.clone()
372
        url.scheme = self._unqualified_scheme
373
        return str(url)
2634.1.1 by Robert Collins
(robertc) Reinstate the accidentally backed out external_url patch.
374
1530.1.3 by Robert Collins
transport implementations now tested consistently.
375
    def is_readonly(self):
376
        """See Transport.is_readonly."""
377
        return True
378
1400.1.1 by Robert Collins
implement a basic test for the ui branch command from http servers
379
    def listable(self):
380
        """See Transport.listable."""
381
        return False
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
382
383
    def stat(self, relpath):
384
        """Return the stat information for a file.
385
        """
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
386
        raise errors.TransportNotPossible('http does not support stat()')
907.1.21 by John Arbash Meinel
Adding http transport as a valid transport protocol.
387
907.1.24 by John Arbash Meinel
Remote functionality work.
388
    def lock_read(self, relpath):
389
        """Lock the given file for shared (read) access.
390
        :return: A lock object, which should be passed to Transport.unlock()
391
        """
392
        # The old RemoteBranch ignore lock for reading, so we will
393
        # continue that tradition and return a bogus lock object.
394
        class BogusLock(object):
395
            def __init__(self, path):
396
                self.path = path
397
            def unlock(self):
398
                pass
399
        return BogusLock(relpath)
400
401
    def lock_write(self, relpath):
402
        """Lock the given file for exclusive (write) access.
403
        WARNING: many transports do not support this, so trying avoid using it
404
405
        :return: A lock object, which should be passed to Transport.unlock()
406
        """
2004.1.25 by v.ladeuil+lp at free
Shuffle http related test code. Hopefully it ends up at the right place :)
407
        raise errors.TransportNotPossible('http does not support lock_write()')
1530.1.1 by Robert Collins
Minimal infrastructure to test TransportTestProviderAdapter.
408
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
409
    def _attempted_range_header(self, offsets, tail_amount):
3059.2.17 by Vincent Ladeuil
Limit GET requests by body size instead of number of ranges.
410
        """Prepare a HTTP Range header at a level the server should accept.
411
412
        :return: the range header representing offsets/tail_amount or None if
413
            no header can be built.
414
        """
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
415
416
        if self._range_hint == 'multi':
3024.2.3 by Vincent Ladeuil
Rewrite http_readv to allow several GET requests. Smoke tested against branch reported in the bug.
417
            # Generate the header describing all offsets
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
418
            return self._range_header(offsets, tail_amount)
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
419
        elif self._range_hint == 'single':
420
            # Combine all the requested ranges into a single
421
            # encompassing one
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
422
            if len(offsets) > 0:
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
423
                if tail_amount not in (0, None):
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
424
                    # Nothing we can do here to combine ranges with tail_amount
425
                    # in a single range, just returns None. The whole file
426
                    # should be downloaded.
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
427
                    return None
428
                else:
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
429
                    start = offsets[0].start
430
                    last = offsets[-1]
431
                    end = last.start + last.length - 1
432
                    whole = self._coalesce_offsets([(start, end - start + 1)],
433
                                                   limit=0, fudge_factor=0)
434
                    return self._range_header(list(whole), 0)
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
435
            else:
436
                # Only tail_amount, requested, leave range_header
437
                # do its work
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
438
                return self._range_header(offsets, tail_amount)
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
439
        else:
440
            return None
441
1786.1.27 by John Arbash Meinel
Fix up the http transports so that tests pass with the new configuration.
442
    @staticmethod
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
443
    def _range_header(ranges, tail_amount):
1750.1.2 by Michael Ellerman
Add support for HTTP multipart ranges and hook it into http+urllib.
444
        """Turn a list of bytes ranges into a HTTP Range header value.
445
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
446
        :param ranges: A list of _CoalescedOffset
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
447
        :param tail_amount: The amount to get from the end of the file.
1750.1.2 by Michael Ellerman
Add support for HTTP multipart ranges and hook it into http+urllib.
448
449
        :return: HTTP range header string.
2004.1.30 by v.ladeuil+lp at free
Fix #62276 and #62029 by providing a more robust http range handling.
450
451
        At least a non-empty ranges *or* a tail_amount must be
452
        provided.
1750.1.2 by Michael Ellerman
Add support for HTTP multipart ranges and hook it into http+urllib.
453
        """
454
        strings = []
2520.2.1 by Vincent Ladeuil
First step to fix #115209 use _coalesce_offsets like other transports.
455
        for offset in ranges:
456
            strings.append('%d-%d' % (offset.start,
457
                                      offset.start + offset.length - 1))
1750.1.2 by Michael Ellerman
Add support for HTTP multipart ranges and hook it into http+urllib.
458
1786.1.8 by John Arbash Meinel
[merge] Johan Rydberg test updates
459
        if tail_amount:
460
            strings.append('-%d' % tail_amount)
461
1786.1.36 by John Arbash Meinel
pycurl expects us to just set the range of bytes, not including bytes=
462
        return ','.join(strings)
1750.1.2 by Michael Ellerman
Add support for HTTP multipart ranges and hook it into http+urllib.
463
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
464
    def _redirected_to(self, source, target):
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
465
        """Returns a transport suitable to re-issue a redirected request.
466
3878.4.5 by Vincent Ladeuil
Don't use the exception as a parameter for _redirected_to.
467
        :param source: The source url as returned by the server.
468
        :param target: The target url as returned by the server.
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
469
470
        The redirection can be handled only if the relpath involved is not
471
        renamed by the redirection.
472
473
        :returns: A transport or None.
474
        """
6145.1.2 by Jelmer Vernooij
Some refactoring.
475
        parsed_source = self._split_url(source)
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
476
        parsed_target = self._split_url(target)
6145.1.2 by Jelmer Vernooij
Some refactoring.
477
        pl = len(self._parsed_url.path)
6145.1.4 by Jelmer Vernooij
Some more comments.
478
        # determine the excess tail - the relative path that was in
479
        # the original request but not part of this transports' URL.
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
480
        excess_tail = parsed_source.path[pl:].strip("/")
481
        if not target.endswith(excess_tail):
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
482
            # The final part of the url has been renamed, we can't handle the
483
            # redirection.
484
            return None
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
485
486
        target_path = parsed_target.path
487
        if excess_tail:
488
            # Drop the tail that was in the redirect but not part of
489
            # the path of this transport.
490
            target_path = target_path[:-len(excess_tail)]
491
6145.1.2 by Jelmer Vernooij
Some refactoring.
492
        if parsed_target.scheme in ('http', 'https'):
3878.4.7 by Vincent Ladeuil
Fixed as per Robert's review.
493
            # Same protocol family (i.e. http[s]), we will preserve the same
494
            # http client implementation when a redirection occurs from one to
495
            # the other (otherwise users may be surprised that bzr switches
496
            # from one implementation to the other, and devs may suffer
497
            # debugging it).
6145.1.2 by Jelmer Vernooij
Some refactoring.
498
            if (parsed_target.scheme == self._unqualified_scheme
499
                and parsed_target.host == self._parsed_url.host
500
                and parsed_target.port == self._parsed_url.port
501
                and (parsed_target.user is None or
502
                     parsed_target.user == self._parsed_url.user)):
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
503
                # If a user is specified, it should match, we don't care about
504
                # passwords, wrong passwords will be rejected anyway.
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
505
                return self.clone(target_path)
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
506
            else:
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
507
                # Rebuild the url preserving the scheme qualification and the
508
                # credentials (if they don't apply, the redirected to server
509
                # will tell us, but if they do apply, we avoid prompting the
510
                # user)
6145.1.2 by Jelmer Vernooij
Some refactoring.
511
                redir_scheme = parsed_target.scheme + '+' + self._impl_name
3878.4.2 by Vincent Ladeuil
Fix bug #265070 by providing a finer sieve for accepted redirections.
512
                new_url = self._unsplit_url(redir_scheme,
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
513
                    self._parsed_url.user,
514
                    self._parsed_url.password,
515
                    parsed_target.host, parsed_target.port,
516
                    target_path)
517
                return transport.get_transport_from_url(new_url)
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
518
        else:
519
            # Redirected to a different protocol
6145.1.3 by Jelmer Vernooij
Fix redirecting to other transports.
520
            new_url = self._unsplit_url(parsed_target.scheme,
521
                    parsed_target.user,
522
                    parsed_target.password,
523
                    parsed_target.host, parsed_target.port,
524
                    target_path)
525
            return transport.get_transport_from_url(new_url)
3878.4.1 by Vincent Ladeuil
Fix bug #245964 by preserving decorators during redirections (when
526
3734.2.3 by Vincent Ladeuil
Don't use multiple inheritance for http smart medium since we
527
528
# TODO: May be better located in smart/medium.py with the other
529
# SmartMedium classes
530
class SmartClientHTTPMedium(medium.SmartClientMedium):
531
532
    def __init__(self, http_transport):
533
        super(SmartClientHTTPMedium, self).__init__(http_transport.base)
534
        # We don't want to create a circular reference between the http
535
        # transport and its associated medium. Since the transport will live
536
        # longer than the medium, the medium keep only a weak reference to its
537
        # transport.
538
        self._http_transport_ref = weakref.ref(http_transport)
539
540
    def get_request(self):
541
        return SmartClientHTTPMediumRequest(self)
2018.2.8 by Andrew Bennetts
Make HttpTransportBase.get_smart_client return self again.
542
3245.4.47 by Andrew Bennetts
Don't automatically send 'hello' requests from RemoteBzrDirFormat.probe_transport unless we have to (i.e. the transport is HTTP).
543
    def should_probe(self):
544
        return True
545
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
546
    def remote_path_from_transport(self, transport):
547
        # Strip the optional 'bzr+' prefix from transport so it will have the
548
        # same scheme as self.
549
        transport_base = transport.base
550
        if transport_base.startswith('bzr+'):
551
            transport_base = transport_base[4:]
552
        rel_url = urlutils.relative_url(self.base, transport_base)
6379.4.2 by Jelmer Vernooij
Add urlutils.quote / urlutils.unquote.
553
        return urlutils.unquote(rel_url)
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
554
3734.2.3 by Vincent Ladeuil
Don't use multiple inheritance for http smart medium since we
555
    def send_http_smart_request(self, bytes):
556
        try:
557
            # Get back the http_transport hold by the weak reference
558
            t = self._http_transport_ref()
559
            code, body_filelike = t._post(bytes)
560
            if code != 200:
6123.2.1 by Jelmer Vernooij
Remove unused imports, fix import of error.
561
                raise errors.InvalidHttpResponse(
3734.2.3 by Vincent Ladeuil
Don't use multiple inheritance for http smart medium since we
562
                    t._remote_path('.bzr/smart'),
563
                    'Expected 200 response code, got %r' % (code,))
4628.1.2 by Vincent Ladeuil
More complete fix.
564
        except (errors.InvalidHttpResponse, errors.ConnectionReset), e:
3734.2.3 by Vincent Ladeuil
Don't use multiple inheritance for http smart medium since we
565
            raise errors.SmartProtocolError(str(e))
566
        return body_filelike
567
3958.1.1 by Andrew Bennetts
Report traffic on smart media as transport activity.
568
    def _report_activity(self, bytes, direction):
569
        """See SmartMedium._report_activity.
570
571
        Does nothing; the underlying plain HTTP transport will report the
572
        activity that this medium would report.
573
        """
574
        pass
575
5247.2.12 by Vincent Ladeuil
Ensure that all transports close their underlying connection.
576
    def disconnect(self):
577
        """See SmartClientMedium.disconnect()."""
578
        t = self._http_transport_ref()
579
        t.disconnect()
580
3734.2.3 by Vincent Ladeuil
Don't use multiple inheritance for http smart medium since we
581
582
# TODO: May be better located in smart/medium.py with the other
583
# SmartMediumRequest classes
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
584
class SmartClientHTTPMediumRequest(medium.SmartClientMediumRequest):
2018.2.8 by Andrew Bennetts
Make HttpTransportBase.get_smart_client return self again.
585
    """A SmartClientMediumRequest that works with an HTTP medium."""
586
2018.5.2 by Andrew Bennetts
Start splitting bzrlib/transport/smart.py into a package.
587
    def __init__(self, client_medium):
588
        medium.SmartClientMediumRequest.__init__(self, client_medium)
2018.2.8 by Andrew Bennetts
Make HttpTransportBase.get_smart_client return self again.
589
        self._buffer = ''
590
591
    def _accept_bytes(self, bytes):
592
        self._buffer += bytes
593
594
    def _finished_writing(self):
595
        data = self._medium.send_http_smart_request(self._buffer)
596
        self._response_body = data
597
598
    def _read_bytes(self, count):
3565.1.2 by Andrew Bennetts
Delete some more code, fix some bugs, add more comments.
599
        """See SmartClientMediumRequest._read_bytes."""
2018.2.8 by Andrew Bennetts
Make HttpTransportBase.get_smart_client return self again.
600
        return self._response_body.read(count)
2004.1.28 by v.ladeuil+lp at free
Merge bzr.dev. Including http modifications by "smart" related code
601
3606.4.1 by Andrew Bennetts
Fix NotImplementedError when probing for smart protocol via HTTP.
602
    def _read_line(self):
603
        line, excess = medium._get_line(self._response_body.read)
604
        if excess != '':
605
            raise AssertionError(
606
                '_get_line returned excess bytes, but this mediumrequest '
607
                'cannot handle excess. (%r)' % (excess,))
608
        return line
609
2018.2.8 by Andrew Bennetts
Make HttpTransportBase.get_smart_client return self again.
610
    def _finished_reading(self):
611
        """See SmartClientMediumRequest._finished_reading."""
612
        pass
4912.2.1 by Martin Pool
Add unhtml_roughly
613
614
4912.2.4 by Martin Pool
Add test for unhtml_roughly, and truncate at 1000 bytes
615
def unhtml_roughly(maybe_html, length_limit=1000):
4912.2.1 by Martin Pool
Add unhtml_roughly
616
    """Very approximate html->text translation, for presenting error bodies.
617
4912.2.4 by Martin Pool
Add test for unhtml_roughly, and truncate at 1000 bytes
618
    :param length_limit: Truncate the result to this many characters.
619
4912.2.1 by Martin Pool
Add unhtml_roughly
620
    >>> unhtml_roughly("<b>bad</b> things happened\\n")
621
    ' bad  things happened '
622
    """
4912.2.4 by Martin Pool
Add test for unhtml_roughly, and truncate at 1000 bytes
623
    return re.subn(r"(<[^>]*>|\n|&nbsp;)", " ", maybe_html)[0][:length_limit]