blob: a8228ebfb4bab2fd8c78b993fde45fe2d10cc958 [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 Rossum442e7201996-03-20 15:33:11 +000023__version__ = '1.3'
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
Jack Jansendc3e3f61995-12-15 13:22:13 +000028else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000029 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000030 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000031 def pathname2url(pathname):
32 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000033
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000034# This really consists of two pieces:
35# (1) a class which handles opening of all sorts of URLs
36# (plus assorted utilities etc.)
37# (2) a set of functions for parsing URLs
38# XXX Should these be separated out into different modules?
39
40
41# Shortcut for basic usage
42_urlopener = None
43def urlopen(url):
44 global _urlopener
45 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000046 _urlopener = FancyURLopener()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000047 return _urlopener.open(url)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000048def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000049 global _urlopener
50 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000051 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000052 if filename:
53 return _urlopener.retrieve(url, filename)
54 else:
55 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000056def urlcleanup():
57 if _urlopener:
58 _urlopener.cleanup()
59
60
61# Class to open URLs.
62# This is a class rather than just a subroutine because we may need
63# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000064# Note -- this is a base class for those who don't want the
65# automatic handling of errors type 302 (relocated) and 401
66# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000067ftpcache = {}
68class URLopener:
69
70 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000071 def __init__(self, proxies=None):
72 if proxies is None:
73 proxies = getproxies()
74 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +000075 server_version = "Python-urllib/%s" % __version__
76 self.addheaders = [('User-agent', server_version)]
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000077 self.tempcache = None
78 # Undocumented feature: if you assign {} to tempcache,
79 # it is used to cache files retrieved with
80 # self.retrieve(). This is not enabled by default
81 # since it does not work for changing documents (and I
82 # haven't got the logic to check expiration headers
83 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000084 self.ftpcache = ftpcache
85 # Undocumented feature: you can use a different
86 # ftp cache by assigning to the .ftpcache member;
87 # in case you want logically independent URL openers
88
89 def __del__(self):
90 self.close()
91
92 def close(self):
93 self.cleanup()
94
95 def cleanup(self):
96 import os
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000097 if self.tempcache:
98 for url in self.tempcache.keys():
99 try:
100 os.unlink(self.tempcache[url][0])
101 except os.error:
102 pass
103 del self.tempcache[url]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000104
105 # Add a header to be used by the HTTP interface only
106 # e.g. u.addheader('Accept', 'sound/basic')
107 def addheader(self, *args):
108 self.addheaders.append(args)
109
110 # External interface
111 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumca445401995-08-29 19:19:12 +0000112 def open(self, fullurl):
113 fullurl = unwrap(fullurl)
114 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000115 if not type: type = 'file'
Guido van Rossum442e7201996-03-20 15:33:11 +0000116 if self.proxies.has_key(type):
117 proxy = self.proxies[type]
118 type, proxy = splittype(proxy)
119 host, selector = splithost(proxy)
120 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000121 name = 'open_' + type
122 if '-' in name:
123 import regsub
124 name = regsub.gsub('-', '_', name)
125 if not hasattr(self, name):
Guido van Rossumca445401995-08-29 19:19:12 +0000126 return self.open_unknown(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000127 try:
128 return getattr(self, name)(url)
129 except socket.error, msg:
130 raise IOError, ('socket error', msg)
131
Guido van Rossumca445401995-08-29 19:19:12 +0000132 # Overridable interface to open unknown URL type
133 def open_unknown(self, fullurl):
134 type, url = splittype(fullurl)
135 raise IOError, ('url error', 'unknown url type', type)
136
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000137 # External interface
138 # retrieve(url) returns (filename, None) for a local object
139 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000140 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000141 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000142 return self.tempcache[url]
143 url1 = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000144 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000145 self.tempcache[url] = self.tempcache[url1]
146 return self.tempcache[url1]
147 type, url1 = splittype(url1)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000148 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000149 try:
150 fp = self.open_local_file(url1)
151 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000152 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000153 except IOError, msg:
154 pass
155 fp = self.open(url)
156 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000157 if not filename:
158 import tempfile
159 filename = tempfile.mktemp()
160 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000161 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000162 self.tempcache[url] = result
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000163 tfp = open(filename, 'w')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000164 bs = 1024*8
165 block = fp.read(bs)
166 while block:
167 tfp.write(block)
168 block = fp.read(bs)
169 del fp
170 del tfp
171 return result
172
173 # Each method named open_<type> knows how to open that type of URL
174
175 # Use HTTP protocol
176 def open_http(self, url):
177 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000178 if type(url) is type(""):
179 host, selector = splithost(url)
180 else:
181 host, selector = url
182 print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000183 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000184 i = string.find(host, '@')
185 if i >= 0:
186 user_passwd, host = host[:i], host[i+1:]
187 else:
188 user_passwd = None
189 if user_passwd:
190 import base64
191 auth = string.strip(base64.encodestring(user_passwd))
192 else:
193 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000194 h = httplib.HTTP(host)
195 h.putrequest('GET', selector)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000196 if auth: h.putheader('Authorization: Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000197 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000198 h.endheaders()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000199 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000200 fp = h.getfile()
201 if errcode == 200:
202 return addinfo(fp, headers)
203 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000204 return self.http_error(url,
205 fp, errcode, errmsg, headers)
206
207 # Handle http errors.
208 # Derived class can override this, or provide specific handlers
209 # named http_error_DDD where DDD is the 3-digit error code
210 def http_error(self, url, fp, errcode, errmsg, headers):
211 # First check if there's a specific handler for this error
212 name = 'http_error_%d' % errcode
213 if hasattr(self, name):
214 method = getattr(self, name)
215 result = method(url, fp, errcode, errmsg, headers)
216 if result: return result
217 return self.http_error_default(
218 url, fp, errcode, errmsg, headers)
219
220 # Default http error handler: close the connection and raises IOError
221 def http_error_default(self, url, fp, errcode, errmsg, headers):
222 void = fp.read()
223 fp.close()
224 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000225
226 # Use Gopher protocol
227 def open_gopher(self, url):
228 import gopherlib
229 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000230 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000231 type, selector = splitgophertype(selector)
232 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000233 selector = unquote(selector)
234 if query:
235 query = unquote(query)
236 fp = gopherlib.send_query(selector, query, host)
237 else:
238 fp = gopherlib.send_selector(selector, host)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000239 return addinfo(fp, noheaders())
240
241 # Use local file or FTP depending on form of URL
242 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000243 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000244 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000245 else:
246 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000247
248 # Use local file
249 def open_local_file(self, url):
250 host, file = splithost(url)
Jack Jansene8ea21b1995-12-21 15:43:53 +0000251 if not host: return addinfo(open(url2pathname(file), 'r'), noheaders())
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000252 host, port = splitport(host)
253 if not port and socket.gethostbyname(host) in (
254 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000255 file = unquote(file)
Jack Jansene8ea21b1995-12-21 15:43:53 +0000256 return addinfo(open(url2pathname(file), 'r'), noheaders())
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000257 raise IOError, ('local file error', 'not on local host')
258
259 # Use FTP protocol
260 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000261 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000262 if not host: raise IOError, ('ftp error', 'no host given')
263 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000264 user, host = splituser(host)
265 if user: user, passwd = splitpasswd(user)
266 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000267 host = socket.gethostbyname(host)
268 if not port:
269 import ftplib
270 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000271 path, attrs = splitattr(path)
272 dirs = string.splitfields(path, '/')
273 dirs, file = dirs[:-1], dirs[-1]
274 if dirs and not dirs[0]: dirs = dirs[1:]
275 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000276 try:
277 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000278 self.ftpcache[key] = \
279 ftpwrapper(user, passwd,
280 host, port, dirs)
281 if not file: type = 'D'
282 else: type = 'I'
283 for attr in attrs:
284 attr, value = splitvalue(attr)
285 if string.lower(attr) == 'type' and \
286 value in ('a', 'A', 'i', 'I', 'd', 'D'):
287 type = string.upper(value)
288 return addinfo(self.ftpcache[key].retrfile(file, type),
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000289 noheaders())
290 except ftperrors(), msg:
291 raise IOError, ('ftp error', msg)
292
293
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000294# Derived class with handlers for errors we can handle (perhaps)
295class FancyURLopener(URLopener):
296
297 def __init__(self, *args):
298 apply(URLopener.__init__, (self,) + args)
299 self.auth_cache = {}
300
301 # Default error handling -- don't raise an exception
302 def http_error_default(self, url, fp, errcode, errmsg, headers):
303 return addinfo(fp, headers)
304
305 # Error 302 -- relocated
306 def http_error_302(self, url, fp, errcode, errmsg, headers):
307 # XXX The server can force infinite recursion here!
308 if headers.has_key('location'):
309 newurl = headers['location']
310 elif headers.has_key('uri'):
311 newurl = headers['uri']
312 else:
313 return
314 void = fp.read()
315 fp.close()
316 return self.open(newurl)
317
318 # Error 401 -- authentication required
319 # See this URL for a description of the basic authentication scheme:
320 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
321 def http_error_401(self, url, fp, errcode, errmsg, headers):
322 if headers.has_key('www-authenticate'):
323 stuff = headers['www-authenticate']
324 p = regex.compile(
325 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
326 if p.match(stuff) >= 0:
327 scheme, realm = p.group(1, 2)
328 if string.lower(scheme) == 'basic':
329 return self.retry_http_basic_auth(
330 url, realm)
331
332 def retry_http_basic_auth(self, url, realm):
333 host, selector = splithost(url)
334 i = string.find(host, '@') + 1
335 host = host[i:]
336 user, passwd = self.get_user_passwd(host, realm, i)
337 if not (user or passwd): return None
338 host = user + ':' + passwd + '@' + host
339 newurl = '//' + host + selector
340 return self.open_http(newurl)
341
342 def get_user_passwd(self, host, realm, clear_cache = 0):
343 key = realm + '@' + string.lower(host)
344 if self.auth_cache.has_key(key):
345 if clear_cache:
346 del self.auth_cache[key]
347 else:
348 return self.auth_cache[key]
349 user, passwd = self.prompt_user_passwd(host, realm)
350 if user or passwd: self.auth_cache[key] = (user, passwd)
351 return user, passwd
352
353 def prompt_user_passwd(self, host, realm):
354 # Override this in a GUI environment!
355 try:
356 user = raw_input("Enter username for %s at %s: " %
357 (realm, host))
358 self.echo_off()
359 try:
360 passwd = raw_input(
361 "Enter password for %s in %s at %s: " %
362 (user, realm, host))
363 finally:
364 self.echo_on()
365 return user, passwd
366 except KeyboardInterrupt:
367 return None, None
368
369 def echo_off(self):
370 import os
371 os.system("stty -echo")
372
373 def echo_on(self):
374 import os
375 print
376 os.system("stty echo")
377
378
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000379# Utility functions
380
381# Return the IP address of the magic hostname 'localhost'
382_localhost = None
383def localhost():
384 global _localhost
385 if not _localhost:
386 _localhost = socket.gethostbyname('localhost')
387 return _localhost
388
389# Return the IP address of the current host
390_thishost = None
391def thishost():
392 global _thishost
393 if not _thishost:
394 _thishost = socket.gethostbyname(socket.gethostname())
395 return _thishost
396
397# Return the set of errors raised by the FTP class
398_ftperrors = None
399def ftperrors():
400 global _ftperrors
401 if not _ftperrors:
402 import ftplib
403 _ftperrors = (ftplib.error_reply,
404 ftplib.error_temp,
405 ftplib.error_perm,
406 ftplib.error_proto)
407 return _ftperrors
408
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000409# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000410_noheaders = None
411def noheaders():
412 global _noheaders
413 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000414 import mimetools
415 import StringIO
416 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000417 _noheaders.fp.close() # Recycle file descriptor
418 return _noheaders
419
420
421# Utility classes
422
423# Class used by open_ftp() for cache of open FTP connections
424class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000425 def __init__(self, user, passwd, host, port, dirs):
426 self.user = unquote(user or '')
427 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000428 self.host = host
429 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000430 self.dirs = []
431 for dir in dirs:
432 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000433 self.init()
434 def init(self):
435 import ftplib
436 self.ftp = ftplib.FTP()
437 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000438 self.ftp.login(self.user, self.passwd)
439 for dir in self.dirs:
440 self.ftp.cwd(dir)
441 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000442 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000443 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
444 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000445 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000446 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000447 except ftplib.all_errors:
448 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000449 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000450 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000451 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000452 try:
453 cmd = 'RETR ' + file
454 conn = self.ftp.transfercmd(cmd)
455 except ftplib.error_perm, reason:
456 if reason[:3] != '550':
457 raise IOError, ('ftp error', reason)
458 if not conn:
459 # Try a directory listing
460 if file: cmd = 'LIST ' + file
461 else: cmd = 'LIST'
462 conn = self.ftp.transfercmd(cmd)
Jack Jansen0d12ead1996-02-14 16:05:20 +0000463 return addclosehook(conn.makefile('rb'), self.ftp.voidresp)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000464
465# Base class for addinfo and addclosehook
466class addbase:
467 def __init__(self, fp):
468 self.fp = fp
469 self.read = self.fp.read
470 self.readline = self.fp.readline
471 self.readlines = self.fp.readlines
472 self.fileno = self.fp.fileno
473 def __repr__(self):
474 return '<%s at %s whose fp = %s>' % (
475 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000476 def close(self):
477 self.read = None
478 self.readline = None
479 self.readlines = None
480 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000481 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000482 self.fp = None
483
484# Class to add a close hook to an open file
485class addclosehook(addbase):
486 def __init__(self, fp, closehook, *hookargs):
487 addbase.__init__(self, fp)
488 self.closehook = closehook
489 self.hookargs = hookargs
490 def close(self):
491 if self.closehook:
492 apply(self.closehook, self.hookargs)
493 self.closehook = None
494 self.hookargs = None
495 addbase.close(self)
496
497# class to add an info() method to an open file
498class addinfo(addbase):
499 def __init__(self, fp, headers):
500 addbase.__init__(self, fp)
501 self.headers = headers
502 def info(self):
503 return self.headers
504
505
506# Utility to combine a URL with a base URL to form a new URL
507
508def basejoin(base, url):
509 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000510 if type:
511 # if url is complete (i.e., it contains a type), return it
512 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000513 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000514 type, basepath = splittype(base) # inherit type from base
515 if host:
516 # if url contains host, just inherit type
517 if type: return type + '://' + host + path
518 else:
519 # no type inherited, so url must have started with //
520 # just return it
521 return url
522 host, basepath = splithost(basepath) # inherit host
523 basepath, basetag = splittag(basepath) # remove extraneuous cruft
524 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000525 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000526 # non-absolute path name
527 if path[:1] in ('#', '?'):
528 # path is just a tag or query, attach to basepath
529 i = len(basepath)
530 else:
531 # else replace last component
532 i = string.rfind(basepath, '/')
533 if i < 0:
534 # basepath not absolute
535 if host:
536 # host present, make absolute
537 basepath = '/'
538 else:
539 # else keep non-absolute
540 basepath = ''
541 else:
542 # remove last file component
543 basepath = basepath[:i+1]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000544 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000545 if type and host: return type + '://' + host + path
546 elif type: return type + ':' + path
547 elif host: return '//' + host + path # don't know what this means
548 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000549
550
Guido van Rossum7c395db1994-07-04 22:14:49 +0000551# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000552# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000553# splittype('type:opaquestring') --> 'type', 'opaquestring'
554# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000555# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
556# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000557# splitport('host:port') --> 'host', 'port'
558# splitquery('/path?query') --> '/path', 'query'
559# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000560# splitattr('/path;attr1=value1;attr2=value2;...') ->
561# '/path', ['attr1=value1', 'attr2=value2', ...]
562# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000563# splitgophertype('/Xselector') --> 'X', 'selector'
564# unquote('abc%20def') -> 'abc def'
565# quote('abc def') -> 'abc%20def')
566
567def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000568 url = string.strip(url)
569 if url[:1] == '<' and url[-1:] == '>':
570 url = string.strip(url[1:-1])
571 if url[:4] == 'URL:': url = string.strip(url[4:])
572 return url
573
574_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
575def splittype(url):
576 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
577 return None, url
578
579_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
580def splithost(url):
581 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
582 return None, url
583
Guido van Rossum7c395db1994-07-04 22:14:49 +0000584_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
585def splituser(host):
586 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
587 return None, host
588
589_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
590def splitpasswd(user):
591 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
592 return user, None
593
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000594_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
595def splitport(host):
596 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
597 return host, None
598
Guido van Rossum53725a21996-06-13 19:12:35 +0000599# Split host and port, returning numeric port.
600# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000601# Return numerical port if a valid number are found after ':'.
602# Return None if ':' but not a valid number.
603_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000604def splitnport(host, defport=-1):
605 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000606 host, port = _nportprog.group(1, 2)
607 try:
608 if not port: raise string.atoi_error, "no digits"
609 nport = string.atoi(port)
610 except string.atoi_error:
611 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000612 return host, nport
613 return host, defport
614
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000615_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
616def splitquery(url):
617 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
618 return url, None
619
620_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
621def splittag(url):
622 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
623 return url, None
624
Guido van Rossum7c395db1994-07-04 22:14:49 +0000625def splitattr(url):
626 words = string.splitfields(url, ';')
627 return words[0], words[1:]
628
629_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
630def splitvalue(attr):
631 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
632 return attr, None
633
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000634def splitgophertype(selector):
635 if selector[:1] == '/' and selector[1:2]:
636 return selector[1], selector[2:]
637 return None, selector
638
639_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
640def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000641 i = 0
642 n = len(s)
643 res = ''
644 while 0 <= i < n:
645 j = _quoteprog.search(s, i)
646 if j < 0:
647 res = res + s[i:]
648 break
Guido van Rossum8c8a02a1996-01-26 17:41:44 +0000649 res = res + (s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000650 i = j+3
651 return res
652
Guido van Rossum3bb54481994-08-29 10:52:58 +0000653always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000654def quote(s, safe = '/'):
655 safe = always_safe + safe
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000656 res = ''
657 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000658 if c in safe:
659 res = res + c
660 else:
661 res = res + '%%%02x' % ord(c)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000662 return res
663
Guido van Rossum442e7201996-03-20 15:33:11 +0000664
665# Proxy handling
666def getproxies():
667 """Return a dictionary of protocol scheme -> proxy server URL mappings.
668
669 Scan the environment for variables named <scheme>_proxy;
670 this seems to be the standard convention. If you need a
671 different way, you can pass a proxies dictionary to the
672 [Fancy]URLopener constructor.
673
674 """
675 proxies = {}
676 for name, value in os.environ.items():
677 if value and name[-6:] == '_proxy':
678 proxies[name[:-6]] = value
679 return proxies
680
681
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000682# Test and time quote() and unquote()
683def test1():
684 import time
685 s = ''
686 for i in range(256): s = s + chr(i)
687 s = s*4
688 t0 = time.time()
689 qs = quote(s)
690 uqs = unquote(qs)
691 t1 = time.time()
692 if uqs != s:
693 print 'Wrong!'
694 print `s`
695 print `qs`
696 print `uqs`
697 print round(t1 - t0, 3), 'sec'
698
699
700# Test program
701def test():
702 import sys
703 import regsub
704 args = sys.argv[1:]
705 if not args:
706 args = [
707 '/etc/passwd',
708 'file:/etc/passwd',
709 'file://localhost/etc/passwd',
710 'ftp://ftp.cwi.nl/etc/passwd',
711 'gopher://gopher.cwi.nl/11/',
712 'http://www.cwi.nl/index.html',
713 ]
714 try:
715 for url in args:
716 print '-'*10, url, '-'*10
717 fn, h = urlretrieve(url)
718 print fn, h
719 if h:
720 print '======'
721 for k in h.keys(): print k + ':', h[k]
722 print '======'
723 fp = open(fn, 'r')
724 data = fp.read()
725 del fp
726 print regsub.gsub('\r', '', data)
727 fn, h = None, None
728 print '-'*40
729 finally:
730 urlcleanup()
731
732# Run test program when run as a script
733if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000734## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000735 test()