blob: 82a26b3b2e6d6f9eaffa86edd2f675fe1bfb07cd [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 Rossumf668d171997-06-06 21:11:11 +000031__version__ = '1.7'
32
33MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
Guido van Rossum6cb15a01995-06-22 19:00:13 +000034
Jack Jansendc3e3f61995-12-15 13:22:13 +000035# Helper for non-unix systems
36if os.name == 'mac':
Guido van Rossum71ac9451996-03-21 16:31:41 +000037 from macurl2path import url2pathname, pathname2url
Guido van Rossum2281d351996-06-26 19:47:37 +000038elif os.name == 'nt':
39 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000040else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000041 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000042 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000043 def pathname2url(pathname):
44 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000045
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000046# This really consists of two pieces:
47# (1) a class which handles opening of all sorts of URLs
48# (plus assorted utilities etc.)
49# (2) a set of functions for parsing URLs
50# XXX Should these be separated out into different modules?
51
52
53# Shortcut for basic usage
54_urlopener = None
Guido van Rossumbd013741996-12-10 16:00:28 +000055def urlopen(url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000056 global _urlopener
57 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000058 _urlopener = FancyURLopener()
Guido van Rossumbd013741996-12-10 16:00:28 +000059 if data is None:
60 return _urlopener.open(url)
61 else:
62 return _urlopener.open(url, data)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000063def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000064 global _urlopener
65 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000066 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000067 if filename:
68 return _urlopener.retrieve(url, filename)
69 else:
70 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000071def urlcleanup():
72 if _urlopener:
73 _urlopener.cleanup()
74
75
76# Class to open URLs.
77# This is a class rather than just a subroutine because we may need
78# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000079# Note -- this is a base class for those who don't want the
80# automatic handling of errors type 302 (relocated) and 401
81# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000082ftpcache = {}
83class URLopener:
84
Guido van Rossum29e77811996-11-27 19:39:58 +000085 tempcache = None # So close() in __del__() won't fail
86
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000087 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000088 def __init__(self, proxies=None):
89 if proxies is None:
90 proxies = getproxies()
91 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +000092 server_version = "Python-urllib/%s" % __version__
93 self.addheaders = [('User-agent', server_version)]
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000094 self.tempcache = None
95 # Undocumented feature: if you assign {} to tempcache,
96 # it is used to cache files retrieved with
97 # self.retrieve(). This is not enabled by default
98 # since it does not work for changing documents (and I
99 # haven't got the logic to check expiration headers
100 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000101 self.ftpcache = ftpcache
102 # Undocumented feature: you can use a different
103 # ftp cache by assigning to the .ftpcache member;
104 # in case you want logically independent URL openers
105
106 def __del__(self):
107 self.close()
108
109 def close(self):
110 self.cleanup()
111
112 def cleanup(self):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000113 if self.tempcache:
Guido van Rossumd23d9401997-01-30 15:54:58 +0000114 import os
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000115 for url in self.tempcache.keys():
116 try:
117 os.unlink(self.tempcache[url][0])
118 except os.error:
119 pass
120 del self.tempcache[url]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000121
122 # Add a header to be used by the HTTP interface only
123 # e.g. u.addheader('Accept', 'sound/basic')
124 def addheader(self, *args):
125 self.addheaders.append(args)
126
127 # External interface
128 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumbd013741996-12-10 16:00:28 +0000129 def open(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000130 fullurl = unwrap(fullurl)
131 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000132 if not type: type = 'file'
Guido van Rossume6ad8911996-09-10 17:02:56 +0000133 self.openedurl = '%s:%s' % (type, url)
Guido van Rossum442e7201996-03-20 15:33:11 +0000134 if self.proxies.has_key(type):
135 proxy = self.proxies[type]
136 type, proxy = splittype(proxy)
137 host, selector = splithost(proxy)
138 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000139 name = 'open_' + type
140 if '-' in name:
141 import regsub
142 name = regsub.gsub('-', '_', name)
143 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000144 if data is None:
145 return self.open_unknown(fullurl)
146 else:
147 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000148 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000149 if data is None:
150 return getattr(self, name)(url)
151 else:
152 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000153 except socket.error, msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000154 raise IOError, ('socket error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000155
Guido van Rossumca445401995-08-29 19:19:12 +0000156 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000157 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000158 type, url = splittype(fullurl)
159 raise IOError, ('url error', 'unknown url type', type)
160
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000161 # External interface
162 # retrieve(url) returns (filename, None) for a local object
163 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000164 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000165 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000166 return self.tempcache[url]
167 url1 = unwrap(url)
Guido van Rossum5b1b33c1996-10-22 13:28:37 +0000168 self.openedurl = url1
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000169 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000170 self.tempcache[url] = self.tempcache[url1]
171 return self.tempcache[url1]
172 type, url1 = splittype(url1)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000173 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000174 try:
175 fp = self.open_local_file(url1)
176 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000177 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000178 except IOError, msg:
179 pass
180 fp = self.open(url)
181 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000182 if not filename:
183 import tempfile
184 filename = tempfile.mktemp()
185 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000186 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000187 self.tempcache[url] = result
Guido van Rossumc511aee1997-04-11 19:01:48 +0000188 tfp = open(filename, 'wb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000189 bs = 1024*8
190 block = fp.read(bs)
191 while block:
192 tfp.write(block)
193 block = fp.read(bs)
Guido van Rossumab0abdc1997-08-26 19:06:40 +0000194 fp.close()
195 tfp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000196 del fp
197 del tfp
198 return result
199
200 # Each method named open_<type> knows how to open that type of URL
201
202 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000203 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000204 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000205 if type(url) is type(""):
206 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000207 user_passwd, host = splituser(host)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000208 realhost = host
Guido van Rossum442e7201996-03-20 15:33:11 +0000209 else:
210 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000211 urltype, rest = splittype(selector)
Guido van Rossumfd795661997-04-02 05:46:35 +0000212 user_passwd = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000213 if string.lower(urltype) != 'http':
214 realhost = None
215 else:
Guido van Rossum78c96371996-08-26 18:09:59 +0000216 realhost, rest = splithost(rest)
217 user_passwd, realhost = splituser(realhost)
218 if user_passwd:
219 selector = "%s://%s%s" % (urltype,
220 realhost, rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000221 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000222 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000223 if user_passwd:
224 import base64
225 auth = string.strip(base64.encodestring(user_passwd))
226 else:
227 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000228 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000229 if data is not None:
230 h.putrequest('POST', selector)
231 h.putheader('Content-type',
232 'application/x-www-form-urlencoded')
233 h.putheader('Content-length', '%d' % len(data))
234 else:
235 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000236 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000237 if realhost: h.putheader('Host', realhost)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000238 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000239 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000240 if data is not None:
241 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000242 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000243 fp = h.getfile()
244 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000245 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000246 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000247 return self.http_error(url,
248 fp, errcode, errmsg, headers)
249
250 # Handle http errors.
251 # Derived class can override this, or provide specific handlers
252 # named http_error_DDD where DDD is the 3-digit error code
253 def http_error(self, url, fp, errcode, errmsg, headers):
254 # First check if there's a specific handler for this error
255 name = 'http_error_%d' % errcode
256 if hasattr(self, name):
257 method = getattr(self, name)
258 result = method(url, fp, errcode, errmsg, headers)
259 if result: return result
260 return self.http_error_default(
261 url, fp, errcode, errmsg, headers)
262
263 # Default http error handler: close the connection and raises IOError
264 def http_error_default(self, url, fp, errcode, errmsg, headers):
265 void = fp.read()
266 fp.close()
267 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000268
269 # Use Gopher protocol
270 def open_gopher(self, url):
271 import gopherlib
272 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000273 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000274 type, selector = splitgophertype(selector)
275 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000276 selector = unquote(selector)
277 if query:
278 query = unquote(query)
279 fp = gopherlib.send_query(selector, query, host)
280 else:
281 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000282 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000283
284 # Use local file or FTP depending on form of URL
285 def open_file(self, url):
Guido van Rossumb6784dc1997-08-20 23:34:01 +0000286 if url[:2] == '//' and url[2:3] != '/':
287 return self.open_ftp(url)
288 else:
289 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000290
291 # Use local file
292 def open_local_file(self, url):
293 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000294 if not host:
Guido van Rossum2966b321997-06-06 17:44:07 +0000295 return addinfourl(
296 open(url2pathname(file), 'rb'),
297 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000298 host, port = splitport(host)
299 if not port and socket.gethostbyname(host) in (
300 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000301 file = unquote(file)
Guido van Rossum2966b321997-06-06 17:44:07 +0000302 return addinfourl(
303 open(url2pathname(file), 'rb'),
304 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000305 raise IOError, ('local file error', 'not on local host')
306
307 # Use FTP protocol
308 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000309 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000310 if not host: raise IOError, ('ftp error', 'no host given')
311 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000312 user, host = splituser(host)
313 if user: user, passwd = splitpasswd(user)
314 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000315 host = socket.gethostbyname(host)
316 if not port:
317 import ftplib
318 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000319 path, attrs = splitattr(path)
320 dirs = string.splitfields(path, '/')
321 dirs, file = dirs[:-1], dirs[-1]
322 if dirs and not dirs[0]: dirs = dirs[1:]
323 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossumf668d171997-06-06 21:11:11 +0000324 if len(self.ftpcache) > MAXFTPCACHE:
325 # Prune the cache, rather arbitrarily
326 for k in self.ftpcache.keys():
327 if k != key:
328 v = self.ftpcache[k]
329 del self.ftpcache[k]
330 v.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000331 try:
332 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000333 self.ftpcache[key] = \
334 ftpwrapper(user, passwd,
335 host, port, dirs)
336 if not file: type = 'D'
337 else: type = 'I'
338 for attr in attrs:
339 attr, value = splitvalue(attr)
340 if string.lower(attr) == 'type' and \
341 value in ('a', 'A', 'i', 'I', 'd', 'D'):
342 type = string.upper(value)
Guido van Rossum2966b321997-06-06 17:44:07 +0000343 return addinfourl(
344 self.ftpcache[key].retrfile(file, type),
345 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000346 except ftperrors(), msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000347 raise IOError, ('ftp error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000348
349
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000350# Derived class with handlers for errors we can handle (perhaps)
351class FancyURLopener(URLopener):
352
353 def __init__(self, *args):
354 apply(URLopener.__init__, (self,) + args)
355 self.auth_cache = {}
356
357 # Default error handling -- don't raise an exception
358 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000359 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000360
Guido van Rossume6ad8911996-09-10 17:02:56 +0000361 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000362 def http_error_302(self, url, fp, errcode, errmsg, headers):
363 # XXX The server can force infinite recursion here!
364 if headers.has_key('location'):
365 newurl = headers['location']
366 elif headers.has_key('uri'):
367 newurl = headers['uri']
368 else:
369 return
370 void = fp.read()
371 fp.close()
372 return self.open(newurl)
373
Guido van Rossume6ad8911996-09-10 17:02:56 +0000374 # Error 301 -- also relocated (permanently)
375 http_error_301 = http_error_302
376
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000377 # Error 401 -- authentication required
378 # See this URL for a description of the basic authentication scheme:
379 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
380 def http_error_401(self, url, fp, errcode, errmsg, headers):
381 if headers.has_key('www-authenticate'):
382 stuff = headers['www-authenticate']
383 p = regex.compile(
384 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
385 if p.match(stuff) >= 0:
386 scheme, realm = p.group(1, 2)
387 if string.lower(scheme) == 'basic':
388 return self.retry_http_basic_auth(
389 url, realm)
390
391 def retry_http_basic_auth(self, url, realm):
392 host, selector = splithost(url)
393 i = string.find(host, '@') + 1
394 host = host[i:]
395 user, passwd = self.get_user_passwd(host, realm, i)
396 if not (user or passwd): return None
397 host = user + ':' + passwd + '@' + host
398 newurl = '//' + host + selector
399 return self.open_http(newurl)
400
401 def get_user_passwd(self, host, realm, clear_cache = 0):
402 key = realm + '@' + string.lower(host)
403 if self.auth_cache.has_key(key):
404 if clear_cache:
405 del self.auth_cache[key]
406 else:
407 return self.auth_cache[key]
408 user, passwd = self.prompt_user_passwd(host, realm)
409 if user or passwd: self.auth_cache[key] = (user, passwd)
410 return user, passwd
411
412 def prompt_user_passwd(self, host, realm):
413 # Override this in a GUI environment!
414 try:
415 user = raw_input("Enter username for %s at %s: " %
416 (realm, host))
417 self.echo_off()
418 try:
419 passwd = raw_input(
420 "Enter password for %s in %s at %s: " %
421 (user, realm, host))
422 finally:
423 self.echo_on()
424 return user, passwd
425 except KeyboardInterrupt:
426 return None, None
427
428 def echo_off(self):
429 import os
430 os.system("stty -echo")
431
432 def echo_on(self):
433 import os
434 print
435 os.system("stty echo")
436
437
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000438# Utility functions
439
440# Return the IP address of the magic hostname 'localhost'
441_localhost = None
442def localhost():
443 global _localhost
444 if not _localhost:
445 _localhost = socket.gethostbyname('localhost')
446 return _localhost
447
448# Return the IP address of the current host
449_thishost = None
450def thishost():
451 global _thishost
452 if not _thishost:
453 _thishost = socket.gethostbyname(socket.gethostname())
454 return _thishost
455
456# Return the set of errors raised by the FTP class
457_ftperrors = None
458def ftperrors():
459 global _ftperrors
460 if not _ftperrors:
461 import ftplib
Guido van Rossum2966b321997-06-06 17:44:07 +0000462 _ftperrors = ftplib.all_errors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000463 return _ftperrors
464
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000465# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000466_noheaders = None
467def noheaders():
468 global _noheaders
469 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000470 import mimetools
471 import StringIO
472 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000473 _noheaders.fp.close() # Recycle file descriptor
474 return _noheaders
475
476
477# Utility classes
478
479# Class used by open_ftp() for cache of open FTP connections
480class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000481 def __init__(self, user, passwd, host, port, dirs):
482 self.user = unquote(user or '')
483 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000484 self.host = host
485 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000486 self.dirs = []
487 for dir in dirs:
488 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000489 self.init()
490 def init(self):
491 import ftplib
492 self.ftp = ftplib.FTP()
493 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000494 self.ftp.login(self.user, self.passwd)
495 for dir in self.dirs:
496 self.ftp.cwd(dir)
497 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000498 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000499 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
500 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000501 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000502 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000503 except ftplib.all_errors:
504 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000505 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000506 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000507 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000508 try:
509 cmd = 'RETR ' + file
510 conn = self.ftp.transfercmd(cmd)
511 except ftplib.error_perm, reason:
512 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000513 raise IOError, ('ftp error', reason), \
514 sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000515 if not conn:
516 # Try a directory listing
517 if file: cmd = 'LIST ' + file
518 else: cmd = 'LIST'
519 conn = self.ftp.transfercmd(cmd)
Guido van Rossumf668d171997-06-06 21:11:11 +0000520 return addclosehook(conn.makefile('rb'), self.endtransfer)
521 def endtransfer(self):
522 try:
523 self.ftp.voidresp()
524 except ftperrors():
525 pass
526 def close(self):
527 try:
528 self.ftp.close()
529 except ftperrors():
530 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000531
532# Base class for addinfo and addclosehook
533class addbase:
534 def __init__(self, fp):
535 self.fp = fp
536 self.read = self.fp.read
537 self.readline = self.fp.readline
538 self.readlines = self.fp.readlines
539 self.fileno = self.fp.fileno
540 def __repr__(self):
541 return '<%s at %s whose fp = %s>' % (
542 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000543 def close(self):
544 self.read = None
545 self.readline = None
546 self.readlines = None
547 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000548 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000549 self.fp = None
550
551# Class to add a close hook to an open file
552class addclosehook(addbase):
553 def __init__(self, fp, closehook, *hookargs):
554 addbase.__init__(self, fp)
555 self.closehook = closehook
556 self.hookargs = hookargs
557 def close(self):
558 if self.closehook:
559 apply(self.closehook, self.hookargs)
560 self.closehook = None
561 self.hookargs = None
562 addbase.close(self)
563
564# class to add an info() method to an open file
565class addinfo(addbase):
566 def __init__(self, fp, headers):
567 addbase.__init__(self, fp)
568 self.headers = headers
569 def info(self):
570 return self.headers
571
Guido van Rossume6ad8911996-09-10 17:02:56 +0000572# class to add info() and geturl() methods to an open file
573class addinfourl(addbase):
574 def __init__(self, fp, headers, url):
575 addbase.__init__(self, fp)
576 self.headers = headers
577 self.url = url
578 def info(self):
579 return self.headers
580 def geturl(self):
581 return self.url
582
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000583
584# Utility to combine a URL with a base URL to form a new URL
585
586def basejoin(base, url):
587 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000588 if type:
589 # if url is complete (i.e., it contains a type), return it
590 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000591 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000592 type, basepath = splittype(base) # inherit type from base
593 if host:
594 # if url contains host, just inherit type
595 if type: return type + '://' + host + path
596 else:
597 # no type inherited, so url must have started with //
598 # just return it
599 return url
600 host, basepath = splithost(basepath) # inherit host
601 basepath, basetag = splittag(basepath) # remove extraneuous cruft
602 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000603 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000604 # non-absolute path name
605 if path[:1] in ('#', '?'):
606 # path is just a tag or query, attach to basepath
607 i = len(basepath)
608 else:
609 # else replace last component
610 i = string.rfind(basepath, '/')
611 if i < 0:
612 # basepath not absolute
613 if host:
614 # host present, make absolute
615 basepath = '/'
616 else:
617 # else keep non-absolute
618 basepath = ''
619 else:
620 # remove last file component
621 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000622 # Interpret ../ (important because of symlinks)
623 while basepath and path[:3] == '../':
624 path = path[3:]
625 i = string.rfind(basepath, '/')
626 if i > 0:
627 basepath = basepath[:i-1]
628
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000629 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000630 if type and host: return type + '://' + host + path
631 elif type: return type + ':' + path
632 elif host: return '//' + host + path # don't know what this means
633 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000634
635
Guido van Rossum7c395db1994-07-04 22:14:49 +0000636# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000637# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000638# splittype('type:opaquestring') --> 'type', 'opaquestring'
639# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000640# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
641# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000642# splitport('host:port') --> 'host', 'port'
643# splitquery('/path?query') --> '/path', 'query'
644# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000645# splitattr('/path;attr1=value1;attr2=value2;...') ->
646# '/path', ['attr1=value1', 'attr2=value2', ...]
647# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000648# splitgophertype('/Xselector') --> 'X', 'selector'
649# unquote('abc%20def') -> 'abc def'
650# quote('abc def') -> 'abc%20def')
651
652def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000653 url = string.strip(url)
654 if url[:1] == '<' and url[-1:] == '>':
655 url = string.strip(url[1:-1])
656 if url[:4] == 'URL:': url = string.strip(url[4:])
657 return url
658
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000659_typeprog = regex.compile('^\([^/:]+\):')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000660def splittype(url):
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000661 if _typeprog.match(url) >= 0:
662 scheme = _typeprog.group(1)
663 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000664 return None, url
665
666_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
667def splithost(url):
668 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
669 return None, url
670
Guido van Rossum7c395db1994-07-04 22:14:49 +0000671_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
672def splituser(host):
673 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
674 return None, host
675
676_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
677def splitpasswd(user):
678 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
679 return user, None
680
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000681_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
682def splitport(host):
683 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
684 return host, None
685
Guido van Rossum53725a21996-06-13 19:12:35 +0000686# Split host and port, returning numeric port.
687# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000688# Return numerical port if a valid number are found after ':'.
689# Return None if ':' but not a valid number.
690_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000691def splitnport(host, defport=-1):
692 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000693 host, port = _nportprog.group(1, 2)
694 try:
695 if not port: raise string.atoi_error, "no digits"
696 nport = string.atoi(port)
697 except string.atoi_error:
698 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000699 return host, nport
700 return host, defport
701
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000702_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
703def splitquery(url):
704 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
705 return url, None
706
707_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
708def splittag(url):
709 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
710 return url, None
711
Guido van Rossum7c395db1994-07-04 22:14:49 +0000712def splitattr(url):
713 words = string.splitfields(url, ';')
714 return words[0], words[1:]
715
716_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
717def splitvalue(attr):
718 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
719 return attr, None
720
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000721def splitgophertype(selector):
722 if selector[:1] == '/' and selector[1:2]:
723 return selector[1], selector[2:]
724 return None, selector
725
726_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
727def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000728 i = 0
729 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000730 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000731 while 0 <= i < n:
732 j = _quoteprog.search(s, i)
733 if j < 0:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000734 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000735 break
Guido van Rossumf8abb381996-08-26 15:56:12 +0000736 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000737 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000738 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000739
Guido van Rossum0564e121996-12-13 14:47:36 +0000740def unquote_plus(s):
741 if '+' in s:
742 import regsub
743 s = regsub.gsub('+', ' ', s)
744 return unquote(s)
745
Guido van Rossum3bb54481994-08-29 10:52:58 +0000746always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000747def quote(s, safe = '/'):
748 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000749 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000750 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000751 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000752 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000753 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000754 res.append('%%%02x' % ord(c))
755 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000756
Guido van Rossum0564e121996-12-13 14:47:36 +0000757def quote_plus(s, safe = '/'):
758 if ' ' in s:
759 import regsub
760 s = regsub.gsub(' ', '+', s)
761 return quote(s, safe + '+')
762 else:
763 return quote(s, safe)
764
Guido van Rossum442e7201996-03-20 15:33:11 +0000765
766# Proxy handling
767def getproxies():
768 """Return a dictionary of protocol scheme -> proxy server URL mappings.
769
770 Scan the environment for variables named <scheme>_proxy;
771 this seems to be the standard convention. If you need a
772 different way, you can pass a proxies dictionary to the
773 [Fancy]URLopener constructor.
774
775 """
776 proxies = {}
777 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000778 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000779 if value and name[-6:] == '_proxy':
780 proxies[name[:-6]] = value
781 return proxies
782
783
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000784# Test and time quote() and unquote()
785def test1():
786 import time
787 s = ''
788 for i in range(256): s = s + chr(i)
789 s = s*4
790 t0 = time.time()
791 qs = quote(s)
792 uqs = unquote(qs)
793 t1 = time.time()
794 if uqs != s:
795 print 'Wrong!'
796 print `s`
797 print `qs`
798 print `uqs`
799 print round(t1 - t0, 3), 'sec'
800
801
802# Test program
803def test():
804 import sys
805 import regsub
806 args = sys.argv[1:]
807 if not args:
808 args = [
809 '/etc/passwd',
810 'file:/etc/passwd',
811 'file://localhost/etc/passwd',
812 'ftp://ftp.cwi.nl/etc/passwd',
813 'gopher://gopher.cwi.nl/11/',
814 'http://www.cwi.nl/index.html',
815 ]
816 try:
817 for url in args:
818 print '-'*10, url, '-'*10
819 fn, h = urlretrieve(url)
820 print fn, h
821 if h:
822 print '======'
823 for k in h.keys(): print k + ':', h[k]
824 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000825 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000826 data = fp.read()
827 del fp
828 print regsub.gsub('\r', '', data)
829 fn, h = None, None
830 print '-'*40
831 finally:
832 urlcleanup()
833
834# Run test program when run as a script
835if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000836## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000837 test()