blob: d9040cc99e82908a66831074724648d9853f00e0 [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)
194 del fp
195 del tfp
196 return result
197
198 # Each method named open_<type> knows how to open that type of URL
199
200 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000201 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000202 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000203 if type(url) is type(""):
204 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000205 user_passwd, host = splituser(host)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000206 realhost = host
Guido van Rossum442e7201996-03-20 15:33:11 +0000207 else:
208 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000209 urltype, rest = splittype(selector)
Guido van Rossumfd795661997-04-02 05:46:35 +0000210 user_passwd = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000211 if string.lower(urltype) != 'http':
212 realhost = None
213 else:
Guido van Rossum78c96371996-08-26 18:09:59 +0000214 realhost, rest = splithost(rest)
215 user_passwd, realhost = splituser(realhost)
216 if user_passwd:
217 selector = "%s://%s%s" % (urltype,
218 realhost, rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000219 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000220 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000221 if user_passwd:
222 import base64
223 auth = string.strip(base64.encodestring(user_passwd))
224 else:
225 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000226 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000227 if data is not None:
228 h.putrequest('POST', selector)
229 h.putheader('Content-type',
230 'application/x-www-form-urlencoded')
231 h.putheader('Content-length', '%d' % len(data))
232 else:
233 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000234 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000235 if realhost: h.putheader('Host', realhost)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000236 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000237 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000238 if data is not None:
239 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000240 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000241 fp = h.getfile()
242 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000243 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000244 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000245 return self.http_error(url,
246 fp, errcode, errmsg, headers)
247
248 # Handle http errors.
249 # Derived class can override this, or provide specific handlers
250 # named http_error_DDD where DDD is the 3-digit error code
251 def http_error(self, url, fp, errcode, errmsg, headers):
252 # First check if there's a specific handler for this error
253 name = 'http_error_%d' % errcode
254 if hasattr(self, name):
255 method = getattr(self, name)
256 result = method(url, fp, errcode, errmsg, headers)
257 if result: return result
258 return self.http_error_default(
259 url, fp, errcode, errmsg, headers)
260
261 # Default http error handler: close the connection and raises IOError
262 def http_error_default(self, url, fp, errcode, errmsg, headers):
263 void = fp.read()
264 fp.close()
265 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000266
267 # Use Gopher protocol
268 def open_gopher(self, url):
269 import gopherlib
270 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000271 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000272 type, selector = splitgophertype(selector)
273 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000274 selector = unquote(selector)
275 if query:
276 query = unquote(query)
277 fp = gopherlib.send_query(selector, query, host)
278 else:
279 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000280 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000281
282 # Use local file or FTP depending on form of URL
283 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000284 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000285 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000286 else:
287 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000288
289 # Use local file
290 def open_local_file(self, url):
291 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000292 if not host:
Guido van Rossum2966b321997-06-06 17:44:07 +0000293 return addinfourl(
294 open(url2pathname(file), 'rb'),
295 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000296 host, port = splitport(host)
297 if not port and socket.gethostbyname(host) in (
298 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000299 file = unquote(file)
Guido van Rossum2966b321997-06-06 17:44:07 +0000300 return addinfourl(
301 open(url2pathname(file), 'rb'),
302 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000303 raise IOError, ('local file error', 'not on local host')
304
305 # Use FTP protocol
306 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000307 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000308 if not host: raise IOError, ('ftp error', 'no host given')
309 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000310 user, host = splituser(host)
311 if user: user, passwd = splitpasswd(user)
312 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000313 host = socket.gethostbyname(host)
314 if not port:
315 import ftplib
316 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000317 path, attrs = splitattr(path)
318 dirs = string.splitfields(path, '/')
319 dirs, file = dirs[:-1], dirs[-1]
320 if dirs and not dirs[0]: dirs = dirs[1:]
321 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossumf668d171997-06-06 21:11:11 +0000322 if len(self.ftpcache) > MAXFTPCACHE:
323 # Prune the cache, rather arbitrarily
324 for k in self.ftpcache.keys():
325 if k != key:
326 v = self.ftpcache[k]
327 del self.ftpcache[k]
328 v.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000329 try:
330 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000331 self.ftpcache[key] = \
332 ftpwrapper(user, passwd,
333 host, port, dirs)
334 if not file: type = 'D'
335 else: type = 'I'
336 for attr in attrs:
337 attr, value = splitvalue(attr)
338 if string.lower(attr) == 'type' and \
339 value in ('a', 'A', 'i', 'I', 'd', 'D'):
340 type = string.upper(value)
Guido van Rossum2966b321997-06-06 17:44:07 +0000341 return addinfourl(
342 self.ftpcache[key].retrfile(file, type),
343 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000344 except ftperrors(), msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000345 raise IOError, ('ftp error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000346
347
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000348# Derived class with handlers for errors we can handle (perhaps)
349class FancyURLopener(URLopener):
350
351 def __init__(self, *args):
352 apply(URLopener.__init__, (self,) + args)
353 self.auth_cache = {}
354
355 # Default error handling -- don't raise an exception
356 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000357 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000358
Guido van Rossume6ad8911996-09-10 17:02:56 +0000359 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000360 def http_error_302(self, url, fp, errcode, errmsg, headers):
361 # XXX The server can force infinite recursion here!
362 if headers.has_key('location'):
363 newurl = headers['location']
364 elif headers.has_key('uri'):
365 newurl = headers['uri']
366 else:
367 return
368 void = fp.read()
369 fp.close()
370 return self.open(newurl)
371
Guido van Rossume6ad8911996-09-10 17:02:56 +0000372 # Error 301 -- also relocated (permanently)
373 http_error_301 = http_error_302
374
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000375 # Error 401 -- authentication required
376 # See this URL for a description of the basic authentication scheme:
377 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
378 def http_error_401(self, url, fp, errcode, errmsg, headers):
379 if headers.has_key('www-authenticate'):
380 stuff = headers['www-authenticate']
381 p = regex.compile(
382 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
383 if p.match(stuff) >= 0:
384 scheme, realm = p.group(1, 2)
385 if string.lower(scheme) == 'basic':
386 return self.retry_http_basic_auth(
387 url, realm)
388
389 def retry_http_basic_auth(self, url, realm):
390 host, selector = splithost(url)
391 i = string.find(host, '@') + 1
392 host = host[i:]
393 user, passwd = self.get_user_passwd(host, realm, i)
394 if not (user or passwd): return None
395 host = user + ':' + passwd + '@' + host
396 newurl = '//' + host + selector
397 return self.open_http(newurl)
398
399 def get_user_passwd(self, host, realm, clear_cache = 0):
400 key = realm + '@' + string.lower(host)
401 if self.auth_cache.has_key(key):
402 if clear_cache:
403 del self.auth_cache[key]
404 else:
405 return self.auth_cache[key]
406 user, passwd = self.prompt_user_passwd(host, realm)
407 if user or passwd: self.auth_cache[key] = (user, passwd)
408 return user, passwd
409
410 def prompt_user_passwd(self, host, realm):
411 # Override this in a GUI environment!
412 try:
413 user = raw_input("Enter username for %s at %s: " %
414 (realm, host))
415 self.echo_off()
416 try:
417 passwd = raw_input(
418 "Enter password for %s in %s at %s: " %
419 (user, realm, host))
420 finally:
421 self.echo_on()
422 return user, passwd
423 except KeyboardInterrupt:
424 return None, None
425
426 def echo_off(self):
427 import os
428 os.system("stty -echo")
429
430 def echo_on(self):
431 import os
432 print
433 os.system("stty echo")
434
435
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000436# Utility functions
437
438# Return the IP address of the magic hostname 'localhost'
439_localhost = None
440def localhost():
441 global _localhost
442 if not _localhost:
443 _localhost = socket.gethostbyname('localhost')
444 return _localhost
445
446# Return the IP address of the current host
447_thishost = None
448def thishost():
449 global _thishost
450 if not _thishost:
451 _thishost = socket.gethostbyname(socket.gethostname())
452 return _thishost
453
454# Return the set of errors raised by the FTP class
455_ftperrors = None
456def ftperrors():
457 global _ftperrors
458 if not _ftperrors:
459 import ftplib
Guido van Rossum2966b321997-06-06 17:44:07 +0000460 _ftperrors = ftplib.all_errors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000461 return _ftperrors
462
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000463# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000464_noheaders = None
465def noheaders():
466 global _noheaders
467 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000468 import mimetools
469 import StringIO
470 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000471 _noheaders.fp.close() # Recycle file descriptor
472 return _noheaders
473
474
475# Utility classes
476
477# Class used by open_ftp() for cache of open FTP connections
478class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000479 def __init__(self, user, passwd, host, port, dirs):
480 self.user = unquote(user or '')
481 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000482 self.host = host
483 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000484 self.dirs = []
485 for dir in dirs:
486 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000487 self.init()
488 def init(self):
489 import ftplib
490 self.ftp = ftplib.FTP()
491 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000492 self.ftp.login(self.user, self.passwd)
493 for dir in self.dirs:
494 self.ftp.cwd(dir)
495 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000496 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000497 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
498 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000499 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000500 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000501 except ftplib.all_errors:
502 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000503 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000504 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000505 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000506 try:
507 cmd = 'RETR ' + file
508 conn = self.ftp.transfercmd(cmd)
509 except ftplib.error_perm, reason:
510 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000511 raise IOError, ('ftp error', reason), \
512 sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000513 if not conn:
514 # Try a directory listing
515 if file: cmd = 'LIST ' + file
516 else: cmd = 'LIST'
517 conn = self.ftp.transfercmd(cmd)
Guido van Rossumf668d171997-06-06 21:11:11 +0000518 return addclosehook(conn.makefile('rb'), self.endtransfer)
519 def endtransfer(self):
520 try:
521 self.ftp.voidresp()
522 except ftperrors():
523 pass
524 def close(self):
525 try:
526 self.ftp.close()
527 except ftperrors():
528 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000529
530# Base class for addinfo and addclosehook
531class addbase:
532 def __init__(self, fp):
533 self.fp = fp
534 self.read = self.fp.read
535 self.readline = self.fp.readline
536 self.readlines = self.fp.readlines
537 self.fileno = self.fp.fileno
538 def __repr__(self):
539 return '<%s at %s whose fp = %s>' % (
540 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000541 def close(self):
542 self.read = None
543 self.readline = None
544 self.readlines = None
545 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000546 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000547 self.fp = None
548
549# Class to add a close hook to an open file
550class addclosehook(addbase):
551 def __init__(self, fp, closehook, *hookargs):
552 addbase.__init__(self, fp)
553 self.closehook = closehook
554 self.hookargs = hookargs
555 def close(self):
556 if self.closehook:
557 apply(self.closehook, self.hookargs)
558 self.closehook = None
559 self.hookargs = None
560 addbase.close(self)
561
562# class to add an info() method to an open file
563class addinfo(addbase):
564 def __init__(self, fp, headers):
565 addbase.__init__(self, fp)
566 self.headers = headers
567 def info(self):
568 return self.headers
569
Guido van Rossume6ad8911996-09-10 17:02:56 +0000570# class to add info() and geturl() methods to an open file
571class addinfourl(addbase):
572 def __init__(self, fp, headers, url):
573 addbase.__init__(self, fp)
574 self.headers = headers
575 self.url = url
576 def info(self):
577 return self.headers
578 def geturl(self):
579 return self.url
580
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000581
582# Utility to combine a URL with a base URL to form a new URL
583
584def basejoin(base, url):
585 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000586 if type:
587 # if url is complete (i.e., it contains a type), return it
588 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000589 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000590 type, basepath = splittype(base) # inherit type from base
591 if host:
592 # if url contains host, just inherit type
593 if type: return type + '://' + host + path
594 else:
595 # no type inherited, so url must have started with //
596 # just return it
597 return url
598 host, basepath = splithost(basepath) # inherit host
599 basepath, basetag = splittag(basepath) # remove extraneuous cruft
600 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000601 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000602 # non-absolute path name
603 if path[:1] in ('#', '?'):
604 # path is just a tag or query, attach to basepath
605 i = len(basepath)
606 else:
607 # else replace last component
608 i = string.rfind(basepath, '/')
609 if i < 0:
610 # basepath not absolute
611 if host:
612 # host present, make absolute
613 basepath = '/'
614 else:
615 # else keep non-absolute
616 basepath = ''
617 else:
618 # remove last file component
619 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000620 # Interpret ../ (important because of symlinks)
621 while basepath and path[:3] == '../':
622 path = path[3:]
623 i = string.rfind(basepath, '/')
624 if i > 0:
625 basepath = basepath[:i-1]
626
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000627 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000628 if type and host: return type + '://' + host + path
629 elif type: return type + ':' + path
630 elif host: return '//' + host + path # don't know what this means
631 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000632
633
Guido van Rossum7c395db1994-07-04 22:14:49 +0000634# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000635# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000636# splittype('type:opaquestring') --> 'type', 'opaquestring'
637# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000638# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
639# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000640# splitport('host:port') --> 'host', 'port'
641# splitquery('/path?query') --> '/path', 'query'
642# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000643# splitattr('/path;attr1=value1;attr2=value2;...') ->
644# '/path', ['attr1=value1', 'attr2=value2', ...]
645# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000646# splitgophertype('/Xselector') --> 'X', 'selector'
647# unquote('abc%20def') -> 'abc def'
648# quote('abc def') -> 'abc%20def')
649
650def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000651 url = string.strip(url)
652 if url[:1] == '<' and url[-1:] == '>':
653 url = string.strip(url[1:-1])
654 if url[:4] == 'URL:': url = string.strip(url[4:])
655 return url
656
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000657_typeprog = regex.compile('^\([^/:]+\):')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000658def splittype(url):
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000659 if _typeprog.match(url) >= 0:
660 scheme = _typeprog.group(1)
661 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000662 return None, url
663
664_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
665def splithost(url):
666 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
667 return None, url
668
Guido van Rossum7c395db1994-07-04 22:14:49 +0000669_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
670def splituser(host):
671 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
672 return None, host
673
674_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
675def splitpasswd(user):
676 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
677 return user, None
678
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000679_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
680def splitport(host):
681 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
682 return host, None
683
Guido van Rossum53725a21996-06-13 19:12:35 +0000684# Split host and port, returning numeric port.
685# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000686# Return numerical port if a valid number are found after ':'.
687# Return None if ':' but not a valid number.
688_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000689def splitnport(host, defport=-1):
690 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000691 host, port = _nportprog.group(1, 2)
692 try:
693 if not port: raise string.atoi_error, "no digits"
694 nport = string.atoi(port)
695 except string.atoi_error:
696 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000697 return host, nport
698 return host, defport
699
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000700_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
701def splitquery(url):
702 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
703 return url, None
704
705_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
706def splittag(url):
707 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
708 return url, None
709
Guido van Rossum7c395db1994-07-04 22:14:49 +0000710def splitattr(url):
711 words = string.splitfields(url, ';')
712 return words[0], words[1:]
713
714_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
715def splitvalue(attr):
716 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
717 return attr, None
718
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000719def splitgophertype(selector):
720 if selector[:1] == '/' and selector[1:2]:
721 return selector[1], selector[2:]
722 return None, selector
723
724_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
725def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000726 i = 0
727 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000728 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000729 while 0 <= i < n:
730 j = _quoteprog.search(s, i)
731 if j < 0:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000732 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000733 break
Guido van Rossumf8abb381996-08-26 15:56:12 +0000734 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000735 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000736 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000737
Guido van Rossum0564e121996-12-13 14:47:36 +0000738def unquote_plus(s):
739 if '+' in s:
740 import regsub
741 s = regsub.gsub('+', ' ', s)
742 return unquote(s)
743
Guido van Rossum3bb54481994-08-29 10:52:58 +0000744always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000745def quote(s, safe = '/'):
746 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000747 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000748 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000749 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000750 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000751 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000752 res.append('%%%02x' % ord(c))
753 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000754
Guido van Rossum0564e121996-12-13 14:47:36 +0000755def quote_plus(s, safe = '/'):
756 if ' ' in s:
757 import regsub
758 s = regsub.gsub(' ', '+', s)
759 return quote(s, safe + '+')
760 else:
761 return quote(s, safe)
762
Guido van Rossum442e7201996-03-20 15:33:11 +0000763
764# Proxy handling
765def getproxies():
766 """Return a dictionary of protocol scheme -> proxy server URL mappings.
767
768 Scan the environment for variables named <scheme>_proxy;
769 this seems to be the standard convention. If you need a
770 different way, you can pass a proxies dictionary to the
771 [Fancy]URLopener constructor.
772
773 """
774 proxies = {}
775 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000776 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000777 if value and name[-6:] == '_proxy':
778 proxies[name[:-6]] = value
779 return proxies
780
781
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000782# Test and time quote() and unquote()
783def test1():
784 import time
785 s = ''
786 for i in range(256): s = s + chr(i)
787 s = s*4
788 t0 = time.time()
789 qs = quote(s)
790 uqs = unquote(qs)
791 t1 = time.time()
792 if uqs != s:
793 print 'Wrong!'
794 print `s`
795 print `qs`
796 print `uqs`
797 print round(t1 - t0, 3), 'sec'
798
799
800# Test program
801def test():
802 import sys
803 import regsub
804 args = sys.argv[1:]
805 if not args:
806 args = [
807 '/etc/passwd',
808 'file:/etc/passwd',
809 'file://localhost/etc/passwd',
810 'ftp://ftp.cwi.nl/etc/passwd',
811 'gopher://gopher.cwi.nl/11/',
812 'http://www.cwi.nl/index.html',
813 ]
814 try:
815 for url in args:
816 print '-'*10, url, '-'*10
817 fn, h = urlretrieve(url)
818 print fn, h
819 if h:
820 print '======'
821 for k in h.keys(): print k + ':', h[k]
822 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000823 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000824 data = fp.read()
825 del fp
826 print regsub.gsub('\r', '', data)
827 fn, h = None, None
828 print '-'*40
829 finally:
830 urlcleanup()
831
832# Run test program when run as a script
833if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000834## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000835 test()