1
# Copyright (C) 2005, 2006 Canonical Ltd
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.
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.
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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
import urllib, urllib2
19
import bzrlib # for the version
20
from bzrlib.errors import BzrError
21
from bzrlib.trace import mutter
22
from bzrlib.transport.http import HttpTransportBase, extract_auth, HttpServer
23
from bzrlib.errors import (TransportNotPossible, NoSuchFile,
24
TransportError, ConnectionError)
27
class Request(urllib2.Request):
28
"""Request object for urllib2 that allows the method to be overridden."""
33
if self.method is not None:
36
return urllib2.Request.get_method(self)
39
class HttpTransport_urllib(HttpTransportBase):
40
"""Python urllib transport for http and https.
43
# TODO: Implement pipelined versions of all of the *_multi() functions.
45
def __init__(self, base):
46
"""Set the base path where files will be stored."""
47
super(HttpTransport_urllib, self).__init__(base)
49
def _get(self, relpath, ranges):
52
path = self._real_abspath(relpath)
53
response = self._get_url_impl(path, method='GET', ranges=ranges)
54
return response.code, response
55
except urllib2.HTTPError, e:
56
mutter('url error code: %s for has url: %r', e.code, path)
58
raise NoSuchFile(path, extra=e)
60
except (BzrError, IOError), e:
61
if hasattr(e, 'errno'):
62
mutter('io error: %s %s for has url: %r',
63
e.errno, errno.errorcode.get(e.errno), path)
64
if e.errno == errno.ENOENT:
65
raise NoSuchFile(path, extra=e)
66
raise ConnectionError(msg = "Error retrieving %s: %s"
67
% (self.abspath(relpath), str(e)),
70
def _get_url_impl(self, url, method, ranges):
71
"""Actually pass get request into urllib
73
:returns: urllib Response object
79
mutter("get_url %s [%s]" % (url, range_string))
80
manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
81
url = extract_auth(url, manager)
82
auth_handler = urllib2.HTTPBasicAuthHandler(manager)
83
opener = urllib2.build_opener(auth_handler)
84
request = Request(url)
85
request.method = method
86
request.add_header('User-Agent', 'bzr/%s (urllib)' % bzrlib.__version__)
88
assert len(ranges) == 1
89
request.add_header('Range', 'bytes=%d-%d' % ranges[0])
90
response = opener.open(request)
93
def should_cache(self):
94
"""Return True if the data pulled across should be cached locally.
98
def has(self, relpath):
99
"""Does the target location exist?
101
abspath = self._real_abspath(relpath)
103
f = self._get_url_impl(abspath, 'HEAD', [])
104
# Without the read and then close()
105
# we tend to have busy sockets.
109
except urllib2.URLError, e:
110
mutter('url error code: %s for has url: %r', e.code, abspath)
115
mutter('io error: %s %s for has url: %r',
116
e.errno, errno.errorcode.get(e.errno), abspath)
117
if e.errno == errno.ENOENT:
119
raise TransportError(orig_error=e)
121
def copy_to(self, relpaths, other, mode=None, pb=None):
122
"""Copy a set of entries from self into another Transport.
124
:param relpaths: A list/generator of entries to be copied.
126
TODO: if other is LocalTransport, is it possible to
127
do better than put(get())?
129
# At this point HttpTransport_urllib might be able to check and see if
130
# the remote location is the same, and rather than download, and
131
# then upload, it could just issue a remote copy_this command.
132
if isinstance(other, HttpTransport_urllib):
133
raise TransportNotPossible('http cannot be the target of copy_to()')
135
return super(HttpTransport_urllib, self).copy_to(relpaths, other, mode=mode, pb=pb)
137
def move(self, rel_from, rel_to):
138
"""Move the item at rel_from to the location at rel_to"""
139
raise TransportNotPossible('http does not support move()')
141
def delete(self, relpath):
142
"""Delete the item at relpath"""
143
raise TransportNotPossible('http does not support delete()')
146
class HttpServer_urllib(HttpServer):
147
"""Subclass of HttpServer that gives http+urllib urls.
149
This is for use in testing: connections to this server will always go
150
through urllib where possible.
153
# urls returned by this server should require the urllib client impl
154
_url_protocol = 'http+urllib'
157
def get_test_permutations():
158
"""Return the permutations to be used in testing."""
159
return [(HttpTransport_urllib, HttpServer_urllib),