blob: 7b5ed6b3594402d6fb2100494f8cb34d6a663fa3 [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 Rossume6ad8911996-09-10 17:02:56 +000023__version__ = '1.5'
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 Rossume6ad8911996-09-10 17:02:56 +0000118 self.openedurl = '%s:%s' % (type, url)
Guido van Rossum442e7201996-03-20 15:33:11 +0000119 if self.proxies.has_key(type):
120 proxy = self.proxies[type]
121 type, proxy = splittype(proxy)
122 host, selector = splithost(proxy)
123 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000124 name = 'open_' + type
125 if '-' in name:
126 import regsub
127 name = regsub.gsub('-', '_', name)
128 if not hasattr(self, name):
Guido van Rossumca445401995-08-29 19:19:12 +0000129 return self.open_unknown(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000130 try:
131 return getattr(self, name)(url)
132 except socket.error, msg:
133 raise IOError, ('socket error', msg)
134
Guido van Rossumca445401995-08-29 19:19:12 +0000135 # Overridable interface to open unknown URL type
136 def open_unknown(self, fullurl):
137 type, url = splittype(fullurl)
138 raise IOError, ('url error', 'unknown url type', type)
139
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000140 # External interface
141 # retrieve(url) returns (filename, None) for a local object
142 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000143 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000144 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000145 return self.tempcache[url]
146 url1 = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000147 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000148 self.tempcache[url] = self.tempcache[url1]
149 return self.tempcache[url1]
150 type, url1 = splittype(url1)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000151 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000152 try:
153 fp = self.open_local_file(url1)
154 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000155 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000156 except IOError, msg:
157 pass
158 fp = self.open(url)
159 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000160 if not filename:
161 import tempfile
162 filename = tempfile.mktemp()
163 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000164 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000165 self.tempcache[url] = result
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000166 tfp = open(filename, 'w')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000167 bs = 1024*8
168 block = fp.read(bs)
169 while block:
170 tfp.write(block)
171 block = fp.read(bs)
172 del fp
173 del tfp
174 return result
175
176 # Each method named open_<type> knows how to open that type of URL
177
178 # Use HTTP protocol
179 def open_http(self, url):
180 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000181 if type(url) is type(""):
182 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000183 user_passwd, host = splituser(host)
Guido van Rossum442e7201996-03-20 15:33:11 +0000184 else:
185 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000186 urltype, rest = splittype(selector)
187 if string.lower(urltype) == 'http':
188 realhost, rest = splithost(rest)
189 user_passwd, realhost = splituser(realhost)
190 if user_passwd:
191 selector = "%s://%s%s" % (urltype,
192 realhost, rest)
Guido van Rossum442e7201996-03-20 15:33:11 +0000193 print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000194 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000195 if user_passwd:
196 import base64
197 auth = string.strip(base64.encodestring(user_passwd))
198 else:
199 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000200 h = httplib.HTTP(host)
201 h.putrequest('GET', selector)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000202 if auth: h.putheader('Authorization: Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000203 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000204 h.endheaders()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000205 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000206 fp = h.getfile()
207 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000208 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000209 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000210 return self.http_error(url,
211 fp, errcode, errmsg, headers)
212
213 # Handle http errors.
214 # Derived class can override this, or provide specific handlers
215 # named http_error_DDD where DDD is the 3-digit error code
216 def http_error(self, url, fp, errcode, errmsg, headers):
217 # First check if there's a specific handler for this error
218 name = 'http_error_%d' % errcode
219 if hasattr(self, name):
220 method = getattr(self, name)
221 result = method(url, fp, errcode, errmsg, headers)
222 if result: return result
223 return self.http_error_default(
224 url, fp, errcode, errmsg, headers)
225
226 # Default http error handler: close the connection and raises IOError
227 def http_error_default(self, url, fp, errcode, errmsg, headers):
228 void = fp.read()
229 fp.close()
230 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000231
232 # Use Gopher protocol
233 def open_gopher(self, url):
234 import gopherlib
235 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000236 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000237 type, selector = splitgophertype(selector)
238 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000239 selector = unquote(selector)
240 if query:
241 query = unquote(query)
242 fp = gopherlib.send_query(selector, query, host)
243 else:
244 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000245 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000246
247 # Use local file or FTP depending on form of URL
248 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000249 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000250 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000251 else:
252 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000253
254 # Use local file
255 def open_local_file(self, url):
256 host, file = splithost(url)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000257 if not host: return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000258 host, port = splitport(host)
259 if not port and socket.gethostbyname(host) in (
260 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000261 file = unquote(file)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000262 return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000263 raise IOError, ('local file error', 'not on local host')
264
265 # Use FTP protocol
266 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000267 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000268 if not host: raise IOError, ('ftp error', 'no host given')
269 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000270 user, host = splituser(host)
271 if user: user, passwd = splitpasswd(user)
272 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000273 host = socket.gethostbyname(host)
274 if not port:
275 import ftplib
276 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000277 path, attrs = splitattr(path)
278 dirs = string.splitfields(path, '/')
279 dirs, file = dirs[:-1], dirs[-1]
280 if dirs and not dirs[0]: dirs = dirs[1:]
281 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000282 try:
283 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000284 self.ftpcache[key] = \
285 ftpwrapper(user, passwd,
286 host, port, dirs)
287 if not file: type = 'D'
288 else: type = 'I'
289 for attr in attrs:
290 attr, value = splitvalue(attr)
291 if string.lower(attr) == 'type' and \
292 value in ('a', 'A', 'i', 'I', 'd', 'D'):
293 type = string.upper(value)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000294 return addinfourl(self.ftpcache[key].retrfile(file, type),
295 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000296 except ftperrors(), msg:
297 raise IOError, ('ftp error', msg)
298
299
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000300# Derived class with handlers for errors we can handle (perhaps)
301class FancyURLopener(URLopener):
302
303 def __init__(self, *args):
304 apply(URLopener.__init__, (self,) + args)
305 self.auth_cache = {}
306
307 # Default error handling -- don't raise an exception
308 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000309 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000310
Guido van Rossume6ad8911996-09-10 17:02:56 +0000311 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000312 def http_error_302(self, url, fp, errcode, errmsg, headers):
313 # XXX The server can force infinite recursion here!
314 if headers.has_key('location'):
315 newurl = headers['location']
316 elif headers.has_key('uri'):
317 newurl = headers['uri']
318 else:
319 return
320 void = fp.read()
321 fp.close()
322 return self.open(newurl)
323
Guido van Rossume6ad8911996-09-10 17:02:56 +0000324 # Error 301 -- also relocated (permanently)
325 http_error_301 = http_error_302
326
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000327 # Error 401 -- authentication required
328 # See this URL for a description of the basic authentication scheme:
329 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
330 def http_error_401(self, url, fp, errcode, errmsg, headers):
331 if headers.has_key('www-authenticate'):
332 stuff = headers['www-authenticate']
333 p = regex.compile(
334 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
335 if p.match(stuff) >= 0:
336 scheme, realm = p.group(1, 2)
337 if string.lower(scheme) == 'basic':
338 return self.retry_http_basic_auth(
339 url, realm)
340
341 def retry_http_basic_auth(self, url, realm):
342 host, selector = splithost(url)
343 i = string.find(host, '@') + 1
344 host = host[i:]
345 user, passwd = self.get_user_passwd(host, realm, i)
346 if not (user or passwd): return None
347 host = user + ':' + passwd + '@' + host
348 newurl = '//' + host + selector
349 return self.open_http(newurl)
350
351 def get_user_passwd(self, host, realm, clear_cache = 0):
352 key = realm + '@' + string.lower(host)
353 if self.auth_cache.has_key(key):
354 if clear_cache:
355 del self.auth_cache[key]
356 else:
357 return self.auth_cache[key]
358 user, passwd = self.prompt_user_passwd(host, realm)
359 if user or passwd: self.auth_cache[key] = (user, passwd)
360 return user, passwd
361
362 def prompt_user_passwd(self, host, realm):
363 # Override this in a GUI environment!
364 try:
365 user = raw_input("Enter username for %s at %s: " %
366 (realm, host))
367 self.echo_off()
368 try:
369 passwd = raw_input(
370 "Enter password for %s in %s at %s: " %
371 (user, realm, host))
372 finally:
373 self.echo_on()
374 return user, passwd
375 except KeyboardInterrupt:
376 return None, None
377
378 def echo_off(self):
379 import os
380 os.system("stty -echo")
381
382 def echo_on(self):
383 import os
384 print
385 os.system("stty echo")
386
387
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000388# Utility functions
389
390# Return the IP address of the magic hostname 'localhost'
391_localhost = None
392def localhost():
393 global _localhost
394 if not _localhost:
395 _localhost = socket.gethostbyname('localhost')
396 return _localhost
397
398# Return the IP address of the current host
399_thishost = None
400def thishost():
401 global _thishost
402 if not _thishost:
403 _thishost = socket.gethostbyname(socket.gethostname())
404 return _thishost
405
406# Return the set of errors raised by the FTP class
407_ftperrors = None
408def ftperrors():
409 global _ftperrors
410 if not _ftperrors:
411 import ftplib
412 _ftperrors = (ftplib.error_reply,
413 ftplib.error_temp,
414 ftplib.error_perm,
415 ftplib.error_proto)
416 return _ftperrors
417
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000418# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000419_noheaders = None
420def noheaders():
421 global _noheaders
422 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000423 import mimetools
424 import StringIO
425 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000426 _noheaders.fp.close() # Recycle file descriptor
427 return _noheaders
428
429
430# Utility classes
431
432# Class used by open_ftp() for cache of open FTP connections
433class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000434 def __init__(self, user, passwd, host, port, dirs):
435 self.user = unquote(user or '')
436 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000437 self.host = host
438 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000439 self.dirs = []
440 for dir in dirs:
441 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000442 self.init()
443 def init(self):
444 import ftplib
445 self.ftp = ftplib.FTP()
446 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000447 self.ftp.login(self.user, self.passwd)
448 for dir in self.dirs:
449 self.ftp.cwd(dir)
450 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000451 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000452 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
453 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000454 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000455 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000456 except ftplib.all_errors:
457 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000458 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000459 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000460 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000461 try:
462 cmd = 'RETR ' + file
463 conn = self.ftp.transfercmd(cmd)
464 except ftplib.error_perm, reason:
465 if reason[:3] != '550':
466 raise IOError, ('ftp error', reason)
467 if not conn:
468 # Try a directory listing
469 if file: cmd = 'LIST ' + file
470 else: cmd = 'LIST'
471 conn = self.ftp.transfercmd(cmd)
Jack Jansen0d12ead1996-02-14 16:05:20 +0000472 return addclosehook(conn.makefile('rb'), self.ftp.voidresp)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000473
474# Base class for addinfo and addclosehook
475class addbase:
476 def __init__(self, fp):
477 self.fp = fp
478 self.read = self.fp.read
479 self.readline = self.fp.readline
480 self.readlines = self.fp.readlines
481 self.fileno = self.fp.fileno
482 def __repr__(self):
483 return '<%s at %s whose fp = %s>' % (
484 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000485 def close(self):
486 self.read = None
487 self.readline = None
488 self.readlines = None
489 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000490 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000491 self.fp = None
492
493# Class to add a close hook to an open file
494class addclosehook(addbase):
495 def __init__(self, fp, closehook, *hookargs):
496 addbase.__init__(self, fp)
497 self.closehook = closehook
498 self.hookargs = hookargs
499 def close(self):
500 if self.closehook:
501 apply(self.closehook, self.hookargs)
502 self.closehook = None
503 self.hookargs = None
504 addbase.close(self)
505
506# class to add an info() method to an open file
507class addinfo(addbase):
508 def __init__(self, fp, headers):
509 addbase.__init__(self, fp)
510 self.headers = headers
511 def info(self):
512 return self.headers
513
Guido van Rossume6ad8911996-09-10 17:02:56 +0000514# class to add info() and geturl() methods to an open file
515class addinfourl(addbase):
516 def __init__(self, fp, headers, url):
517 addbase.__init__(self, fp)
518 self.headers = headers
519 self.url = url
520 def info(self):
521 return self.headers
522 def geturl(self):
523 return self.url
524
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000525
526# Utility to combine a URL with a base URL to form a new URL
527
528def basejoin(base, url):
529 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000530 if type:
531 # if url is complete (i.e., it contains a type), return it
532 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000533 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000534 type, basepath = splittype(base) # inherit type from base
535 if host:
536 # if url contains host, just inherit type
537 if type: return type + '://' + host + path
538 else:
539 # no type inherited, so url must have started with //
540 # just return it
541 return url
542 host, basepath = splithost(basepath) # inherit host
543 basepath, basetag = splittag(basepath) # remove extraneuous cruft
544 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000545 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000546 # non-absolute path name
547 if path[:1] in ('#', '?'):
548 # path is just a tag or query, attach to basepath
549 i = len(basepath)
550 else:
551 # else replace last component
552 i = string.rfind(basepath, '/')
553 if i < 0:
554 # basepath not absolute
555 if host:
556 # host present, make absolute
557 basepath = '/'
558 else:
559 # else keep non-absolute
560 basepath = ''
561 else:
562 # remove last file component
563 basepath = basepath[:i+1]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000564 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000565 if type and host: return type + '://' + host + path
566 elif type: return type + ':' + path
567 elif host: return '//' + host + path # don't know what this means
568 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000569
570
Guido van Rossum7c395db1994-07-04 22:14:49 +0000571# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000572# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000573# splittype('type:opaquestring') --> 'type', 'opaquestring'
574# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000575# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
576# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000577# splitport('host:port') --> 'host', 'port'
578# splitquery('/path?query') --> '/path', 'query'
579# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000580# splitattr('/path;attr1=value1;attr2=value2;...') ->
581# '/path', ['attr1=value1', 'attr2=value2', ...]
582# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000583# splitgophertype('/Xselector') --> 'X', 'selector'
584# unquote('abc%20def') -> 'abc def'
585# quote('abc def') -> 'abc%20def')
586
587def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000588 url = string.strip(url)
589 if url[:1] == '<' and url[-1:] == '>':
590 url = string.strip(url[1:-1])
591 if url[:4] == 'URL:': url = string.strip(url[4:])
592 return url
593
594_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
595def splittype(url):
596 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
597 return None, url
598
599_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
600def splithost(url):
601 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
602 return None, url
603
Guido van Rossum7c395db1994-07-04 22:14:49 +0000604_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
605def splituser(host):
606 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
607 return None, host
608
609_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
610def splitpasswd(user):
611 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
612 return user, None
613
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000614_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
615def splitport(host):
616 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
617 return host, None
618
Guido van Rossum53725a21996-06-13 19:12:35 +0000619# Split host and port, returning numeric port.
620# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000621# Return numerical port if a valid number are found after ':'.
622# Return None if ':' but not a valid number.
623_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000624def splitnport(host, defport=-1):
625 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000626 host, port = _nportprog.group(1, 2)
627 try:
628 if not port: raise string.atoi_error, "no digits"
629 nport = string.atoi(port)
630 except string.atoi_error:
631 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000632 return host, nport
633 return host, defport
634
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000635_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
636def splitquery(url):
637 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
638 return url, None
639
640_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
641def splittag(url):
642 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
643 return url, None
644
Guido van Rossum7c395db1994-07-04 22:14:49 +0000645def splitattr(url):
646 words = string.splitfields(url, ';')
647 return words[0], words[1:]
648
649_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
650def splitvalue(attr):
651 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
652 return attr, None
653
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000654def splitgophertype(selector):
655 if selector[:1] == '/' and selector[1:2]:
656 return selector[1], selector[2:]
657 return None, selector
658
659_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
660def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000661 i = 0
662 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000663 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000664 while 0 <= i < n:
665 j = _quoteprog.search(s, i)
666 if j < 0:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000667 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000668 break
Guido van Rossumf8abb381996-08-26 15:56:12 +0000669 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000670 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000671 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000672
Guido van Rossum3bb54481994-08-29 10:52:58 +0000673always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000674def quote(s, safe = '/'):
675 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000676 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000677 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000678 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000679 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000680 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000681 res.append('%%%02x' % ord(c))
682 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000683
Guido van Rossum442e7201996-03-20 15:33:11 +0000684
685# Proxy handling
686def getproxies():
687 """Return a dictionary of protocol scheme -> proxy server URL mappings.
688
689 Scan the environment for variables named <scheme>_proxy;
690 this seems to be the standard convention. If you need a
691 different way, you can pass a proxies dictionary to the
692 [Fancy]URLopener constructor.
693
694 """
695 proxies = {}
696 for name, value in os.environ.items():
697 if value and name[-6:] == '_proxy':
698 proxies[name[:-6]] = value
699 return proxies
700
701
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000702# Test and time quote() and unquote()
703def test1():
704 import time
705 s = ''
706 for i in range(256): s = s + chr(i)
707 s = s*4
708 t0 = time.time()
709 qs = quote(s)
710 uqs = unquote(qs)
711 t1 = time.time()
712 if uqs != s:
713 print 'Wrong!'
714 print `s`
715 print `qs`
716 print `uqs`
717 print round(t1 - t0, 3), 'sec'
718
719
720# Test program
721def test():
722 import sys
723 import regsub
724 args = sys.argv[1:]
725 if not args:
726 args = [
727 '/etc/passwd',
728 'file:/etc/passwd',
729 'file://localhost/etc/passwd',
730 'ftp://ftp.cwi.nl/etc/passwd',
731 'gopher://gopher.cwi.nl/11/',
732 'http://www.cwi.nl/index.html',
733 ]
734 try:
735 for url in args:
736 print '-'*10, url, '-'*10
737 fn, h = urlretrieve(url)
738 print fn, h
739 if h:
740 print '======'
741 for k in h.keys(): print k + ':', h[k]
742 print '======'
743 fp = open(fn, 'r')
744 data = fp.read()
745 del fp
746 print regsub.gsub('\r', '', data)
747 fn, h = None, None
748 print '-'*40
749 finally:
750 urlcleanup()
751
752# Run test program when run as a script
753if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000754## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000755 test()