1
# Copyright (C) 2005 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
16
"""Implementation of Transport over http.
19
from bzrlib.transport import Transport, register_transport
20
from bzrlib.errors import (TransportNotPossible, NoSuchFile,
21
TransportError, ConnectionError)
23
from cStringIO import StringIO
24
import urllib, urllib2
27
from bzrlib.errors import BzrError, BzrCheckError
28
from bzrlib.branch import Branch
29
from bzrlib.trace import mutter
32
def extract_auth(url, password_manager):
34
Extract auth parameters from am HTTP/HTTPS url and add them to the given
35
password manager. Return the url, minus those auth parameters (which
38
assert url.startswith('http://') or url.startswith('https://')
39
scheme, host = url.split('//', 1)
41
host, path = host.split('/', 1)
47
auth, host = host.split('@', 1)
49
username, password = auth.split(':', 1)
51
username, password = auth, None
53
host, port = host.split(':', 1)
55
# FIXME: if password isn't given, should we ask for it?
56
if password is not None:
57
username = urllib.unquote(username)
58
password = urllib.unquote(password)
59
password_manager.add_password(None, host, username, password)
60
url = scheme + '//' + host + port + path
65
mutter("get_url %s" % url)
66
manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
67
url = extract_auth(url, manager)
68
auth_handler = urllib2.HTTPBasicAuthHandler(manager)
69
opener = urllib2.build_opener(auth_handler)
70
url_f = opener.open(url)
73
class HttpTransport(Transport):
74
"""This is the transport agent for http:// access.
76
TODO: Implement pipelined versions of all of the *_multi() functions.
79
def __init__(self, base):
80
"""Set the base path where files will be stored."""
81
assert base.startswith('http://') or base.startswith('https://')
82
super(HttpTransport, self).__init__(base)
83
# In the future we might actually connect to the remote host
84
# rather than using get_url
85
# self._connection = None
86
(self._proto, self._host,
87
self._path, self._parameters,
88
self._query, self._fragment) = urlparse.urlparse(self.base)
90
def should_cache(self):
91
"""Return True if the data pulled across should be cached locally.
95
def clone(self, offset=None):
96
"""Return a new HttpTransport with root at self.base + offset
97
For now HttpTransport does not actually connect, so just return
98
a new HttpTransport object.
101
return HttpTransport(self.base)
103
return HttpTransport(self.abspath(offset))
105
def abspath(self, relpath):
106
"""Return the full url to the given relative path.
107
This can be supplied with a string or a list
109
assert isinstance(relpath, basestring)
110
if isinstance(relpath, basestring):
111
relpath_parts = relpath.split('/')
113
# TODO: Don't call this with an array - no magic interfaces
114
relpath_parts = relpath[:]
115
if len(relpath_parts) > 1:
116
if relpath_parts[0] == '':
117
raise ValueError("path %r within branch %r seems to be absolute"
118
% (relpath, self._path))
119
if relpath_parts[-1] == '':
120
raise ValueError("path %r within branch %r seems to be a directory"
121
% (relpath, self._path))
122
basepath = self._path.split('/')
123
if len(basepath) > 0 and basepath[-1] == '':
124
basepath = basepath[:-1]
125
for p in relpath_parts:
127
if len(basepath) == 0:
128
# In most filesystems, a request for the parent
129
# of root, just returns root.
132
elif p == '.' or p == '':
136
# Possibly, we could use urlparse.urljoin() here, but
137
# I'm concerned about when it chooses to strip the last
138
# portion of the path, and when it doesn't.
139
path = '/'.join(basepath)
140
return urlparse.urlunparse((self._proto,
141
self._host, path, '', '', ''))
143
def has(self, relpath):
144
"""Does the target location exist?
146
TODO: HttpTransport.has() should use a HEAD request,
147
not a full GET request.
149
TODO: This should be changed so that we don't use
150
urllib2 and get an exception, the code path would be
151
cleaner if we just do an http HEAD request, and parse
156
path = self.abspath(relpath)
158
# Without the read and then close()
159
# we tend to have busy sockets.
163
except urllib2.URLError, e:
164
mutter('url error code: %s for has url: %r', e.code, path)
169
mutter('io error: %s %s for has url: %r',
170
e.errno, errno.errorcode.get(e.errno), path)
171
if e.errno == errno.ENOENT:
173
raise TransportError(orig_error=e)
175
def get(self, relpath, decode=False):
176
"""Get the file at the given relative path.
178
:param relpath: The relative path to the file
182
path = self.abspath(relpath)
184
except urllib2.HTTPError, e:
185
mutter('url error code: %s for has url: %r', e.code, path)
187
raise NoSuchFile(path, extra=e)
189
except (BzrError, IOError), e:
190
if hasattr(e, 'errno'):
191
mutter('io error: %s %s for has url: %r',
192
e.errno, errno.errorcode.get(e.errno), path)
193
if e.errno == errno.ENOENT:
194
raise NoSuchFile(path, extra=e)
195
raise ConnectionError(msg = "Error retrieving %s: %s"
196
% (self.abspath(relpath), str(e)),
199
def put(self, relpath, f, mode=None):
200
"""Copy the file-like or string object into the location.
202
:param relpath: Location to put the contents, relative to base.
203
:param f: File-like or string object.
205
raise TransportNotPossible('http PUT not supported')
207
def mkdir(self, relpath, mode=None):
208
"""Create a directory at the given path."""
209
raise TransportNotPossible('http does not support mkdir()')
211
def append(self, relpath, f):
212
"""Append the text in the file-like object into the final
215
raise TransportNotPossible('http does not support append()')
217
def copy(self, rel_from, rel_to):
218
"""Copy the item at rel_from to the location at rel_to"""
219
raise TransportNotPossible('http does not support copy()')
221
def copy_to(self, relpaths, other, mode=None, pb=None):
222
"""Copy a set of entries from self into another Transport.
224
:param relpaths: A list/generator of entries to be copied.
226
TODO: if other is LocalTransport, is it possible to
227
do better than put(get())?
229
# At this point HttpTransport might be able to check and see if
230
# the remote location is the same, and rather than download, and
231
# then upload, it could just issue a remote copy_this command.
232
if isinstance(other, HttpTransport):
233
raise TransportNotPossible('http cannot be the target of copy_to()')
235
return super(HttpTransport, self).copy_to(relpaths, other, mode=mode, pb=pb)
237
def move(self, rel_from, rel_to):
238
"""Move the item at rel_from to the location at rel_to"""
239
raise TransportNotPossible('http does not support move()')
241
def delete(self, relpath):
242
"""Delete the item at relpath"""
243
raise TransportNotPossible('http does not support delete()')
246
"""See Transport.listable."""
249
def stat(self, relpath):
250
"""Return the stat information for a file.
252
raise TransportNotPossible('http does not support stat()')
254
def lock_read(self, relpath):
255
"""Lock the given file for shared (read) access.
256
:return: A lock object, which should be passed to Transport.unlock()
258
# The old RemoteBranch ignore lock for reading, so we will
259
# continue that tradition and return a bogus lock object.
260
class BogusLock(object):
261
def __init__(self, path):
265
return BogusLock(relpath)
267
def lock_write(self, relpath):
268
"""Lock the given file for exclusive (write) access.
269
WARNING: many transports do not support this, so trying avoid using it
271
:return: A lock object, which should be passed to Transport.unlock()
273
raise TransportNotPossible('http does not support lock_write()')