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
NonRelativePath, 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 HttpTransportError(TransportError):
76
class HttpTransport(Transport):
77
"""This is the transport agent for http:// access.
79
TODO: Implement pipelined versions of all of the *_multi() functions.
82
def __init__(self, base):
83
"""Set the base path where files will be stored."""
84
assert base.startswith('http://') or base.startswith('https://')
85
super(HttpTransport, self).__init__(base)
86
# In the future we might actually connect to the remote host
87
# rather than using get_url
88
# self._connection = None
89
(self._proto, self._host,
90
self._path, self._parameters,
91
self._query, self._fragment) = urlparse.urlparse(self.base)
93
def should_cache(self):
94
"""Return True if the data pulled across should be cached locally.
98
def clone(self, offset=None):
99
"""Return a new HttpTransport with root at self.base + offset
100
For now HttpTransport does not actually connect, so just return
101
a new HttpTransport object.
104
return HttpTransport(self.base)
106
return HttpTransport(self.abspath(offset))
108
def abspath(self, relpath):
109
"""Return the full url to the given relative path.
110
This can be supplied with a string or a list
112
assert isinstance(relpath, basestring)
113
if isinstance(relpath, basestring):
114
relpath_parts = relpath.split('/')
116
# TODO: Don't call this with an array - no magic interfaces
117
relpath_parts = relpath[:]
118
if len(relpath_parts) > 1:
119
if relpath_parts[0] == '':
120
raise ValueError("path %r within branch %r seems to be absolute"
121
% (relpath, self._path))
122
if relpath_parts[-1] == '':
123
raise ValueError("path %r within branch %r seems to be a directory"
124
% (relpath, self._path))
125
basepath = self._path.split('/')
126
if len(basepath) > 0 and basepath[-1] == '':
127
basepath = basepath[:-1]
128
for p in relpath_parts:
130
if len(basepath) == 0:
131
# In most filesystems, a request for the parent
132
# of root, just returns root.
135
elif p == '.' or p == '':
139
# Possibly, we could use urlparse.urljoin() here, but
140
# I'm concerned about when it chooses to strip the last
141
# portion of the path, and when it doesn't.
142
path = '/'.join(basepath)
143
return urlparse.urlunparse((self._proto,
144
self._host, path, '', '', ''))
146
def has(self, relpath):
147
"""Does the target location exist?
149
TODO: HttpTransport.has() should use a HEAD request,
150
not a full GET request.
152
TODO: This should be changed so that we don't use
153
urllib2 and get an exception, the code path would be
154
cleaner if we just do an http HEAD request, and parse
158
f = get_url(self.abspath(relpath))
159
# Without the read and then close()
160
# we tend to have busy sockets.
164
except urllib2.URLError, e:
169
if e.errno == errno.ENOENT:
171
raise HttpTransportError(orig_error=e)
173
def get(self, relpath, decode=False):
174
"""Get the file at the given relative path.
176
:param relpath: The relative path to the file
179
return get_url(self.abspath(relpath))
180
except urllib2.HTTPError, e:
182
raise NoSuchFile(msg = "Error retrieving %s: %s"
183
% (self.abspath(relpath), str(e)),
186
except (BzrError, IOError), e:
187
raise ConnectionError(msg = "Error retrieving %s: %s"
188
% (self.abspath(relpath), str(e)),
191
def put(self, relpath, f):
192
"""Copy the file-like or string object into the location.
194
:param relpath: Location to put the contents, relative to base.
195
:param f: File-like or string object.
197
raise TransportNotPossible('http PUT not supported')
199
def mkdir(self, relpath):
200
"""Create a directory at the given path."""
201
raise TransportNotPossible('http does not support mkdir()')
203
def append(self, relpath, f):
204
"""Append the text in the file-like object into the final
207
raise TransportNotPossible('http does not support append()')
209
def copy(self, rel_from, rel_to):
210
"""Copy the item at rel_from to the location at rel_to"""
211
raise TransportNotPossible('http does not support copy()')
213
def copy_to(self, relpaths, other, pb=None):
214
"""Copy a set of entries from self into another Transport.
216
:param relpaths: A list/generator of entries to be copied.
218
TODO: if other is LocalTransport, is it possible to
219
do better than put(get())?
221
# At this point HttpTransport might be able to check and see if
222
# the remote location is the same, and rather than download, and
223
# then upload, it could just issue a remote copy_this command.
224
if isinstance(other, HttpTransport):
225
raise TransportNotPossible('http cannot be the target of copy_to()')
227
return super(HttpTransport, self).copy_to(relpaths, other, pb=pb)
229
def move(self, rel_from, rel_to):
230
"""Move the item at rel_from to the location at rel_to"""
231
raise TransportNotPossible('http does not support move()')
233
def delete(self, relpath):
234
"""Delete the item at relpath"""
235
raise TransportNotPossible('http does not support delete()')
238
"""See Transport.listable."""
241
def stat(self, relpath):
242
"""Return the stat information for a file.
244
raise TransportNotPossible('http does not support stat()')
246
def lock_read(self, relpath):
247
"""Lock the given file for shared (read) access.
248
:return: A lock object, which should be passed to Transport.unlock()
250
# The old RemoteBranch ignore lock for reading, so we will
251
# continue that tradition and return a bogus lock object.
252
class BogusLock(object):
253
def __init__(self, path):
257
return BogusLock(relpath)
259
def lock_write(self, relpath):
260
"""Lock the given file for exclusive (write) access.
261
WARNING: many transports do not support this, so trying avoid using it
263
:return: A lock object, which should be passed to Transport.unlock()
265
raise TransportNotPossible('http does not support lock_write()')