blob: f036078b895117734e0ee60f7319cca907212140 [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':
Jack Jansene8ea21b1995-12-21 15:43:53 +000027 def url2pathname(pathname):
28 "Convert /-delimited pathname to mac pathname"
29 #
30 # XXXX The .. handling should be fixed...
31 #
32 tp = splittype(pathname)[0]
33 if tp and tp <> 'file':
34 raise RuntimeError, 'Cannot convert non-local URL to pathname'
Jack Jansendc3e3f61995-12-15 13:22:13 +000035 components = string.split(pathname, '/')
Guido van Rossum442e7201996-03-20 15:33:11 +000036 # Remove . and embedded ..
Jack Jansen0d12ead1996-02-14 16:05:20 +000037 i = 0
38 while i < len(components):
39 if components[i] == '.':
40 del components[i]
41 elif components[i] == '..' and i > 0 and \
42 components[i-1] not in ('', '..'):
43 del components[i-1:i+1]
44 i = i-1
45 elif components[i] == '' and i > 0 and components[i-1] <> '':
46 del components[i]
47 else:
48 i = i+1
Jack Jansendc3e3f61995-12-15 13:22:13 +000049 if not components[0]:
50 # Absolute unix path, don't start with colon
51 return string.join(components[1:], ':')
52 else:
Guido van Rossum442e7201996-03-20 15:33:11 +000053 # relative unix path, start with colon. First replace
54 # leading .. by empty strings (giving ::file)
55 i = 0
56 while i < len(components) and components[i] == '..':
57 components[i] = ''
58 i = i + 1
Jack Jansendc3e3f61995-12-15 13:22:13 +000059 return ':' + string.join(components, ':')
Jack Jansene8ea21b1995-12-21 15:43:53 +000060
61 def pathname2url(pathname):
62 "convert mac pathname to /-delimited pathname"
63 if '/' in pathname:
64 raise RuntimeError, "Cannot convert pathname containing slashes"
65 components = string.split(pathname, ':')
Guido van Rossum442e7201996-03-20 15:33:11 +000066 # Replace empty string ('::') by .. (will result in '/../' later)
67 for i in range(1, len(components)):
68 if components[i] == '':
69 components[i] = '..'
Jack Jansene8ea21b1995-12-21 15:43:53 +000070 # Truncate names longer than 31 bytes
71 components = map(lambda x: x[:31], components)
72
73 if os.path.isabs(pathname):
74 return '/' + string.join(components, '/')
75 else:
76 return string.join(components, '/')
Jack Jansendc3e3f61995-12-15 13:22:13 +000077else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000078 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000079 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000080 def pathname2url(pathname):
81 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000082
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000083# This really consists of two pieces:
84# (1) a class which handles opening of all sorts of URLs
85# (plus assorted utilities etc.)
86# (2) a set of functions for parsing URLs
87# XXX Should these be separated out into different modules?
88
89
90# Shortcut for basic usage
91_urlopener = None
92def urlopen(url):
93 global _urlopener
94 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000095 _urlopener = FancyURLopener()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000096 return _urlopener.open(url)
97def urlretrieve(url):
98 global _urlopener
99 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000100 _urlopener = FancyURLopener()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000101 return _urlopener.retrieve(url)
102def urlcleanup():
103 if _urlopener:
104 _urlopener.cleanup()
105
106
107# Class to open URLs.
108# This is a class rather than just a subroutine because we may need
109# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000110# Note -- this is a base class for those who don't want the
111# automatic handling of errors type 302 (relocated) and 401
112# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000113ftpcache = {}
114class URLopener:
115
116 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +0000117 def __init__(self, proxies=None):
118 if proxies is None:
119 proxies = getproxies()
120 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000121 server_version = "Python-urllib/%s" % __version__
122 self.addheaders = [('User-agent', server_version)]
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000123 self.tempcache = None
124 # Undocumented feature: if you assign {} to tempcache,
125 # it is used to cache files retrieved with
126 # self.retrieve(). This is not enabled by default
127 # since it does not work for changing documents (and I
128 # haven't got the logic to check expiration headers
129 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000130 self.ftpcache = ftpcache
131 # Undocumented feature: you can use a different
132 # ftp cache by assigning to the .ftpcache member;
133 # in case you want logically independent URL openers
134
135 def __del__(self):
136 self.close()
137
138 def close(self):
139 self.cleanup()
140
141 def cleanup(self):
142 import os
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000143 if self.tempcache:
144 for url in self.tempcache.keys():
145 try:
146 os.unlink(self.tempcache[url][0])
147 except os.error:
148 pass
149 del self.tempcache[url]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000150
151 # Add a header to be used by the HTTP interface only
152 # e.g. u.addheader('Accept', 'sound/basic')
153 def addheader(self, *args):
154 self.addheaders.append(args)
155
156 # External interface
157 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumca445401995-08-29 19:19:12 +0000158 def open(self, fullurl):
159 fullurl = unwrap(fullurl)
160 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000161 if not type: type = 'file'
Guido van Rossum442e7201996-03-20 15:33:11 +0000162 if self.proxies.has_key(type):
163 proxy = self.proxies[type]
164 type, proxy = splittype(proxy)
165 host, selector = splithost(proxy)
166 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000167 name = 'open_' + type
168 if '-' in name:
169 import regsub
170 name = regsub.gsub('-', '_', name)
171 if not hasattr(self, name):
Guido van Rossumca445401995-08-29 19:19:12 +0000172 return self.open_unknown(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000173 try:
174 return getattr(self, name)(url)
175 except socket.error, msg:
176 raise IOError, ('socket error', msg)
177
Guido van Rossumca445401995-08-29 19:19:12 +0000178 # Overridable interface to open unknown URL type
179 def open_unknown(self, fullurl):
180 type, url = splittype(fullurl)
181 raise IOError, ('url error', 'unknown url type', type)
182
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000183 # External interface
184 # retrieve(url) returns (filename, None) for a local object
185 # or (tempfilename, headers) for a remote object
186 def retrieve(self, url):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000187 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000188 return self.tempcache[url]
189 url1 = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000190 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000191 self.tempcache[url] = self.tempcache[url1]
192 return self.tempcache[url1]
193 type, url1 = splittype(url1)
194 if not type or type == 'file':
195 try:
196 fp = self.open_local_file(url1)
197 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000198 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000199 except IOError, msg:
200 pass
201 fp = self.open(url)
202 headers = fp.info()
203 import tempfile
204 tfn = tempfile.mktemp()
Guido van Rossumfa59e831994-09-21 11:36:19 +0000205 result = tfn, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000206 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000207 self.tempcache[url] = result
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000208 tfp = open(tfn, 'w')
209 bs = 1024*8
210 block = fp.read(bs)
211 while block:
212 tfp.write(block)
213 block = fp.read(bs)
214 del fp
215 del tfp
216 return result
217
218 # Each method named open_<type> knows how to open that type of URL
219
220 # Use HTTP protocol
221 def open_http(self, url):
222 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000223 if type(url) is type(""):
224 host, selector = splithost(url)
225 else:
226 host, selector = url
227 print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000228 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000229 i = string.find(host, '@')
230 if i >= 0:
231 user_passwd, host = host[:i], host[i+1:]
232 else:
233 user_passwd = None
234 if user_passwd:
235 import base64
236 auth = string.strip(base64.encodestring(user_passwd))
237 else:
238 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000239 h = httplib.HTTP(host)
240 h.putrequest('GET', selector)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000241 if auth: h.putheader('Authorization: Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000242 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000243 h.endheaders()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000244 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000245 fp = h.getfile()
246 if errcode == 200:
247 return addinfo(fp, headers)
248 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000249 return self.http_error(url,
250 fp, errcode, errmsg, headers)
251
252 # Handle http errors.
253 # Derived class can override this, or provide specific handlers
254 # named http_error_DDD where DDD is the 3-digit error code
255 def http_error(self, url, fp, errcode, errmsg, headers):
256 # First check if there's a specific handler for this error
257 name = 'http_error_%d' % errcode
258 if hasattr(self, name):
259 method = getattr(self, name)
260 result = method(url, fp, errcode, errmsg, headers)
261 if result: return result
262 return self.http_error_default(
263 url, fp, errcode, errmsg, headers)
264
265 # Default http error handler: close the connection and raises IOError
266 def http_error_default(self, url, fp, errcode, errmsg, headers):
267 void = fp.read()
268 fp.close()
269 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000270
271 # Use Gopher protocol
272 def open_gopher(self, url):
273 import gopherlib
274 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000275 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000276 type, selector = splitgophertype(selector)
277 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000278 selector = unquote(selector)
279 if query:
280 query = unquote(query)
281 fp = gopherlib.send_query(selector, query, host)
282 else:
283 fp = gopherlib.send_selector(selector, host)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000284 return addinfo(fp, noheaders())
285
286 # Use local file or FTP depending on form of URL
287 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000288 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000289 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000290 else:
291 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000292
293 # Use local file
294 def open_local_file(self, url):
295 host, file = splithost(url)
Jack Jansene8ea21b1995-12-21 15:43:53 +0000296 if not host: return addinfo(open(url2pathname(file), 'r'), noheaders())
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000297 host, port = splitport(host)
298 if not port and socket.gethostbyname(host) in (
299 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000300 file = unquote(file)
Jack Jansene8ea21b1995-12-21 15:43:53 +0000301 return addinfo(open(url2pathname(file), 'r'), noheaders())
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000302 raise IOError, ('local file error', 'not on local host')
303
304 # Use FTP protocol
305 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000306 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000307 if not host: raise IOError, ('ftp error', 'no host given')
308 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000309 user, host = splituser(host)
310 if user: user, passwd = splitpasswd(user)
311 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000312 host = socket.gethostbyname(host)
313 if not port:
314 import ftplib
315 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000316 path, attrs = splitattr(path)
317 dirs = string.splitfields(path, '/')
318 dirs, file = dirs[:-1], dirs[-1]
319 if dirs and not dirs[0]: dirs = dirs[1:]
320 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000321 try:
322 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000323 self.ftpcache[key] = \
324 ftpwrapper(user, passwd,
325 host, port, dirs)
326 if not file: type = 'D'
327 else: type = 'I'
328 for attr in attrs:
329 attr, value = splitvalue(attr)
330 if string.lower(attr) == 'type' and \
331 value in ('a', 'A', 'i', 'I', 'd', 'D'):
332 type = string.upper(value)
333 return addinfo(self.ftpcache[key].retrfile(file, type),
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000334 noheaders())
335 except ftperrors(), msg:
336 raise IOError, ('ftp error', msg)
337
338
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000339# Derived class with handlers for errors we can handle (perhaps)
340class FancyURLopener(URLopener):
341
342 def __init__(self, *args):
343 apply(URLopener.__init__, (self,) + args)
344 self.auth_cache = {}
345
346 # Default error handling -- don't raise an exception
347 def http_error_default(self, url, fp, errcode, errmsg, headers):
348 return addinfo(fp, headers)
349
350 # Error 302 -- relocated
351 def http_error_302(self, url, fp, errcode, errmsg, headers):
352 # XXX The server can force infinite recursion here!
353 if headers.has_key('location'):
354 newurl = headers['location']
355 elif headers.has_key('uri'):
356 newurl = headers['uri']
357 else:
358 return
359 void = fp.read()
360 fp.close()
361 return self.open(newurl)
362
363 # Error 401 -- authentication required
364 # See this URL for a description of the basic authentication scheme:
365 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
366 def http_error_401(self, url, fp, errcode, errmsg, headers):
367 if headers.has_key('www-authenticate'):
368 stuff = headers['www-authenticate']
369 p = regex.compile(
370 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
371 if p.match(stuff) >= 0:
372 scheme, realm = p.group(1, 2)
373 if string.lower(scheme) == 'basic':
374 return self.retry_http_basic_auth(
375 url, realm)
376
377 def retry_http_basic_auth(self, url, realm):
378 host, selector = splithost(url)
379 i = string.find(host, '@') + 1
380 host = host[i:]
381 user, passwd = self.get_user_passwd(host, realm, i)
382 if not (user or passwd): return None
383 host = user + ':' + passwd + '@' + host
384 newurl = '//' + host + selector
385 return self.open_http(newurl)
386
387 def get_user_passwd(self, host, realm, clear_cache = 0):
388 key = realm + '@' + string.lower(host)
389 if self.auth_cache.has_key(key):
390 if clear_cache:
391 del self.auth_cache[key]
392 else:
393 return self.auth_cache[key]
394 user, passwd = self.prompt_user_passwd(host, realm)
395 if user or passwd: self.auth_cache[key] = (user, passwd)
396 return user, passwd
397
398 def prompt_user_passwd(self, host, realm):
399 # Override this in a GUI environment!
400 try:
401 user = raw_input("Enter username for %s at %s: " %
402 (realm, host))
403 self.echo_off()
404 try:
405 passwd = raw_input(
406 "Enter password for %s in %s at %s: " %
407 (user, realm, host))
408 finally:
409 self.echo_on()
410 return user, passwd
411 except KeyboardInterrupt:
412 return None, None
413
414 def echo_off(self):
415 import os
416 os.system("stty -echo")
417
418 def echo_on(self):
419 import os
420 print
421 os.system("stty echo")
422
423
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000424# Utility functions
425
426# Return the IP address of the magic hostname 'localhost'
427_localhost = None
428def localhost():
429 global _localhost
430 if not _localhost:
431 _localhost = socket.gethostbyname('localhost')
432 return _localhost
433
434# Return the IP address of the current host
435_thishost = None
436def thishost():
437 global _thishost
438 if not _thishost:
439 _thishost = socket.gethostbyname(socket.gethostname())
440 return _thishost
441
442# Return the set of errors raised by the FTP class
443_ftperrors = None
444def ftperrors():
445 global _ftperrors
446 if not _ftperrors:
447 import ftplib
448 _ftperrors = (ftplib.error_reply,
449 ftplib.error_temp,
450 ftplib.error_perm,
451 ftplib.error_proto)
452 return _ftperrors
453
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000454# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000455_noheaders = None
456def noheaders():
457 global _noheaders
458 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000459 import mimetools
460 import StringIO
461 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000462 _noheaders.fp.close() # Recycle file descriptor
463 return _noheaders
464
465
466# Utility classes
467
468# Class used by open_ftp() for cache of open FTP connections
469class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000470 def __init__(self, user, passwd, host, port, dirs):
471 self.user = unquote(user or '')
472 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000473 self.host = host
474 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000475 self.dirs = []
476 for dir in dirs:
477 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000478 self.init()
479 def init(self):
480 import ftplib
481 self.ftp = ftplib.FTP()
482 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000483 self.ftp.login(self.user, self.passwd)
484 for dir in self.dirs:
485 self.ftp.cwd(dir)
486 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000487 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000488 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
489 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000490 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000491 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000492 except ftplib.all_errors:
493 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000494 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000495 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000496 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000497 try:
498 cmd = 'RETR ' + file
499 conn = self.ftp.transfercmd(cmd)
500 except ftplib.error_perm, reason:
501 if reason[:3] != '550':
502 raise IOError, ('ftp error', reason)
503 if not conn:
504 # Try a directory listing
505 if file: cmd = 'LIST ' + file
506 else: cmd = 'LIST'
507 conn = self.ftp.transfercmd(cmd)
Jack Jansen0d12ead1996-02-14 16:05:20 +0000508 return addclosehook(conn.makefile('rb'), self.ftp.voidresp)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000509
510# Base class for addinfo and addclosehook
511class addbase:
512 def __init__(self, fp):
513 self.fp = fp
514 self.read = self.fp.read
515 self.readline = self.fp.readline
516 self.readlines = self.fp.readlines
517 self.fileno = self.fp.fileno
518 def __repr__(self):
519 return '<%s at %s whose fp = %s>' % (
520 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000521 def close(self):
522 self.read = None
523 self.readline = None
524 self.readlines = None
525 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000526 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000527 self.fp = None
528
529# Class to add a close hook to an open file
530class addclosehook(addbase):
531 def __init__(self, fp, closehook, *hookargs):
532 addbase.__init__(self, fp)
533 self.closehook = closehook
534 self.hookargs = hookargs
535 def close(self):
536 if self.closehook:
537 apply(self.closehook, self.hookargs)
538 self.closehook = None
539 self.hookargs = None
540 addbase.close(self)
541
542# class to add an info() method to an open file
543class addinfo(addbase):
544 def __init__(self, fp, headers):
545 addbase.__init__(self, fp)
546 self.headers = headers
547 def info(self):
548 return self.headers
549
550
551# Utility to combine a URL with a base URL to form a new URL
552
553def basejoin(base, url):
554 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000555 if type:
556 # if url is complete (i.e., it contains a type), return it
557 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000558 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000559 type, basepath = splittype(base) # inherit type from base
560 if host:
561 # if url contains host, just inherit type
562 if type: return type + '://' + host + path
563 else:
564 # no type inherited, so url must have started with //
565 # just return it
566 return url
567 host, basepath = splithost(basepath) # inherit host
568 basepath, basetag = splittag(basepath) # remove extraneuous cruft
569 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000570 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000571 # non-absolute path name
572 if path[:1] in ('#', '?'):
573 # path is just a tag or query, attach to basepath
574 i = len(basepath)
575 else:
576 # else replace last component
577 i = string.rfind(basepath, '/')
578 if i < 0:
579 # basepath not absolute
580 if host:
581 # host present, make absolute
582 basepath = '/'
583 else:
584 # else keep non-absolute
585 basepath = ''
586 else:
587 # remove last file component
588 basepath = basepath[:i+1]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000589 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000590 if type and host: return type + '://' + host + path
591 elif type: return type + ':' + path
592 elif host: return '//' + host + path # don't know what this means
593 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000594
595
Guido van Rossum7c395db1994-07-04 22:14:49 +0000596# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000597# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000598# splittype('type:opaquestring') --> 'type', 'opaquestring'
599# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000600# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
601# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000602# splitport('host:port') --> 'host', 'port'
603# splitquery('/path?query') --> '/path', 'query'
604# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000605# splitattr('/path;attr1=value1;attr2=value2;...') ->
606# '/path', ['attr1=value1', 'attr2=value2', ...]
607# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000608# splitgophertype('/Xselector') --> 'X', 'selector'
609# unquote('abc%20def') -> 'abc def'
610# quote('abc def') -> 'abc%20def')
611
612def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000613 url = string.strip(url)
614 if url[:1] == '<' and url[-1:] == '>':
615 url = string.strip(url[1:-1])
616 if url[:4] == 'URL:': url = string.strip(url[4:])
617 return url
618
619_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
620def splittype(url):
621 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
622 return None, url
623
624_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
625def splithost(url):
626 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
627 return None, url
628
Guido van Rossum7c395db1994-07-04 22:14:49 +0000629_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
630def splituser(host):
631 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
632 return None, host
633
634_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
635def splitpasswd(user):
636 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
637 return user, None
638
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000639_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
640def splitport(host):
641 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
642 return host, None
643
644_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
645def splitquery(url):
646 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
647 return url, None
648
649_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
650def splittag(url):
651 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
652 return url, None
653
Guido van Rossum7c395db1994-07-04 22:14:49 +0000654def splitattr(url):
655 words = string.splitfields(url, ';')
656 return words[0], words[1:]
657
658_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
659def splitvalue(attr):
660 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
661 return attr, None
662
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000663def splitgophertype(selector):
664 if selector[:1] == '/' and selector[1:2]:
665 return selector[1], selector[2:]
666 return None, selector
667
668_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
669def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000670 i = 0
671 n = len(s)
672 res = ''
673 while 0 <= i < n:
674 j = _quoteprog.search(s, i)
675 if j < 0:
676 res = res + s[i:]
677 break
Guido van Rossum8c8a02a1996-01-26 17:41:44 +0000678 res = res + (s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000679 i = j+3
680 return res
681
Guido van Rossum3bb54481994-08-29 10:52:58 +0000682always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000683def quote(s, safe = '/'):
684 safe = always_safe + safe
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000685 res = ''
686 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000687 if c in safe:
688 res = res + c
689 else:
690 res = res + '%%%02x' % ord(c)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000691 return res
692
Guido van Rossum442e7201996-03-20 15:33:11 +0000693
694# Proxy handling
695def getproxies():
696 """Return a dictionary of protocol scheme -> proxy server URL mappings.
697
698 Scan the environment for variables named <scheme>_proxy;
699 this seems to be the standard convention. If you need a
700 different way, you can pass a proxies dictionary to the
701 [Fancy]URLopener constructor.
702
703 """
704 proxies = {}
705 for name, value in os.environ.items():
706 if value and name[-6:] == '_proxy':
707 proxies[name[:-6]] = value
708 return proxies
709
710
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000711# Test and time quote() and unquote()
712def test1():
713 import time
714 s = ''
715 for i in range(256): s = s + chr(i)
716 s = s*4
717 t0 = time.time()
718 qs = quote(s)
719 uqs = unquote(qs)
720 t1 = time.time()
721 if uqs != s:
722 print 'Wrong!'
723 print `s`
724 print `qs`
725 print `uqs`
726 print round(t1 - t0, 3), 'sec'
727
728
729# Test program
730def test():
731 import sys
732 import regsub
733 args = sys.argv[1:]
734 if not args:
735 args = [
736 '/etc/passwd',
737 'file:/etc/passwd',
738 'file://localhost/etc/passwd',
739 'ftp://ftp.cwi.nl/etc/passwd',
740 'gopher://gopher.cwi.nl/11/',
741 'http://www.cwi.nl/index.html',
742 ]
743 try:
744 for url in args:
745 print '-'*10, url, '-'*10
746 fn, h = urlretrieve(url)
747 print fn, h
748 if h:
749 print '======'
750 for k in h.keys(): print k + ':', h[k]
751 print '======'
752 fp = open(fn, 'r')
753 data = fp.read()
754 del fp
755 print regsub.gsub('\r', '', data)
756 fn, h = None, None
757 print '-'*40
758 finally:
759 urlcleanup()
760
761# Run test program when run as a script
762if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000763## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000764 test()