blob: 621785f688cde4b5b5cb203d4e2169d0948b19f3 [file] [log] [blame]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001# Open an arbitrary URL
2#
3# See the following document for a tentative description of URLs:
4# Uniform Resource Locators Tim Berners-Lee
5# INTERNET DRAFT CERN
6# IETF URL Working Group 14 July 1993
7# draft-ietf-uri-url-01.txt
8#
9# The object returned by URLopener().open(file) will differ per
10# protocol. All you know is that is has methods read(), readline(),
11# readlines(), fileno(), close() and info(). The read*(), fileno()
12# and close() methods work like those of open files.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000013# The info() method returns an mimetools.Message object which can be
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000014# used to query various info about the object, if available.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000015# (mimetools.Message objects are queried with the getheader() method.)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000016
Guido van Rossum7c395db1994-07-04 22:14:49 +000017import string
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000018import socket
19import regex
Jack Jansendc3e3f61995-12-15 13:22:13 +000020import os
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000021
22
Guido van Rossum78c96371996-08-26 18:09:59 +000023__version__ = '1.4'
Guido van Rossum6cb15a01995-06-22 19:00:13 +000024
Jack Jansendc3e3f61995-12-15 13:22:13 +000025# Helper for non-unix systems
26if os.name == 'mac':
Guido van Rossum71ac9451996-03-21 16:31:41 +000027 from macurl2path import url2pathname, pathname2url
Guido van Rossum2281d351996-06-26 19:47:37 +000028elif os.name == 'nt':
29 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000030else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000031 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000032 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000033 def pathname2url(pathname):
34 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000035
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000036# This really consists of two pieces:
37# (1) a class which handles opening of all sorts of URLs
38# (plus assorted utilities etc.)
39# (2) a set of functions for parsing URLs
40# XXX Should these be separated out into different modules?
41
42
43# Shortcut for basic usage
44_urlopener = None
45def urlopen(url):
46 global _urlopener
47 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000048 _urlopener = FancyURLopener()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000049 return _urlopener.open(url)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000050def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000051 global _urlopener
52 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000053 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000054 if filename:
55 return _urlopener.retrieve(url, filename)
56 else:
57 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000058def urlcleanup():
59 if _urlopener:
60 _urlopener.cleanup()
61
62
63# Class to open URLs.
64# This is a class rather than just a subroutine because we may need
65# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000066# Note -- this is a base class for those who don't want the
67# automatic handling of errors type 302 (relocated) and 401
68# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000069ftpcache = {}
70class URLopener:
71
72 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000073 def __init__(self, proxies=None):
74 if proxies is None:
75 proxies = getproxies()
76 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +000077 server_version = "Python-urllib/%s" % __version__
78 self.addheaders = [('User-agent', server_version)]
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000079 self.tempcache = None
80 # Undocumented feature: if you assign {} to tempcache,
81 # it is used to cache files retrieved with
82 # self.retrieve(). This is not enabled by default
83 # since it does not work for changing documents (and I
84 # haven't got the logic to check expiration headers
85 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000086 self.ftpcache = ftpcache
87 # Undocumented feature: you can use a different
88 # ftp cache by assigning to the .ftpcache member;
89 # in case you want logically independent URL openers
90
91 def __del__(self):
92 self.close()
93
94 def close(self):
95 self.cleanup()
96
97 def cleanup(self):
98 import os
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000099 if self.tempcache:
100 for url in self.tempcache.keys():
101 try:
102 os.unlink(self.tempcache[url][0])
103 except os.error:
104 pass
105 del self.tempcache[url]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000106
107 # Add a header to be used by the HTTP interface only
108 # e.g. u.addheader('Accept', 'sound/basic')
109 def addheader(self, *args):
110 self.addheaders.append(args)
111
112 # External interface
113 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumca445401995-08-29 19:19:12 +0000114 def open(self, fullurl):
115 fullurl = unwrap(fullurl)
116 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000117 if not type: type = 'file'
Guido van Rossum442e7201996-03-20 15:33:11 +0000118 if self.proxies.has_key(type):
119 proxy = self.proxies[type]
120 type, proxy = splittype(proxy)
121 host, selector = splithost(proxy)
122 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000123 name = 'open_' + type
124 if '-' in name:
125 import regsub
126 name = regsub.gsub('-', '_', name)
127 if not hasattr(self, name):
Guido van Rossumca445401995-08-29 19:19:12 +0000128 return self.open_unknown(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000129 try:
130 return getattr(self, name)(url)
131 except socket.error, msg:
132 raise IOError, ('socket error', msg)
133
Guido van Rossumca445401995-08-29 19:19:12 +0000134 # Overridable interface to open unknown URL type
135 def open_unknown(self, fullurl):
136 type, url = splittype(fullurl)
137 raise IOError, ('url error', 'unknown url type', type)
138
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000139 # External interface
140 # retrieve(url) returns (filename, None) for a local object
141 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000142 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000143 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000144 return self.tempcache[url]
145 url1 = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000146 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000147 self.tempcache[url] = self.tempcache[url1]
148 return self.tempcache[url1]
149 type, url1 = splittype(url1)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000150 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000151 try:
152 fp = self.open_local_file(url1)
153 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000154 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000155 except IOError, msg:
156 pass
157 fp = self.open(url)
158 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000159 if not filename:
160 import tempfile
161 filename = tempfile.mktemp()
162 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000163 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000164 self.tempcache[url] = result
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000165 tfp = open(filename, 'w')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000166 bs = 1024*8
167 block = fp.read(bs)
168 while block:
169 tfp.write(block)
170 block = fp.read(bs)
171 del fp
172 del tfp
173 return result
174
175 # Each method named open_<type> knows how to open that type of URL
176
177 # Use HTTP protocol
178 def open_http(self, url):
179 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000180 if type(url) is type(""):
181 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000182 user_passwd, host = splituser(host)
Guido van Rossum442e7201996-03-20 15:33:11 +0000183 else:
184 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000185 urltype, rest = splittype(selector)
186 if string.lower(urltype) == 'http':
187 realhost, rest = splithost(rest)
188 user_passwd, realhost = splituser(realhost)
189 if user_passwd:
190 selector = "%s://%s%s" % (urltype,
191 realhost, rest)
Guido van Rossum442e7201996-03-20 15:33:11 +0000192 print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000193 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000194 if user_passwd:
195 import base64
196 auth = string.strip(base64.encodestring(user_passwd))
197 else:
198 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000199 h = httplib.HTTP(host)
200 h.putrequest('GET', selector)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000201 if auth: h.putheader('Authorization: Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000202 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000203 h.endheaders()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000204 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000205 fp = h.getfile()
206 if errcode == 200:
207 return addinfo(fp, headers)
208 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000209 return self.http_error(url,
210 fp, errcode, errmsg, headers)
211
212 # Handle http errors.
213 # Derived class can override this, or provide specific handlers
214 # named http_error_DDD where DDD is the 3-digit error code
215 def http_error(self, url, fp, errcode, errmsg, headers):
216 # First check if there's a specific handler for this error
217 name = 'http_error_%d' % errcode
218 if hasattr(self, name):
219 method = getattr(self, name)
220 result = method(url, fp, errcode, errmsg, headers)
221 if result: return result
222 return self.http_error_default(
223 url, fp, errcode, errmsg, headers)
224
225 # Default http error handler: close the connection and raises IOError
226 def http_error_default(self, url, fp, errcode, errmsg, headers):
227 void = fp.read()
228 fp.close()
229 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000230
231 # Use Gopher protocol
232 def open_gopher(self, url):
233 import gopherlib
234 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000235 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000236 type, selector = splitgophertype(selector)
237 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000238 selector = unquote(selector)
239 if query:
240 query = unquote(query)
241 fp = gopherlib.send_query(selector, query, host)
242 else:
243 fp = gopherlib.send_selector(selector, host)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000244 return addinfo(fp, noheaders())
245
246 # Use local file or FTP depending on form of URL
247 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000248 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000249 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000250 else:
251 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000252
253 # Use local file
254 def open_local_file(self, url):
255 host, file = splithost(url)
Jack Jansene8ea21b1995-12-21 15:43:53 +0000256 if not host: return addinfo(open(url2pathname(file), 'r'), noheaders())
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000257 host, port = splitport(host)
258 if not port and socket.gethostbyname(host) in (
259 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000260 file = unquote(file)
Jack Jansene8ea21b1995-12-21 15:43:53 +0000261 return addinfo(open(url2pathname(file), 'r'), noheaders())
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000262 raise IOError, ('local file error', 'not on local host')
263
264 # Use FTP protocol
265 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000266 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000267 if not host: raise IOError, ('ftp error', 'no host given')
268 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000269 user, host = splituser(host)
270 if user: user, passwd = splitpasswd(user)
271 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000272 host = socket.gethostbyname(host)
273 if not port:
274 import ftplib
275 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000276 path, attrs = splitattr(path)
277 dirs = string.splitfields(path, '/')
278 dirs, file = dirs[:-1], dirs[-1]
279 if dirs and not dirs[0]: dirs = dirs[1:]
280 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000281 try:
282 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000283 self.ftpcache[key] = \
284 ftpwrapper(user, passwd,
285 host, port, dirs)
286 if not file: type = 'D'
287 else: type = 'I'
288 for attr in attrs:
289 attr, value = splitvalue(attr)
290 if string.lower(attr) == 'type' and \
291 value in ('a', 'A', 'i', 'I', 'd', 'D'):
292 type = string.upper(value)
293 return addinfo(self.ftpcache[key].retrfile(file, type),
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000294 noheaders())
295 except ftperrors(), msg:
296 raise IOError, ('ftp error', msg)
297
298
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000299# Derived class with handlers for errors we can handle (perhaps)
300class FancyURLopener(URLopener):
301
302 def __init__(self, *args):
303 apply(URLopener.__init__, (self,) + args)
304 self.auth_cache = {}
305
306 # Default error handling -- don't raise an exception
307 def http_error_default(self, url, fp, errcode, errmsg, headers):
308 return addinfo(fp, headers)
309
310 # Error 302 -- relocated
311 def http_error_302(self, url, fp, errcode, errmsg, headers):
312 # XXX The server can force infinite recursion here!
313 if headers.has_key('location'):
314 newurl = headers['location']
315 elif headers.has_key('uri'):
316 newurl = headers['uri']
317 else:
318 return
319 void = fp.read()
320 fp.close()
321 return self.open(newurl)
322
323 # Error 401 -- authentication required
324 # See this URL for a description of the basic authentication scheme:
325 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
326 def http_error_401(self, url, fp, errcode, errmsg, headers):
327 if headers.has_key('www-authenticate'):
328 stuff = headers['www-authenticate']
329 p = regex.compile(
330 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
331 if p.match(stuff) >= 0:
332 scheme, realm = p.group(1, 2)
333 if string.lower(scheme) == 'basic':
334 return self.retry_http_basic_auth(
335 url, realm)
336
337 def retry_http_basic_auth(self, url, realm):
338 host, selector = splithost(url)
339 i = string.find(host, '@') + 1
340 host = host[i:]
341 user, passwd = self.get_user_passwd(host, realm, i)
342 if not (user or passwd): return None
343 host = user + ':' + passwd + '@' + host
344 newurl = '//' + host + selector
345 return self.open_http(newurl)
346
347 def get_user_passwd(self, host, realm, clear_cache = 0):
348 key = realm + '@' + string.lower(host)
349 if self.auth_cache.has_key(key):
350 if clear_cache:
351 del self.auth_cache[key]
352 else:
353 return self.auth_cache[key]
354 user, passwd = self.prompt_user_passwd(host, realm)
355 if user or passwd: self.auth_cache[key] = (user, passwd)
356 return user, passwd
357
358 def prompt_user_passwd(self, host, realm):
359 # Override this in a GUI environment!
360 try:
361 user = raw_input("Enter username for %s at %s: " %
362 (realm, host))
363 self.echo_off()
364 try:
365 passwd = raw_input(
366 "Enter password for %s in %s at %s: " %
367 (user, realm, host))
368 finally:
369 self.echo_on()
370 return user, passwd
371 except KeyboardInterrupt:
372 return None, None
373
374 def echo_off(self):
375 import os
376 os.system("stty -echo")
377
378 def echo_on(self):
379 import os
380 print
381 os.system("stty echo")
382
383
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000384# Utility functions
385
386# Return the IP address of the magic hostname 'localhost'
387_localhost = None
388def localhost():
389 global _localhost
390 if not _localhost:
391 _localhost = socket.gethostbyname('localhost')
392 return _localhost
393
394# Return the IP address of the current host
395_thishost = None
396def thishost():
397 global _thishost
398 if not _thishost:
399 _thishost = socket.gethostbyname(socket.gethostname())
400 return _thishost
401
402# Return the set of errors raised by the FTP class
403_ftperrors = None
404def ftperrors():
405 global _ftperrors
406 if not _ftperrors:
407 import ftplib
408 _ftperrors = (ftplib.error_reply,
409 ftplib.error_temp,
410 ftplib.error_perm,
411 ftplib.error_proto)
412 return _ftperrors
413
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000414# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000415_noheaders = None
416def noheaders():
417 global _noheaders
418 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000419 import mimetools
420 import StringIO
421 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000422 _noheaders.fp.close() # Recycle file descriptor
423 return _noheaders
424
425
426# Utility classes
427
428# Class used by open_ftp() for cache of open FTP connections
429class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000430 def __init__(self, user, passwd, host, port, dirs):
431 self.user = unquote(user or '')
432 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000433 self.host = host
434 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000435 self.dirs = []
436 for dir in dirs:
437 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000438 self.init()
439 def init(self):
440 import ftplib
441 self.ftp = ftplib.FTP()
442 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000443 self.ftp.login(self.user, self.passwd)
444 for dir in self.dirs:
445 self.ftp.cwd(dir)
446 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000447 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000448 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
449 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000450 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000451 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000452 except ftplib.all_errors:
453 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000454 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000455 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000456 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000457 try:
458 cmd = 'RETR ' + file
459 conn = self.ftp.transfercmd(cmd)
460 except ftplib.error_perm, reason:
461 if reason[:3] != '550':
462 raise IOError, ('ftp error', reason)
463 if not conn:
464 # Try a directory listing
465 if file: cmd = 'LIST ' + file
466 else: cmd = 'LIST'
467 conn = self.ftp.transfercmd(cmd)
Jack Jansen0d12ead1996-02-14 16:05:20 +0000468 return addclosehook(conn.makefile('rb'), self.ftp.voidresp)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000469
470# Base class for addinfo and addclosehook
471class addbase:
472 def __init__(self, fp):
473 self.fp = fp
474 self.read = self.fp.read
475 self.readline = self.fp.readline
476 self.readlines = self.fp.readlines
477 self.fileno = self.fp.fileno
478 def __repr__(self):
479 return '<%s at %s whose fp = %s>' % (
480 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000481 def close(self):
482 self.read = None
483 self.readline = None
484 self.readlines = None
485 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000486 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000487 self.fp = None
488
489# Class to add a close hook to an open file
490class addclosehook(addbase):
491 def __init__(self, fp, closehook, *hookargs):
492 addbase.__init__(self, fp)
493 self.closehook = closehook
494 self.hookargs = hookargs
495 def close(self):
496 if self.closehook:
497 apply(self.closehook, self.hookargs)
498 self.closehook = None
499 self.hookargs = None
500 addbase.close(self)
501
502# class to add an info() method to an open file
503class addinfo(addbase):
504 def __init__(self, fp, headers):
505 addbase.__init__(self, fp)
506 self.headers = headers
507 def info(self):
508 return self.headers
509
510
511# Utility to combine a URL with a base URL to form a new URL
512
513def basejoin(base, url):
514 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000515 if type:
516 # if url is complete (i.e., it contains a type), return it
517 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000518 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000519 type, basepath = splittype(base) # inherit type from base
520 if host:
521 # if url contains host, just inherit type
522 if type: return type + '://' + host + path
523 else:
524 # no type inherited, so url must have started with //
525 # just return it
526 return url
527 host, basepath = splithost(basepath) # inherit host
528 basepath, basetag = splittag(basepath) # remove extraneuous cruft
529 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000530 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000531 # non-absolute path name
532 if path[:1] in ('#', '?'):
533 # path is just a tag or query, attach to basepath
534 i = len(basepath)
535 else:
536 # else replace last component
537 i = string.rfind(basepath, '/')
538 if i < 0:
539 # basepath not absolute
540 if host:
541 # host present, make absolute
542 basepath = '/'
543 else:
544 # else keep non-absolute
545 basepath = ''
546 else:
547 # remove last file component
548 basepath = basepath[:i+1]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000549 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000550 if type and host: return type + '://' + host + path
551 elif type: return type + ':' + path
552 elif host: return '//' + host + path # don't know what this means
553 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000554
555
Guido van Rossum7c395db1994-07-04 22:14:49 +0000556# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000557# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000558# splittype('type:opaquestring') --> 'type', 'opaquestring'
559# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000560# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
561# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000562# splitport('host:port') --> 'host', 'port'
563# splitquery('/path?query') --> '/path', 'query'
564# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000565# splitattr('/path;attr1=value1;attr2=value2;...') ->
566# '/path', ['attr1=value1', 'attr2=value2', ...]
567# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000568# splitgophertype('/Xselector') --> 'X', 'selector'
569# unquote('abc%20def') -> 'abc def'
570# quote('abc def') -> 'abc%20def')
571
572def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000573 url = string.strip(url)
574 if url[:1] == '<' and url[-1:] == '>':
575 url = string.strip(url[1:-1])
576 if url[:4] == 'URL:': url = string.strip(url[4:])
577 return url
578
579_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
580def splittype(url):
581 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
582 return None, url
583
584_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
585def splithost(url):
586 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
587 return None, url
588
Guido van Rossum7c395db1994-07-04 22:14:49 +0000589_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
590def splituser(host):
591 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
592 return None, host
593
594_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
595def splitpasswd(user):
596 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
597 return user, None
598
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000599_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
600def splitport(host):
601 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
602 return host, None
603
Guido van Rossum53725a21996-06-13 19:12:35 +0000604# Split host and port, returning numeric port.
605# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000606# Return numerical port if a valid number are found after ':'.
607# Return None if ':' but not a valid number.
608_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000609def splitnport(host, defport=-1):
610 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000611 host, port = _nportprog.group(1, 2)
612 try:
613 if not port: raise string.atoi_error, "no digits"
614 nport = string.atoi(port)
615 except string.atoi_error:
616 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000617 return host, nport
618 return host, defport
619
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000620_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
621def splitquery(url):
622 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
623 return url, None
624
625_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
626def splittag(url):
627 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
628 return url, None
629
Guido van Rossum7c395db1994-07-04 22:14:49 +0000630def splitattr(url):
631 words = string.splitfields(url, ';')
632 return words[0], words[1:]
633
634_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
635def splitvalue(attr):
636 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
637 return attr, None
638
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000639def splitgophertype(selector):
640 if selector[:1] == '/' and selector[1:2]:
641 return selector[1], selector[2:]
642 return None, selector
643
644_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
645def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000646 i = 0
647 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000648 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000649 while 0 <= i < n:
650 j = _quoteprog.search(s, i)
651 if j < 0:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000652 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000653 break
Guido van Rossumf8abb381996-08-26 15:56:12 +0000654 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000655 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000656 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000657
Guido van Rossum3bb54481994-08-29 10:52:58 +0000658always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000659def quote(s, safe = '/'):
660 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000661 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000662 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000663 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000664 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000665 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000666 res.append('%%%02x' % ord(c))
667 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000668
Guido van Rossum442e7201996-03-20 15:33:11 +0000669
670# Proxy handling
671def getproxies():
672 """Return a dictionary of protocol scheme -> proxy server URL mappings.
673
674 Scan the environment for variables named <scheme>_proxy;
675 this seems to be the standard convention. If you need a
676 different way, you can pass a proxies dictionary to the
677 [Fancy]URLopener constructor.
678
679 """
680 proxies = {}
681 for name, value in os.environ.items():
682 if value and name[-6:] == '_proxy':
683 proxies[name[:-6]] = value
684 return proxies
685
686
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000687# Test and time quote() and unquote()
688def test1():
689 import time
690 s = ''
691 for i in range(256): s = s + chr(i)
692 s = s*4
693 t0 = time.time()
694 qs = quote(s)
695 uqs = unquote(qs)
696 t1 = time.time()
697 if uqs != s:
698 print 'Wrong!'
699 print `s`
700 print `qs`
701 print `uqs`
702 print round(t1 - t0, 3), 'sec'
703
704
705# Test program
706def test():
707 import sys
708 import regsub
709 args = sys.argv[1:]
710 if not args:
711 args = [
712 '/etc/passwd',
713 'file:/etc/passwd',
714 'file://localhost/etc/passwd',
715 'ftp://ftp.cwi.nl/etc/passwd',
716 'gopher://gopher.cwi.nl/11/',
717 'http://www.cwi.nl/index.html',
718 ]
719 try:
720 for url in args:
721 print '-'*10, url, '-'*10
722 fn, h = urlretrieve(url)
723 print fn, h
724 if h:
725 print '======'
726 for k in h.keys(): print k + ':', h[k]
727 print '======'
728 fp = open(fn, 'r')
729 data = fp.read()
730 del fp
731 print regsub.gsub('\r', '', data)
732 fn, h = None, None
733 print '-'*40
734 finally:
735 urlcleanup()
736
737# Run test program when run as a script
738if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000739## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000740 test()