blob: 99bed8f1cd7793353a75122dafc86d2b9c18e789 [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 Rossum5b1b33c1996-10-22 13:28:37 +0000147 self.openedurl = url1
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000148 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000149 self.tempcache[url] = self.tempcache[url1]
150 return self.tempcache[url1]
151 type, url1 = splittype(url1)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000152 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000153 try:
154 fp = self.open_local_file(url1)
155 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000156 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000157 except IOError, msg:
158 pass
159 fp = self.open(url)
160 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000161 if not filename:
162 import tempfile
163 filename = tempfile.mktemp()
164 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000165 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000166 self.tempcache[url] = result
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000167 tfp = open(filename, 'w')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000168 bs = 1024*8
169 block = fp.read(bs)
170 while block:
171 tfp.write(block)
172 block = fp.read(bs)
173 del fp
174 del tfp
175 return result
176
177 # Each method named open_<type> knows how to open that type of URL
178
179 # Use HTTP protocol
180 def open_http(self, url):
181 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000182 if type(url) is type(""):
183 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000184 user_passwd, host = splituser(host)
Guido van Rossum442e7201996-03-20 15:33:11 +0000185 else:
186 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000187 urltype, rest = splittype(selector)
188 if string.lower(urltype) == 'http':
189 realhost, rest = splithost(rest)
190 user_passwd, realhost = splituser(realhost)
191 if user_passwd:
192 selector = "%s://%s%s" % (urltype,
193 realhost, rest)
Guido van Rossum442e7201996-03-20 15:33:11 +0000194 print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000195 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000196 if user_passwd:
197 import base64
198 auth = string.strip(base64.encodestring(user_passwd))
199 else:
200 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000201 h = httplib.HTTP(host)
202 h.putrequest('GET', selector)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000203 if auth: h.putheader('Authorization: Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000204 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000205 h.endheaders()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000206 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000207 fp = h.getfile()
208 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000209 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000210 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000211 return self.http_error(url,
212 fp, errcode, errmsg, headers)
213
214 # Handle http errors.
215 # Derived class can override this, or provide specific handlers
216 # named http_error_DDD where DDD is the 3-digit error code
217 def http_error(self, url, fp, errcode, errmsg, headers):
218 # First check if there's a specific handler for this error
219 name = 'http_error_%d' % errcode
220 if hasattr(self, name):
221 method = getattr(self, name)
222 result = method(url, fp, errcode, errmsg, headers)
223 if result: return result
224 return self.http_error_default(
225 url, fp, errcode, errmsg, headers)
226
227 # Default http error handler: close the connection and raises IOError
228 def http_error_default(self, url, fp, errcode, errmsg, headers):
229 void = fp.read()
230 fp.close()
231 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000232
233 # Use Gopher protocol
234 def open_gopher(self, url):
235 import gopherlib
236 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000237 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000238 type, selector = splitgophertype(selector)
239 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000240 selector = unquote(selector)
241 if query:
242 query = unquote(query)
243 fp = gopherlib.send_query(selector, query, host)
244 else:
245 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000246 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000247
248 # Use local file or FTP depending on form of URL
249 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000250 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000251 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000252 else:
253 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000254
255 # Use local file
256 def open_local_file(self, url):
257 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000258 if not host:
259 return addinfourl(open(url2pathname(file), 'r'), noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000260 host, port = splitport(host)
261 if not port and socket.gethostbyname(host) in (
262 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000263 file = unquote(file)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000264 return addinfourl(open(url2pathname(file), 'r'), noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000265 raise IOError, ('local file error', 'not on local host')
266
267 # Use FTP protocol
268 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000269 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000270 if not host: raise IOError, ('ftp error', 'no host given')
271 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000272 user, host = splituser(host)
273 if user: user, passwd = splitpasswd(user)
274 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000275 host = socket.gethostbyname(host)
276 if not port:
277 import ftplib
278 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000279 path, attrs = splitattr(path)
280 dirs = string.splitfields(path, '/')
281 dirs, file = dirs[:-1], dirs[-1]
282 if dirs and not dirs[0]: dirs = dirs[1:]
283 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000284 try:
285 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000286 self.ftpcache[key] = \
287 ftpwrapper(user, passwd,
288 host, port, dirs)
289 if not file: type = 'D'
290 else: type = 'I'
291 for attr in attrs:
292 attr, value = splitvalue(attr)
293 if string.lower(attr) == 'type' and \
294 value in ('a', 'A', 'i', 'I', 'd', 'D'):
295 type = string.upper(value)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000296 return addinfourl(self.ftpcache[key].retrfile(file, type),
297 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000298 except ftperrors(), msg:
299 raise IOError, ('ftp error', msg)
300
301
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000302# Derived class with handlers for errors we can handle (perhaps)
303class FancyURLopener(URLopener):
304
305 def __init__(self, *args):
306 apply(URLopener.__init__, (self,) + args)
307 self.auth_cache = {}
308
309 # Default error handling -- don't raise an exception
310 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000311 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000312
Guido van Rossume6ad8911996-09-10 17:02:56 +0000313 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000314 def http_error_302(self, url, fp, errcode, errmsg, headers):
315 # XXX The server can force infinite recursion here!
316 if headers.has_key('location'):
317 newurl = headers['location']
318 elif headers.has_key('uri'):
319 newurl = headers['uri']
320 else:
321 return
322 void = fp.read()
323 fp.close()
324 return self.open(newurl)
325
Guido van Rossume6ad8911996-09-10 17:02:56 +0000326 # Error 301 -- also relocated (permanently)
327 http_error_301 = http_error_302
328
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000329 # Error 401 -- authentication required
330 # See this URL for a description of the basic authentication scheme:
331 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
332 def http_error_401(self, url, fp, errcode, errmsg, headers):
333 if headers.has_key('www-authenticate'):
334 stuff = headers['www-authenticate']
335 p = regex.compile(
336 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
337 if p.match(stuff) >= 0:
338 scheme, realm = p.group(1, 2)
339 if string.lower(scheme) == 'basic':
340 return self.retry_http_basic_auth(
341 url, realm)
342
343 def retry_http_basic_auth(self, url, realm):
344 host, selector = splithost(url)
345 i = string.find(host, '@') + 1
346 host = host[i:]
347 user, passwd = self.get_user_passwd(host, realm, i)
348 if not (user or passwd): return None
349 host = user + ':' + passwd + '@' + host
350 newurl = '//' + host + selector
351 return self.open_http(newurl)
352
353 def get_user_passwd(self, host, realm, clear_cache = 0):
354 key = realm + '@' + string.lower(host)
355 if self.auth_cache.has_key(key):
356 if clear_cache:
357 del self.auth_cache[key]
358 else:
359 return self.auth_cache[key]
360 user, passwd = self.prompt_user_passwd(host, realm)
361 if user or passwd: self.auth_cache[key] = (user, passwd)
362 return user, passwd
363
364 def prompt_user_passwd(self, host, realm):
365 # Override this in a GUI environment!
366 try:
367 user = raw_input("Enter username for %s at %s: " %
368 (realm, host))
369 self.echo_off()
370 try:
371 passwd = raw_input(
372 "Enter password for %s in %s at %s: " %
373 (user, realm, host))
374 finally:
375 self.echo_on()
376 return user, passwd
377 except KeyboardInterrupt:
378 return None, None
379
380 def echo_off(self):
381 import os
382 os.system("stty -echo")
383
384 def echo_on(self):
385 import os
386 print
387 os.system("stty echo")
388
389
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000390# Utility functions
391
392# Return the IP address of the magic hostname 'localhost'
393_localhost = None
394def localhost():
395 global _localhost
396 if not _localhost:
397 _localhost = socket.gethostbyname('localhost')
398 return _localhost
399
400# Return the IP address of the current host
401_thishost = None
402def thishost():
403 global _thishost
404 if not _thishost:
405 _thishost = socket.gethostbyname(socket.gethostname())
406 return _thishost
407
408# Return the set of errors raised by the FTP class
409_ftperrors = None
410def ftperrors():
411 global _ftperrors
412 if not _ftperrors:
413 import ftplib
414 _ftperrors = (ftplib.error_reply,
415 ftplib.error_temp,
416 ftplib.error_perm,
417 ftplib.error_proto)
418 return _ftperrors
419
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000420# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000421_noheaders = None
422def noheaders():
423 global _noheaders
424 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000425 import mimetools
426 import StringIO
427 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000428 _noheaders.fp.close() # Recycle file descriptor
429 return _noheaders
430
431
432# Utility classes
433
434# Class used by open_ftp() for cache of open FTP connections
435class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000436 def __init__(self, user, passwd, host, port, dirs):
437 self.user = unquote(user or '')
438 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000439 self.host = host
440 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000441 self.dirs = []
442 for dir in dirs:
443 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000444 self.init()
445 def init(self):
446 import ftplib
447 self.ftp = ftplib.FTP()
448 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000449 self.ftp.login(self.user, self.passwd)
450 for dir in self.dirs:
451 self.ftp.cwd(dir)
452 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000453 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000454 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
455 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000456 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000457 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000458 except ftplib.all_errors:
459 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000460 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000461 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000462 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000463 try:
464 cmd = 'RETR ' + file
465 conn = self.ftp.transfercmd(cmd)
466 except ftplib.error_perm, reason:
467 if reason[:3] != '550':
468 raise IOError, ('ftp error', reason)
469 if not conn:
470 # Try a directory listing
471 if file: cmd = 'LIST ' + file
472 else: cmd = 'LIST'
473 conn = self.ftp.transfercmd(cmd)
Jack Jansen0d12ead1996-02-14 16:05:20 +0000474 return addclosehook(conn.makefile('rb'), self.ftp.voidresp)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000475
476# Base class for addinfo and addclosehook
477class addbase:
478 def __init__(self, fp):
479 self.fp = fp
480 self.read = self.fp.read
481 self.readline = self.fp.readline
482 self.readlines = self.fp.readlines
483 self.fileno = self.fp.fileno
484 def __repr__(self):
485 return '<%s at %s whose fp = %s>' % (
486 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000487 def close(self):
488 self.read = None
489 self.readline = None
490 self.readlines = None
491 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000492 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000493 self.fp = None
494
495# Class to add a close hook to an open file
496class addclosehook(addbase):
497 def __init__(self, fp, closehook, *hookargs):
498 addbase.__init__(self, fp)
499 self.closehook = closehook
500 self.hookargs = hookargs
501 def close(self):
502 if self.closehook:
503 apply(self.closehook, self.hookargs)
504 self.closehook = None
505 self.hookargs = None
506 addbase.close(self)
507
508# class to add an info() method to an open file
509class addinfo(addbase):
510 def __init__(self, fp, headers):
511 addbase.__init__(self, fp)
512 self.headers = headers
513 def info(self):
514 return self.headers
515
Guido van Rossume6ad8911996-09-10 17:02:56 +0000516# class to add info() and geturl() methods to an open file
517class addinfourl(addbase):
518 def __init__(self, fp, headers, url):
519 addbase.__init__(self, fp)
520 self.headers = headers
521 self.url = url
522 def info(self):
523 return self.headers
524 def geturl(self):
525 return self.url
526
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000527
528# Utility to combine a URL with a base URL to form a new URL
529
530def basejoin(base, url):
531 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000532 if type:
533 # if url is complete (i.e., it contains a type), return it
534 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000535 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000536 type, basepath = splittype(base) # inherit type from base
537 if host:
538 # if url contains host, just inherit type
539 if type: return type + '://' + host + path
540 else:
541 # no type inherited, so url must have started with //
542 # just return it
543 return url
544 host, basepath = splithost(basepath) # inherit host
545 basepath, basetag = splittag(basepath) # remove extraneuous cruft
546 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000547 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000548 # non-absolute path name
549 if path[:1] in ('#', '?'):
550 # path is just a tag or query, attach to basepath
551 i = len(basepath)
552 else:
553 # else replace last component
554 i = string.rfind(basepath, '/')
555 if i < 0:
556 # basepath not absolute
557 if host:
558 # host present, make absolute
559 basepath = '/'
560 else:
561 # else keep non-absolute
562 basepath = ''
563 else:
564 # remove last file component
565 basepath = basepath[:i+1]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000566 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000567 if type and host: return type + '://' + host + path
568 elif type: return type + ':' + path
569 elif host: return '//' + host + path # don't know what this means
570 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000571
572
Guido van Rossum7c395db1994-07-04 22:14:49 +0000573# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000574# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000575# splittype('type:opaquestring') --> 'type', 'opaquestring'
576# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000577# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
578# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000579# splitport('host:port') --> 'host', 'port'
580# splitquery('/path?query') --> '/path', 'query'
581# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000582# splitattr('/path;attr1=value1;attr2=value2;...') ->
583# '/path', ['attr1=value1', 'attr2=value2', ...]
584# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000585# splitgophertype('/Xselector') --> 'X', 'selector'
586# unquote('abc%20def') -> 'abc def'
587# quote('abc def') -> 'abc%20def')
588
589def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000590 url = string.strip(url)
591 if url[:1] == '<' and url[-1:] == '>':
592 url = string.strip(url[1:-1])
593 if url[:4] == 'URL:': url = string.strip(url[4:])
594 return url
595
596_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
597def splittype(url):
598 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
599 return None, url
600
601_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
602def splithost(url):
603 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
604 return None, url
605
Guido van Rossum7c395db1994-07-04 22:14:49 +0000606_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
607def splituser(host):
608 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
609 return None, host
610
611_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
612def splitpasswd(user):
613 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
614 return user, None
615
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000616_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
617def splitport(host):
618 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
619 return host, None
620
Guido van Rossum53725a21996-06-13 19:12:35 +0000621# Split host and port, returning numeric port.
622# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000623# Return numerical port if a valid number are found after ':'.
624# Return None if ':' but not a valid number.
625_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000626def splitnport(host, defport=-1):
627 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000628 host, port = _nportprog.group(1, 2)
629 try:
630 if not port: raise string.atoi_error, "no digits"
631 nport = string.atoi(port)
632 except string.atoi_error:
633 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000634 return host, nport
635 return host, defport
636
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000637_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
638def splitquery(url):
639 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
640 return url, None
641
642_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
643def splittag(url):
644 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
645 return url, None
646
Guido van Rossum7c395db1994-07-04 22:14:49 +0000647def splitattr(url):
648 words = string.splitfields(url, ';')
649 return words[0], words[1:]
650
651_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
652def splitvalue(attr):
653 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
654 return attr, None
655
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000656def splitgophertype(selector):
657 if selector[:1] == '/' and selector[1:2]:
658 return selector[1], selector[2:]
659 return None, selector
660
661_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
662def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000663 i = 0
664 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000665 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000666 while 0 <= i < n:
667 j = _quoteprog.search(s, i)
668 if j < 0:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000669 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000670 break
Guido van Rossumf8abb381996-08-26 15:56:12 +0000671 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000672 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000673 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000674
Guido van Rossum3bb54481994-08-29 10:52:58 +0000675always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000676def quote(s, safe = '/'):
677 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000678 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000679 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000680 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000681 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000682 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000683 res.append('%%%02x' % ord(c))
684 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000685
Guido van Rossum442e7201996-03-20 15:33:11 +0000686
687# Proxy handling
688def getproxies():
689 """Return a dictionary of protocol scheme -> proxy server URL mappings.
690
691 Scan the environment for variables named <scheme>_proxy;
692 this seems to be the standard convention. If you need a
693 different way, you can pass a proxies dictionary to the
694 [Fancy]URLopener constructor.
695
696 """
697 proxies = {}
698 for name, value in os.environ.items():
699 if value and name[-6:] == '_proxy':
700 proxies[name[:-6]] = value
701 return proxies
702
703
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000704# Test and time quote() and unquote()
705def test1():
706 import time
707 s = ''
708 for i in range(256): s = s + chr(i)
709 s = s*4
710 t0 = time.time()
711 qs = quote(s)
712 uqs = unquote(qs)
713 t1 = time.time()
714 if uqs != s:
715 print 'Wrong!'
716 print `s`
717 print `qs`
718 print `uqs`
719 print round(t1 - t0, 3), 'sec'
720
721
722# Test program
723def test():
724 import sys
725 import regsub
726 args = sys.argv[1:]
727 if not args:
728 args = [
729 '/etc/passwd',
730 'file:/etc/passwd',
731 'file://localhost/etc/passwd',
732 'ftp://ftp.cwi.nl/etc/passwd',
733 'gopher://gopher.cwi.nl/11/',
734 'http://www.cwi.nl/index.html',
735 ]
736 try:
737 for url in args:
738 print '-'*10, url, '-'*10
739 fn, h = urlretrieve(url)
740 print fn, h
741 if h:
742 print '======'
743 for k in h.keys(): print k + ':', h[k]
744 print '======'
745 fp = open(fn, 'r')
746 data = fp.read()
747 del fp
748 print regsub.gsub('\r', '', data)
749 fn, h = None, None
750 print '-'*40
751 finally:
752 urlcleanup()
753
754# Run test program when run as a script
755if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000756## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000757 test()