blob: 390dd636340eb8f8f142b930055792dc7e8c2a74 [file] [log] [blame]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001# Open an arbitrary URL
2#
Guido van Rossum838cb281997-02-10 17:51:56 +00003# See the following document for more info on URLs:
4# "Names and Addresses, URIs, URLs, URNs, URCs", at
5# http://www.w3.org/pub/WWW/Addressing/Overview.html
6#
7# See also the HTTP spec (from which the error codes are derived):
8# "HTTP - Hypertext Transfer Protocol", at
9# http://www.w3.org/pub/WWW/Protocols/
10#
11# Related standards and specs:
12# - RFC1808: the "relative URL" spec. (authoritative status)
13# - RFC1738 - the "URL standard". (authoritative status)
14# - RFC1630 - the "URI spec". (informational status)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000015#
16# The object returned by URLopener().open(file) will differ per
17# protocol. All you know is that is has methods read(), readline(),
18# readlines(), fileno(), close() and info(). The read*(), fileno()
19# and close() methods work like those of open files.
Guido van Rossum838cb281997-02-10 17:51:56 +000020# The info() method returns a mimetools.Message object which can be
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000021# used to query various info about the object, if available.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000022# (mimetools.Message objects are queried with the getheader() method.)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000023
Guido van Rossum7c395db1994-07-04 22:14:49 +000024import string
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000025import socket
26import regex
Jack Jansendc3e3f61995-12-15 13:22:13 +000027import os
Guido van Rossum3c8484e1996-11-20 22:02:24 +000028import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000029
30
Guido van Rossumbd013741996-12-10 16:00:28 +000031__version__ = '1.6'
Guido van Rossum6cb15a01995-06-22 19:00:13 +000032
Jack Jansendc3e3f61995-12-15 13:22:13 +000033# Helper for non-unix systems
34if os.name == 'mac':
Guido van Rossum71ac9451996-03-21 16:31:41 +000035 from macurl2path import url2pathname, pathname2url
Guido van Rossum2281d351996-06-26 19:47:37 +000036elif os.name == 'nt':
37 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000038else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000039 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000040 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000041 def pathname2url(pathname):
42 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000043
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000044# This really consists of two pieces:
45# (1) a class which handles opening of all sorts of URLs
46# (plus assorted utilities etc.)
47# (2) a set of functions for parsing URLs
48# XXX Should these be separated out into different modules?
49
50
51# Shortcut for basic usage
52_urlopener = None
Guido van Rossumbd013741996-12-10 16:00:28 +000053def urlopen(url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000054 global _urlopener
55 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000056 _urlopener = FancyURLopener()
Guido van Rossumbd013741996-12-10 16:00:28 +000057 if data is None:
58 return _urlopener.open(url)
59 else:
60 return _urlopener.open(url, data)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000061def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000062 global _urlopener
63 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000064 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000065 if filename:
66 return _urlopener.retrieve(url, filename)
67 else:
68 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000069def urlcleanup():
70 if _urlopener:
71 _urlopener.cleanup()
72
73
74# Class to open URLs.
75# This is a class rather than just a subroutine because we may need
76# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000077# Note -- this is a base class for those who don't want the
78# automatic handling of errors type 302 (relocated) and 401
79# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000080ftpcache = {}
81class URLopener:
82
Guido van Rossum29e77811996-11-27 19:39:58 +000083 tempcache = None # So close() in __del__() won't fail
84
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000085 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000086 def __init__(self, proxies=None):
87 if proxies is None:
88 proxies = getproxies()
89 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +000090 server_version = "Python-urllib/%s" % __version__
91 self.addheaders = [('User-agent', server_version)]
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000092 self.tempcache = None
93 # Undocumented feature: if you assign {} to tempcache,
94 # it is used to cache files retrieved with
95 # self.retrieve(). This is not enabled by default
96 # since it does not work for changing documents (and I
97 # haven't got the logic to check expiration headers
98 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000099 self.ftpcache = ftpcache
100 # Undocumented feature: you can use a different
101 # ftp cache by assigning to the .ftpcache member;
102 # in case you want logically independent URL openers
103
104 def __del__(self):
105 self.close()
106
107 def close(self):
108 self.cleanup()
109
110 def cleanup(self):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000111 if self.tempcache:
Guido van Rossumd23d9401997-01-30 15:54:58 +0000112 import os
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000113 for url in self.tempcache.keys():
114 try:
115 os.unlink(self.tempcache[url][0])
116 except os.error:
117 pass
118 del self.tempcache[url]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000119
120 # Add a header to be used by the HTTP interface only
121 # e.g. u.addheader('Accept', 'sound/basic')
122 def addheader(self, *args):
123 self.addheaders.append(args)
124
125 # External interface
126 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumbd013741996-12-10 16:00:28 +0000127 def open(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000128 fullurl = unwrap(fullurl)
129 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000130 if not type: type = 'file'
Guido van Rossume6ad8911996-09-10 17:02:56 +0000131 self.openedurl = '%s:%s' % (type, url)
Guido van Rossum442e7201996-03-20 15:33:11 +0000132 if self.proxies.has_key(type):
133 proxy = self.proxies[type]
134 type, proxy = splittype(proxy)
135 host, selector = splithost(proxy)
136 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000137 name = 'open_' + type
138 if '-' in name:
139 import regsub
140 name = regsub.gsub('-', '_', name)
141 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000142 if data is None:
143 return self.open_unknown(fullurl)
144 else:
145 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000146 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000147 if data is None:
148 return getattr(self, name)(url)
149 else:
150 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000151 except socket.error, msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000152 raise IOError, ('socket error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000153
Guido van Rossumca445401995-08-29 19:19:12 +0000154 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000155 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000156 type, url = splittype(fullurl)
157 raise IOError, ('url error', 'unknown url type', type)
158
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000159 # External interface
160 # retrieve(url) returns (filename, None) for a local object
161 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000162 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000163 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000164 return self.tempcache[url]
165 url1 = unwrap(url)
Guido van Rossum5b1b33c1996-10-22 13:28:37 +0000166 self.openedurl = url1
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000167 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000168 self.tempcache[url] = self.tempcache[url1]
169 return self.tempcache[url1]
170 type, url1 = splittype(url1)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000171 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000172 try:
173 fp = self.open_local_file(url1)
174 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000175 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000176 except IOError, msg:
177 pass
178 fp = self.open(url)
179 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000180 if not filename:
181 import tempfile
182 filename = tempfile.mktemp()
183 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000184 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000185 self.tempcache[url] = result
Guido van Rossumc511aee1997-04-11 19:01:48 +0000186 tfp = open(filename, 'wb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000187 bs = 1024*8
188 block = fp.read(bs)
189 while block:
190 tfp.write(block)
191 block = fp.read(bs)
192 del fp
193 del tfp
194 return result
195
196 # Each method named open_<type> knows how to open that type of URL
197
198 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000199 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000200 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000201 if type(url) is type(""):
202 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000203 user_passwd, host = splituser(host)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000204 realhost = host
Guido van Rossum442e7201996-03-20 15:33:11 +0000205 else:
206 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000207 urltype, rest = splittype(selector)
Guido van Rossumfd795661997-04-02 05:46:35 +0000208 user_passwd = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000209 if string.lower(urltype) != 'http':
210 realhost = None
211 else:
Guido van Rossum78c96371996-08-26 18:09:59 +0000212 realhost, rest = splithost(rest)
213 user_passwd, realhost = splituser(realhost)
214 if user_passwd:
215 selector = "%s://%s%s" % (urltype,
216 realhost, rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000217 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000218 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000219 if user_passwd:
220 import base64
221 auth = string.strip(base64.encodestring(user_passwd))
222 else:
223 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000224 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000225 if data is not None:
226 h.putrequest('POST', selector)
227 h.putheader('Content-type',
228 'application/x-www-form-urlencoded')
229 h.putheader('Content-length', '%d' % len(data))
230 else:
231 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000232 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000233 if realhost: h.putheader('Host', realhost)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000234 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000235 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000236 if data is not None:
237 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000238 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000239 fp = h.getfile()
240 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000241 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000242 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000243 return self.http_error(url,
244 fp, errcode, errmsg, headers)
245
246 # Handle http errors.
247 # Derived class can override this, or provide specific handlers
248 # named http_error_DDD where DDD is the 3-digit error code
249 def http_error(self, url, fp, errcode, errmsg, headers):
250 # First check if there's a specific handler for this error
251 name = 'http_error_%d' % errcode
252 if hasattr(self, name):
253 method = getattr(self, name)
254 result = method(url, fp, errcode, errmsg, headers)
255 if result: return result
256 return self.http_error_default(
257 url, fp, errcode, errmsg, headers)
258
259 # Default http error handler: close the connection and raises IOError
260 def http_error_default(self, url, fp, errcode, errmsg, headers):
261 void = fp.read()
262 fp.close()
263 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000264
265 # Use Gopher protocol
266 def open_gopher(self, url):
267 import gopherlib
268 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000269 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000270 type, selector = splitgophertype(selector)
271 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000272 selector = unquote(selector)
273 if query:
274 query = unquote(query)
275 fp = gopherlib.send_query(selector, query, host)
276 else:
277 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000278 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000279
280 # Use local file or FTP depending on form of URL
281 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000282 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000283 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000284 else:
285 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000286
287 # Use local file
288 def open_local_file(self, url):
289 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000290 if not host:
Guido van Rossumc511aee1997-04-11 19:01:48 +0000291 return addinfourl(open(url2pathname(file), 'rb'), noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000292 host, port = splitport(host)
293 if not port and socket.gethostbyname(host) in (
294 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000295 file = unquote(file)
Guido van Rossumc511aee1997-04-11 19:01:48 +0000296 return addinfourl(open(url2pathname(file), 'rb'), noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000297 raise IOError, ('local file error', 'not on local host')
298
299 # Use FTP protocol
300 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000301 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000302 if not host: raise IOError, ('ftp error', 'no host given')
303 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000304 user, host = splituser(host)
305 if user: user, passwd = splitpasswd(user)
306 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000307 host = socket.gethostbyname(host)
308 if not port:
309 import ftplib
310 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000311 path, attrs = splitattr(path)
312 dirs = string.splitfields(path, '/')
313 dirs, file = dirs[:-1], dirs[-1]
314 if dirs and not dirs[0]: dirs = dirs[1:]
315 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000316 try:
317 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000318 self.ftpcache[key] = \
319 ftpwrapper(user, passwd,
320 host, port, dirs)
321 if not file: type = 'D'
322 else: type = 'I'
323 for attr in attrs:
324 attr, value = splitvalue(attr)
325 if string.lower(attr) == 'type' and \
326 value in ('a', 'A', 'i', 'I', 'd', 'D'):
327 type = string.upper(value)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000328 return addinfourl(self.ftpcache[key].retrfile(file, type),
329 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000330 except ftperrors(), msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000331 raise IOError, ('ftp error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000332
333
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000334# Derived class with handlers for errors we can handle (perhaps)
335class FancyURLopener(URLopener):
336
337 def __init__(self, *args):
338 apply(URLopener.__init__, (self,) + args)
339 self.auth_cache = {}
340
341 # Default error handling -- don't raise an exception
342 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000343 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000344
Guido van Rossume6ad8911996-09-10 17:02:56 +0000345 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000346 def http_error_302(self, url, fp, errcode, errmsg, headers):
347 # XXX The server can force infinite recursion here!
348 if headers.has_key('location'):
349 newurl = headers['location']
350 elif headers.has_key('uri'):
351 newurl = headers['uri']
352 else:
353 return
354 void = fp.read()
355 fp.close()
356 return self.open(newurl)
357
Guido van Rossume6ad8911996-09-10 17:02:56 +0000358 # Error 301 -- also relocated (permanently)
359 http_error_301 = http_error_302
360
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000361 # Error 401 -- authentication required
362 # See this URL for a description of the basic authentication scheme:
363 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
364 def http_error_401(self, url, fp, errcode, errmsg, headers):
365 if headers.has_key('www-authenticate'):
366 stuff = headers['www-authenticate']
367 p = regex.compile(
368 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
369 if p.match(stuff) >= 0:
370 scheme, realm = p.group(1, 2)
371 if string.lower(scheme) == 'basic':
372 return self.retry_http_basic_auth(
373 url, realm)
374
375 def retry_http_basic_auth(self, url, realm):
376 host, selector = splithost(url)
377 i = string.find(host, '@') + 1
378 host = host[i:]
379 user, passwd = self.get_user_passwd(host, realm, i)
380 if not (user or passwd): return None
381 host = user + ':' + passwd + '@' + host
382 newurl = '//' + host + selector
383 return self.open_http(newurl)
384
385 def get_user_passwd(self, host, realm, clear_cache = 0):
386 key = realm + '@' + string.lower(host)
387 if self.auth_cache.has_key(key):
388 if clear_cache:
389 del self.auth_cache[key]
390 else:
391 return self.auth_cache[key]
392 user, passwd = self.prompt_user_passwd(host, realm)
393 if user or passwd: self.auth_cache[key] = (user, passwd)
394 return user, passwd
395
396 def prompt_user_passwd(self, host, realm):
397 # Override this in a GUI environment!
398 try:
399 user = raw_input("Enter username for %s at %s: " %
400 (realm, host))
401 self.echo_off()
402 try:
403 passwd = raw_input(
404 "Enter password for %s in %s at %s: " %
405 (user, realm, host))
406 finally:
407 self.echo_on()
408 return user, passwd
409 except KeyboardInterrupt:
410 return None, None
411
412 def echo_off(self):
413 import os
414 os.system("stty -echo")
415
416 def echo_on(self):
417 import os
418 print
419 os.system("stty echo")
420
421
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000422# Utility functions
423
424# Return the IP address of the magic hostname 'localhost'
425_localhost = None
426def localhost():
427 global _localhost
428 if not _localhost:
429 _localhost = socket.gethostbyname('localhost')
430 return _localhost
431
432# Return the IP address of the current host
433_thishost = None
434def thishost():
435 global _thishost
436 if not _thishost:
437 _thishost = socket.gethostbyname(socket.gethostname())
438 return _thishost
439
440# Return the set of errors raised by the FTP class
441_ftperrors = None
442def ftperrors():
443 global _ftperrors
444 if not _ftperrors:
445 import ftplib
446 _ftperrors = (ftplib.error_reply,
447 ftplib.error_temp,
448 ftplib.error_perm,
449 ftplib.error_proto)
450 return _ftperrors
451
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000452# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000453_noheaders = None
454def noheaders():
455 global _noheaders
456 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000457 import mimetools
458 import StringIO
459 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000460 _noheaders.fp.close() # Recycle file descriptor
461 return _noheaders
462
463
464# Utility classes
465
466# Class used by open_ftp() for cache of open FTP connections
467class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000468 def __init__(self, user, passwd, host, port, dirs):
469 self.user = unquote(user or '')
470 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000471 self.host = host
472 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000473 self.dirs = []
474 for dir in dirs:
475 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000476 self.init()
477 def init(self):
478 import ftplib
479 self.ftp = ftplib.FTP()
480 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000481 self.ftp.login(self.user, self.passwd)
482 for dir in self.dirs:
483 self.ftp.cwd(dir)
484 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000485 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000486 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
487 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000488 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000489 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000490 except ftplib.all_errors:
491 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000492 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000493 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000494 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000495 try:
496 cmd = 'RETR ' + file
497 conn = self.ftp.transfercmd(cmd)
498 except ftplib.error_perm, reason:
499 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000500 raise IOError, ('ftp error', reason), \
501 sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000502 if not conn:
503 # Try a directory listing
504 if file: cmd = 'LIST ' + file
505 else: cmd = 'LIST'
506 conn = self.ftp.transfercmd(cmd)
Jack Jansen0d12ead1996-02-14 16:05:20 +0000507 return addclosehook(conn.makefile('rb'), self.ftp.voidresp)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000508
509# Base class for addinfo and addclosehook
510class addbase:
511 def __init__(self, fp):
512 self.fp = fp
513 self.read = self.fp.read
514 self.readline = self.fp.readline
515 self.readlines = self.fp.readlines
516 self.fileno = self.fp.fileno
517 def __repr__(self):
518 return '<%s at %s whose fp = %s>' % (
519 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000520 def close(self):
521 self.read = None
522 self.readline = None
523 self.readlines = None
524 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000525 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000526 self.fp = None
527
528# Class to add a close hook to an open file
529class addclosehook(addbase):
530 def __init__(self, fp, closehook, *hookargs):
531 addbase.__init__(self, fp)
532 self.closehook = closehook
533 self.hookargs = hookargs
534 def close(self):
535 if self.closehook:
536 apply(self.closehook, self.hookargs)
537 self.closehook = None
538 self.hookargs = None
539 addbase.close(self)
540
541# class to add an info() method to an open file
542class addinfo(addbase):
543 def __init__(self, fp, headers):
544 addbase.__init__(self, fp)
545 self.headers = headers
546 def info(self):
547 return self.headers
548
Guido van Rossume6ad8911996-09-10 17:02:56 +0000549# class to add info() and geturl() methods to an open file
550class addinfourl(addbase):
551 def __init__(self, fp, headers, url):
552 addbase.__init__(self, fp)
553 self.headers = headers
554 self.url = url
555 def info(self):
556 return self.headers
557 def geturl(self):
558 return self.url
559
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000560
561# Utility to combine a URL with a base URL to form a new URL
562
563def basejoin(base, url):
564 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000565 if type:
566 # if url is complete (i.e., it contains a type), return it
567 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000568 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000569 type, basepath = splittype(base) # inherit type from base
570 if host:
571 # if url contains host, just inherit type
572 if type: return type + '://' + host + path
573 else:
574 # no type inherited, so url must have started with //
575 # just return it
576 return url
577 host, basepath = splithost(basepath) # inherit host
578 basepath, basetag = splittag(basepath) # remove extraneuous cruft
579 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000580 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000581 # non-absolute path name
582 if path[:1] in ('#', '?'):
583 # path is just a tag or query, attach to basepath
584 i = len(basepath)
585 else:
586 # else replace last component
587 i = string.rfind(basepath, '/')
588 if i < 0:
589 # basepath not absolute
590 if host:
591 # host present, make absolute
592 basepath = '/'
593 else:
594 # else keep non-absolute
595 basepath = ''
596 else:
597 # remove last file component
598 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000599 # Interpret ../ (important because of symlinks)
600 while basepath and path[:3] == '../':
601 path = path[3:]
602 i = string.rfind(basepath, '/')
603 if i > 0:
604 basepath = basepath[:i-1]
605
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000606 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000607 if type and host: return type + '://' + host + path
608 elif type: return type + ':' + path
609 elif host: return '//' + host + path # don't know what this means
610 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000611
612
Guido van Rossum7c395db1994-07-04 22:14:49 +0000613# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000614# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000615# splittype('type:opaquestring') --> 'type', 'opaquestring'
616# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000617# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
618# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000619# splitport('host:port') --> 'host', 'port'
620# splitquery('/path?query') --> '/path', 'query'
621# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000622# splitattr('/path;attr1=value1;attr2=value2;...') ->
623# '/path', ['attr1=value1', 'attr2=value2', ...]
624# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000625# splitgophertype('/Xselector') --> 'X', 'selector'
626# unquote('abc%20def') -> 'abc def'
627# quote('abc def') -> 'abc%20def')
628
629def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000630 url = string.strip(url)
631 if url[:1] == '<' and url[-1:] == '>':
632 url = string.strip(url[1:-1])
633 if url[:4] == 'URL:': url = string.strip(url[4:])
634 return url
635
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000636_typeprog = regex.compile('^\([^/:]+\):')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000637def splittype(url):
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000638 if _typeprog.match(url) >= 0:
639 scheme = _typeprog.group(1)
640 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000641 return None, url
642
643_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
644def splithost(url):
645 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
646 return None, url
647
Guido van Rossum7c395db1994-07-04 22:14:49 +0000648_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
649def splituser(host):
650 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
651 return None, host
652
653_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
654def splitpasswd(user):
655 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
656 return user, None
657
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000658_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
659def splitport(host):
660 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
661 return host, None
662
Guido van Rossum53725a21996-06-13 19:12:35 +0000663# Split host and port, returning numeric port.
664# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000665# Return numerical port if a valid number are found after ':'.
666# Return None if ':' but not a valid number.
667_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000668def splitnport(host, defport=-1):
669 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000670 host, port = _nportprog.group(1, 2)
671 try:
672 if not port: raise string.atoi_error, "no digits"
673 nport = string.atoi(port)
674 except string.atoi_error:
675 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000676 return host, nport
677 return host, defport
678
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000679_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
680def splitquery(url):
681 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
682 return url, None
683
684_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
685def splittag(url):
686 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
687 return url, None
688
Guido van Rossum7c395db1994-07-04 22:14:49 +0000689def splitattr(url):
690 words = string.splitfields(url, ';')
691 return words[0], words[1:]
692
693_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
694def splitvalue(attr):
695 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
696 return attr, None
697
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000698def splitgophertype(selector):
699 if selector[:1] == '/' and selector[1:2]:
700 return selector[1], selector[2:]
701 return None, selector
702
703_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
704def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000705 i = 0
706 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000707 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000708 while 0 <= i < n:
709 j = _quoteprog.search(s, i)
710 if j < 0:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000711 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000712 break
Guido van Rossumf8abb381996-08-26 15:56:12 +0000713 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000714 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000715 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000716
Guido van Rossum0564e121996-12-13 14:47:36 +0000717def unquote_plus(s):
718 if '+' in s:
719 import regsub
720 s = regsub.gsub('+', ' ', s)
721 return unquote(s)
722
Guido van Rossum3bb54481994-08-29 10:52:58 +0000723always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000724def quote(s, safe = '/'):
725 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000726 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000727 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000728 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000729 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000730 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000731 res.append('%%%02x' % ord(c))
732 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000733
Guido van Rossum0564e121996-12-13 14:47:36 +0000734def quote_plus(s, safe = '/'):
735 if ' ' in s:
736 import regsub
737 s = regsub.gsub(' ', '+', s)
738 return quote(s, safe + '+')
739 else:
740 return quote(s, safe)
741
Guido van Rossum442e7201996-03-20 15:33:11 +0000742
743# Proxy handling
744def getproxies():
745 """Return a dictionary of protocol scheme -> proxy server URL mappings.
746
747 Scan the environment for variables named <scheme>_proxy;
748 this seems to be the standard convention. If you need a
749 different way, you can pass a proxies dictionary to the
750 [Fancy]URLopener constructor.
751
752 """
753 proxies = {}
754 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000755 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000756 if value and name[-6:] == '_proxy':
757 proxies[name[:-6]] = value
758 return proxies
759
760
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000761# Test and time quote() and unquote()
762def test1():
763 import time
764 s = ''
765 for i in range(256): s = s + chr(i)
766 s = s*4
767 t0 = time.time()
768 qs = quote(s)
769 uqs = unquote(qs)
770 t1 = time.time()
771 if uqs != s:
772 print 'Wrong!'
773 print `s`
774 print `qs`
775 print `uqs`
776 print round(t1 - t0, 3), 'sec'
777
778
779# Test program
780def test():
781 import sys
782 import regsub
783 args = sys.argv[1:]
784 if not args:
785 args = [
786 '/etc/passwd',
787 'file:/etc/passwd',
788 'file://localhost/etc/passwd',
789 'ftp://ftp.cwi.nl/etc/passwd',
790 'gopher://gopher.cwi.nl/11/',
791 'http://www.cwi.nl/index.html',
792 ]
793 try:
794 for url in args:
795 print '-'*10, url, '-'*10
796 fn, h = urlretrieve(url)
797 print fn, h
798 if h:
799 print '======'
800 for k in h.keys(): print k + ':', h[k]
801 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000802 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000803 data = fp.read()
804 del fp
805 print regsub.gsub('\r', '', data)
806 fn, h = None, None
807 print '-'*40
808 finally:
809 urlcleanup()
810
811# Run test program when run as a script
812if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000813## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000814 test()