blob: 2a9087aa53bbb6ee9d9b1bd7c5b8da0040647ad4 [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
Jack Jansendc3e3f61995-12-15 13:22:13 +000026import os
Guido van Rossum3c8484e1996-11-20 22:02:24 +000027import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000028
29
Guido van Rossum8a666e71998-02-13 01:39:16 +000030__version__ = '1.10'
Guido van Rossumf668d171997-06-06 21:11:11 +000031
32MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
Guido van Rossum6cb15a01995-06-22 19:00:13 +000033
Jack Jansendc3e3f61995-12-15 13:22:13 +000034# Helper for non-unix systems
35if os.name == 'mac':
Guido van Rossum71ac9451996-03-21 16:31:41 +000036 from macurl2path import url2pathname, pathname2url
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +000037elif os.name == 'nt':
Guido van Rossum2281d351996-06-26 19:47:37 +000038 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000039else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000040 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000041 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000042 def pathname2url(pathname):
43 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000044
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000045# This really consists of two pieces:
46# (1) a class which handles opening of all sorts of URLs
47# (plus assorted utilities etc.)
48# (2) a set of functions for parsing URLs
49# XXX Should these be separated out into different modules?
50
51
52# Shortcut for basic usage
53_urlopener = None
Guido van Rossumbd013741996-12-10 16:00:28 +000054def urlopen(url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000055 global _urlopener
56 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000057 _urlopener = FancyURLopener()
Guido van Rossumbd013741996-12-10 16:00:28 +000058 if data is None:
59 return _urlopener.open(url)
60 else:
61 return _urlopener.open(url, data)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000062def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000063 global _urlopener
64 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000065 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000066 if filename:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +000067 return _urlopener.retrieve(url, filename)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000068 else:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +000069 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000070def urlcleanup():
71 if _urlopener:
72 _urlopener.cleanup()
73
74
75# Class to open URLs.
76# This is a class rather than just a subroutine because we may need
77# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000078# Note -- this is a base class for those who don't want the
79# automatic handling of errors type 302 (relocated) and 401
80# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000081ftpcache = {}
82class URLopener:
83
Guido van Rossum036309b1997-10-27 18:56:19 +000084 __tempfiles = None
Guido van Rossum29e77811996-11-27 19:39:58 +000085
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000086 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000087 def __init__(self, proxies=None):
88 if proxies is None:
89 proxies = getproxies()
Guido van Rossum83600051997-11-18 15:50:39 +000090 assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
Guido van Rossum442e7201996-03-20 15:33:11 +000091 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 Rossum10499321997-09-08 02:16:33 +000094 self.__tempfiles = []
Guido van Rossum036309b1997-10-27 18:56:19 +000095 self.__unlink = os.unlink # See cleanup()
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000096 self.tempcache = None
97 # Undocumented feature: if you assign {} to tempcache,
98 # it is used to cache files retrieved with
99 # self.retrieve(). This is not enabled by default
100 # since it does not work for changing documents (and I
101 # haven't got the logic to check expiration headers
102 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000103 self.ftpcache = ftpcache
104 # Undocumented feature: you can use a different
105 # ftp cache by assigning to the .ftpcache member;
106 # in case you want logically independent URL openers
Guido van Rossum4163e701998-08-06 13:39:09 +0000107 # XXX This is not threadsafe. Bah.
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000108
109 def __del__(self):
110 self.close()
111
112 def close(self):
113 self.cleanup()
114
115 def cleanup(self):
Guido van Rossum036309b1997-10-27 18:56:19 +0000116 # This code sometimes runs when the rest of this module
117 # has already been deleted, so it can't use any globals
118 # or import anything.
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000119 if self.__tempfiles:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000120 for file in self.__tempfiles:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000121 try:
Guido van Rossum036309b1997-10-27 18:56:19 +0000122 self.__unlink(file)
123 except:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000124 pass
Guido van Rossum036309b1997-10-27 18:56:19 +0000125 del self.__tempfiles[:]
126 if self.tempcache:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000127 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000128
129 # Add a header to be used by the HTTP interface only
130 # e.g. u.addheader('Accept', 'sound/basic')
131 def addheader(self, *args):
132 self.addheaders.append(args)
133
134 # External interface
135 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumbd013741996-12-10 16:00:28 +0000136 def open(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000137 fullurl = unwrap(fullurl)
Guido van Rossum03710d21998-02-05 16:22:27 +0000138 if self.tempcache and self.tempcache.has_key(fullurl):
139 filename, headers = self.tempcache[fullurl]
140 fp = open(filename, 'rb')
141 return addinfourl(fp, headers, fullurl)
Guido van Rossumca445401995-08-29 19:19:12 +0000142 type, url = splittype(fullurl)
Guido van Rossuma08faba1998-03-30 17:17:24 +0000143 if not type: type = 'file'
Guido van Rossum442e7201996-03-20 15:33:11 +0000144 if self.proxies.has_key(type):
145 proxy = self.proxies[type]
146 type, proxy = splittype(proxy)
147 host, selector = splithost(proxy)
148 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000149 name = 'open_' + type
150 if '-' in name:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000151 # replace - with _
Guido van Rossum332e1441997-09-29 23:23:46 +0000152 name = string.join(string.split(name, '-'), '_')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000153 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000154 if data is None:
155 return self.open_unknown(fullurl)
156 else:
157 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000158 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000159 if data is None:
160 return getattr(self, name)(url)
161 else:
162 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000163 except socket.error, msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000164 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000165
Guido van Rossumca445401995-08-29 19:19:12 +0000166 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000167 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000168 type, url = splittype(fullurl)
169 raise IOError, ('url error', 'unknown url type', type)
170
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000171 # External interface
172 # retrieve(url) returns (filename, None) for a local object
173 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000174 def retrieve(self, url, filename=None):
Guido van Rossum03710d21998-02-05 16:22:27 +0000175 url = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000176 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000177 return self.tempcache[url]
Guido van Rossum03710d21998-02-05 16:22:27 +0000178 type, url1 = splittype(url)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000179 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000180 try:
181 fp = self.open_local_file(url1)
Guido van Rossum0454b511998-04-03 15:57:58 +0000182 hdrs = fp.info()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000183 del fp
Guido van Rossumb5916ab1998-04-03 15:56:16 +0000184 return url2pathname(splithost(url1)[1]), hdrs
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000185 except IOError, msg:
186 pass
187 fp = self.open(url)
188 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000189 if not filename:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000190 import tempfile
Guido van Rossum0454b511998-04-03 15:57:58 +0000191 garbage, path = splittype(url)
Guido van Rossum0454b511998-04-03 15:57:58 +0000192 garbage, path = splithost(path or "")
Guido van Rossum0454b511998-04-03 15:57:58 +0000193 path, garbage = splitquery(path or "")
Guido van Rossum0454b511998-04-03 15:57:58 +0000194 path, garbage = splitattr(path or "")
Guido van Rossumb5916ab1998-04-03 15:56:16 +0000195 suffix = os.path.splitext(path)[1]
196 filename = tempfile.mktemp(suffix)
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000197 self.__tempfiles.append(filename)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000198 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000199 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000200 self.tempcache[url] = result
Guido van Rossumc511aee1997-04-11 19:01:48 +0000201 tfp = open(filename, 'wb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000202 bs = 1024*8
203 block = fp.read(bs)
204 while block:
205 tfp.write(block)
206 block = fp.read(bs)
Guido van Rossumab0abdc1997-08-26 19:06:40 +0000207 fp.close()
208 tfp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000209 del fp
210 del tfp
211 return result
212
213 # Each method named open_<type> knows how to open that type of URL
214
215 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000216 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000217 import httplib
Guido van Rossum0eae8fb1998-04-27 15:19:17 +0000218 user_passwd = None
Guido van Rossum442e7201996-03-20 15:33:11 +0000219 if type(url) is type(""):
220 host, selector = splithost(url)
Guido van Rossum0eae8fb1998-04-27 15:19:17 +0000221 if host:
222 user_passwd, host = splituser(host)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000223 realhost = host
Guido van Rossum442e7201996-03-20 15:33:11 +0000224 else:
225 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000226 urltype, rest = splittype(selector)
Guido van Rossume0c0da91998-05-05 13:58:13 +0000227 url = rest
Guido van Rossumfd795661997-04-02 05:46:35 +0000228 user_passwd = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000229 if string.lower(urltype) != 'http':
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000230 realhost = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000231 else:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000232 realhost, rest = splithost(rest)
Guido van Rossum0eae8fb1998-04-27 15:19:17 +0000233 if realhost:
234 user_passwd, realhost = \
235 splituser(realhost)
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000236 if user_passwd:
237 selector = "%s://%s%s" % (urltype,
238 realhost,
239 rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000240 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000241 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000242 if user_passwd:
243 import base64
244 auth = string.strip(base64.encodestring(user_passwd))
245 else:
246 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000247 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000248 if data is not None:
249 h.putrequest('POST', selector)
250 h.putheader('Content-type',
251 'application/x-www-form-urlencoded')
252 h.putheader('Content-length', '%d' % len(data))
253 else:
254 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000255 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000256 if realhost: h.putheader('Host', realhost)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000257 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000258 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000259 if data is not None:
260 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000261 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000262 fp = h.getfile()
263 if errcode == 200:
Guido van Rossum8a666e71998-02-13 01:39:16 +0000264 return addinfourl(fp, headers, "http:" + url)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000265 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000266 return self.http_error(url,
267 fp, errcode, errmsg, headers)
268
269 # Handle http errors.
270 # Derived class can override this, or provide specific handlers
271 # named http_error_DDD where DDD is the 3-digit error code
272 def http_error(self, url, fp, errcode, errmsg, headers):
273 # First check if there's a specific handler for this error
274 name = 'http_error_%d' % errcode
275 if hasattr(self, name):
276 method = getattr(self, name)
277 result = method(url, fp, errcode, errmsg, headers)
278 if result: return result
279 return self.http_error_default(
280 url, fp, errcode, errmsg, headers)
281
282 # Default http error handler: close the connection and raises IOError
283 def http_error_default(self, url, fp, errcode, errmsg, headers):
284 void = fp.read()
285 fp.close()
286 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000287
288 # Use Gopher protocol
289 def open_gopher(self, url):
290 import gopherlib
291 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000292 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000293 type, selector = splitgophertype(selector)
294 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000295 selector = unquote(selector)
296 if query:
297 query = unquote(query)
298 fp = gopherlib.send_query(selector, query, host)
299 else:
300 fp = gopherlib.send_selector(selector, host)
Guido van Rossum8a666e71998-02-13 01:39:16 +0000301 return addinfourl(fp, noheaders(), "gopher:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000302
303 # Use local file or FTP depending on form of URL
304 def open_file(self, url):
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000305 if url[:2] == '//' and url[2:3] != '/':
306 return self.open_ftp(url)
307 else:
308 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000309
310 # Use local file
311 def open_local_file(self, url):
Guido van Rossumb5916ab1998-04-03 15:56:16 +0000312 import mimetypes, mimetools, StringIO
313 mtype = mimetypes.guess_type(url)[0]
314 headers = mimetools.Message(StringIO.StringIO(
315 'Content-Type: %s\n' % (mtype or 'text/plain')))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000316 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000317 if not host:
Guido van Rossum2966b321997-06-06 17:44:07 +0000318 return addinfourl(
319 open(url2pathname(file), 'rb'),
Guido van Rossumb5916ab1998-04-03 15:56:16 +0000320 headers, 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000321 host, port = splitport(host)
322 if not port and socket.gethostbyname(host) in (
323 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000324 file = unquote(file)
Guido van Rossum2966b321997-06-06 17:44:07 +0000325 return addinfourl(
326 open(url2pathname(file), 'rb'),
Guido van Rossumb5916ab1998-04-03 15:56:16 +0000327 headers, 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000328 raise IOError, ('local file error', 'not on local host')
329
330 # Use FTP protocol
331 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000332 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000333 if not host: raise IOError, ('ftp error', 'no host given')
334 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000335 user, host = splituser(host)
336 if user: user, passwd = splitpasswd(user)
337 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000338 host = socket.gethostbyname(host)
339 if not port:
340 import ftplib
341 port = ftplib.FTP_PORT
Guido van Rossumc0f29c21997-12-02 20:26:21 +0000342 else:
343 port = int(port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000344 path, attrs = splitattr(path)
345 dirs = string.splitfields(path, '/')
346 dirs, file = dirs[:-1], dirs[-1]
347 if dirs and not dirs[0]: dirs = dirs[1:]
348 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum4163e701998-08-06 13:39:09 +0000349 # XXX thread unsafe!
Guido van Rossumf668d171997-06-06 21:11:11 +0000350 if len(self.ftpcache) > MAXFTPCACHE:
351 # Prune the cache, rather arbitrarily
352 for k in self.ftpcache.keys():
353 if k != key:
354 v = self.ftpcache[k]
355 del self.ftpcache[k]
356 v.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000357 try:
358 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000359 self.ftpcache[key] = \
Guido van Rossum8a666e71998-02-13 01:39:16 +0000360 ftpwrapper(user, passwd,
361 host, port, dirs)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000362 if not file: type = 'D'
363 else: type = 'I'
364 for attr in attrs:
365 attr, value = splitvalue(attr)
366 if string.lower(attr) == 'type' and \
367 value in ('a', 'A', 'i', 'I', 'd', 'D'):
368 type = string.upper(value)
Guido van Rossum2966b321997-06-06 17:44:07 +0000369 return addinfourl(
370 self.ftpcache[key].retrfile(file, type),
Guido van Rossum8a666e71998-02-13 01:39:16 +0000371 noheaders(), "ftp:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000372 except ftperrors(), msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000373 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000374
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000375 # Use "data" URL
376 def open_data(self, url, data=None):
377 # ignore POSTed data
378 #
379 # syntax of data URLs:
380 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
381 # mediatype := [ type "/" subtype ] *( ";" parameter )
382 # data := *urlchar
383 # parameter := attribute "=" value
384 import StringIO, mimetools, time
385 try:
386 [type, data] = string.split(url, ',', 1)
387 except ValueError:
388 raise IOError, ('data error', 'bad data URL')
389 if not type:
390 type = 'text/plain;charset=US-ASCII'
391 semi = string.rfind(type, ';')
392 if semi >= 0 and '=' not in type[semi:]:
393 encoding = type[semi+1:]
394 type = type[:semi]
395 else:
396 encoding = ''
397 msg = []
398 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
399 time.gmtime(time.time())))
400 msg.append('Content-type: %s' % type)
401 if encoding == 'base64':
402 import base64
403 data = base64.decodestring(data)
404 else:
405 data = unquote(data)
406 msg.append('Content-length: %d' % len(data))
407 msg.append('')
408 msg.append(data)
409 msg = string.join(msg, '\n')
410 f = StringIO.StringIO(msg)
411 headers = mimetools.Message(f, 0)
412 f.fileno = None # needed for addinfourl
413 return addinfourl(f, headers, url)
414
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000415
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000416# Derived class with handlers for errors we can handle (perhaps)
417class FancyURLopener(URLopener):
418
419 def __init__(self, *args):
420 apply(URLopener.__init__, (self,) + args)
421 self.auth_cache = {}
422
423 # Default error handling -- don't raise an exception
424 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000425 return addinfourl(fp, headers, "http:" + url)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000426
Guido van Rossume6ad8911996-09-10 17:02:56 +0000427 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000428 def http_error_302(self, url, fp, errcode, errmsg, headers):
429 # XXX The server can force infinite recursion here!
430 if headers.has_key('location'):
431 newurl = headers['location']
432 elif headers.has_key('uri'):
433 newurl = headers['uri']
434 else:
435 return
436 void = fp.read()
437 fp.close()
438 return self.open(newurl)
439
Guido van Rossume6ad8911996-09-10 17:02:56 +0000440 # Error 301 -- also relocated (permanently)
441 http_error_301 = http_error_302
442
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000443 # Error 401 -- authentication required
444 # See this URL for a description of the basic authentication scheme:
445 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
446 def http_error_401(self, url, fp, errcode, errmsg, headers):
447 if headers.has_key('www-authenticate'):
448 stuff = headers['www-authenticate']
Guido van Rossum332e1441997-09-29 23:23:46 +0000449 import re
450 match = re.match(
451 '[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
452 if match:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000453 scheme, realm = match.groups()
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000454 if string.lower(scheme) == 'basic':
455 return self.retry_http_basic_auth(
456 url, realm)
457
458 def retry_http_basic_auth(self, url, realm):
459 host, selector = splithost(url)
460 i = string.find(host, '@') + 1
461 host = host[i:]
462 user, passwd = self.get_user_passwd(host, realm, i)
463 if not (user or passwd): return None
464 host = user + ':' + passwd + '@' + host
Guido van Rossume0c0da91998-05-05 13:58:13 +0000465 newurl = 'http://' + host + selector
466 return self.open(newurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000467
468 def get_user_passwd(self, host, realm, clear_cache = 0):
469 key = realm + '@' + string.lower(host)
470 if self.auth_cache.has_key(key):
471 if clear_cache:
472 del self.auth_cache[key]
473 else:
474 return self.auth_cache[key]
475 user, passwd = self.prompt_user_passwd(host, realm)
476 if user or passwd: self.auth_cache[key] = (user, passwd)
477 return user, passwd
478
479 def prompt_user_passwd(self, host, realm):
480 # Override this in a GUI environment!
Guido van Rossumae9ee731998-06-12 14:21:13 +0000481 import getpass
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000482 try:
483 user = raw_input("Enter username for %s at %s: " %
484 (realm, host))
Guido van Rossumae9ee731998-06-12 14:21:13 +0000485 passwd = getpass.getpass(
486 "Enter password for %s in %s at %s: " %
487 (user, realm, host))
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000488 return user, passwd
489 except KeyboardInterrupt:
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000490 print
Guido van Rossumae9ee731998-06-12 14:21:13 +0000491 return None, None
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000492
493
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000494# Utility functions
495
496# Return the IP address of the magic hostname 'localhost'
497_localhost = None
498def localhost():
499 global _localhost
500 if not _localhost:
501 _localhost = socket.gethostbyname('localhost')
502 return _localhost
503
504# Return the IP address of the current host
505_thishost = None
506def thishost():
507 global _thishost
508 if not _thishost:
509 _thishost = socket.gethostbyname(socket.gethostname())
510 return _thishost
511
512# Return the set of errors raised by the FTP class
513_ftperrors = None
514def ftperrors():
515 global _ftperrors
516 if not _ftperrors:
517 import ftplib
Guido van Rossum2966b321997-06-06 17:44:07 +0000518 _ftperrors = ftplib.all_errors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000519 return _ftperrors
520
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000521# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000522_noheaders = None
523def noheaders():
524 global _noheaders
525 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000526 import mimetools
527 import StringIO
528 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000529 _noheaders.fp.close() # Recycle file descriptor
530 return _noheaders
531
532
533# Utility classes
534
535# Class used by open_ftp() for cache of open FTP connections
536class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000537 def __init__(self, user, passwd, host, port, dirs):
538 self.user = unquote(user or '')
539 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000540 self.host = host
541 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000542 self.dirs = []
543 for dir in dirs:
544 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000545 self.init()
546 def init(self):
547 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000548 self.busy = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000549 self.ftp = ftplib.FTP()
550 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000551 self.ftp.login(self.user, self.passwd)
552 for dir in self.dirs:
553 self.ftp.cwd(dir)
554 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000555 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000556 self.endtransfer()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000557 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
558 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000559 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000560 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000561 except ftplib.all_errors:
562 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000563 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000564 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000565 if file and not isdir:
Guido van Rossumd4990041997-12-28 04:21:20 +0000566 # Use nlst to see if the file exists at all
567 try:
568 self.ftp.nlst(file)
569 except ftplib.error_perm, reason:
570 raise IOError, ('ftp error', reason), \
571 sys.exc_info()[2]
Guido van Rossume7579621998-01-19 22:26:54 +0000572 # Restore the transfer mode!
573 self.ftp.voidcmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000574 # Try to retrieve as a file
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000575 try:
576 cmd = 'RETR ' + file
577 conn = self.ftp.transfercmd(cmd)
578 except ftplib.error_perm, reason:
579 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000580 raise IOError, ('ftp error', reason), \
Guido van Rossum332e1441997-09-29 23:23:46 +0000581 sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000582 if not conn:
Guido van Rossume7579621998-01-19 22:26:54 +0000583 # Set transfer mode to ASCII!
584 self.ftp.voidcmd('TYPE A')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000585 # Try a directory listing
586 if file: cmd = 'LIST ' + file
587 else: cmd = 'LIST'
588 conn = self.ftp.transfercmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000589 self.busy = 1
Guido van Rossumf668d171997-06-06 21:11:11 +0000590 return addclosehook(conn.makefile('rb'), self.endtransfer)
591 def endtransfer(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000592 if not self.busy:
593 return
594 self.busy = 0
Guido van Rossumf668d171997-06-06 21:11:11 +0000595 try:
596 self.ftp.voidresp()
597 except ftperrors():
598 pass
599 def close(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000600 self.endtransfer()
Guido van Rossumf668d171997-06-06 21:11:11 +0000601 try:
602 self.ftp.close()
603 except ftperrors():
604 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000605
606# Base class for addinfo and addclosehook
607class addbase:
608 def __init__(self, fp):
609 self.fp = fp
610 self.read = self.fp.read
611 self.readline = self.fp.readline
612 self.readlines = self.fp.readlines
613 self.fileno = self.fp.fileno
614 def __repr__(self):
615 return '<%s at %s whose fp = %s>' % (
616 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000617 def close(self):
618 self.read = None
619 self.readline = None
620 self.readlines = None
621 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000622 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000623 self.fp = None
624
625# Class to add a close hook to an open file
626class addclosehook(addbase):
627 def __init__(self, fp, closehook, *hookargs):
628 addbase.__init__(self, fp)
629 self.closehook = closehook
630 self.hookargs = hookargs
631 def close(self):
632 if self.closehook:
633 apply(self.closehook, self.hookargs)
634 self.closehook = None
635 self.hookargs = None
636 addbase.close(self)
637
638# class to add an info() method to an open file
639class addinfo(addbase):
640 def __init__(self, fp, headers):
641 addbase.__init__(self, fp)
642 self.headers = headers
643 def info(self):
644 return self.headers
645
Guido van Rossume6ad8911996-09-10 17:02:56 +0000646# class to add info() and geturl() methods to an open file
647class addinfourl(addbase):
648 def __init__(self, fp, headers, url):
649 addbase.__init__(self, fp)
650 self.headers = headers
651 self.url = url
652 def info(self):
653 return self.headers
654 def geturl(self):
655 return self.url
656
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000657
658# Utility to combine a URL with a base URL to form a new URL
659
660def basejoin(base, url):
661 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000662 if type:
663 # if url is complete (i.e., it contains a type), return it
664 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000665 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000666 type, basepath = splittype(base) # inherit type from base
667 if host:
668 # if url contains host, just inherit type
669 if type: return type + '://' + host + path
670 else:
671 # no type inherited, so url must have started with //
672 # just return it
673 return url
674 host, basepath = splithost(basepath) # inherit host
675 basepath, basetag = splittag(basepath) # remove extraneuous cruft
676 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000677 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000678 # non-absolute path name
679 if path[:1] in ('#', '?'):
680 # path is just a tag or query, attach to basepath
681 i = len(basepath)
682 else:
683 # else replace last component
684 i = string.rfind(basepath, '/')
685 if i < 0:
686 # basepath not absolute
687 if host:
688 # host present, make absolute
689 basepath = '/'
690 else:
691 # else keep non-absolute
692 basepath = ''
693 else:
694 # remove last file component
695 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000696 # Interpret ../ (important because of symlinks)
697 while basepath and path[:3] == '../':
698 path = path[3:]
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000699 i = string.rfind(basepath[:-1], '/')
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000700 if i > 0:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000701 basepath = basepath[:i+1]
702 elif i == 0:
703 basepath = '/'
704 break
705 else:
706 basepath = ''
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000707
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000708 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000709 if type and host: return type + '://' + host + path
710 elif type: return type + ':' + path
711 elif host: return '//' + host + path # don't know what this means
712 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000713
714
Guido van Rossum7c395db1994-07-04 22:14:49 +0000715# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000716# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000717# splittype('type:opaquestring') --> 'type', 'opaquestring'
718# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000719# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
720# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000721# splitport('host:port') --> 'host', 'port'
722# splitquery('/path?query') --> '/path', 'query'
723# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000724# splitattr('/path;attr1=value1;attr2=value2;...') ->
725# '/path', ['attr1=value1', 'attr2=value2', ...]
726# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000727# splitgophertype('/Xselector') --> 'X', 'selector'
728# unquote('abc%20def') -> 'abc def'
729# quote('abc def') -> 'abc%20def')
730
731def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000732 url = string.strip(url)
733 if url[:1] == '<' and url[-1:] == '>':
734 url = string.strip(url[1:-1])
735 if url[:4] == 'URL:': url = string.strip(url[4:])
736 return url
737
Guido van Rossum332e1441997-09-29 23:23:46 +0000738_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000739def splittype(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000740 global _typeprog
741 if _typeprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000742 import re
743 _typeprog = re.compile('^([^/:]+):')
Guido van Rossum332e1441997-09-29 23:23:46 +0000744
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000745 match = _typeprog.match(url)
Guido van Rossum332e1441997-09-29 23:23:46 +0000746 if match:
747 scheme = match.group(1)
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000748 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000749 return None, url
750
Guido van Rossum332e1441997-09-29 23:23:46 +0000751_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000752def splithost(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000753 global _hostprog
754 if _hostprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000755 import re
756 _hostprog = re.compile('^//([^/]+)(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000757
Guido van Rossuma08faba1998-03-30 17:17:24 +0000758 match = _hostprog.match(url)
Guido van Rossum332e1441997-09-29 23:23:46 +0000759 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000760 return None, url
761
Guido van Rossum332e1441997-09-29 23:23:46 +0000762_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000763def splituser(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000764 global _userprog
765 if _userprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000766 import re
767 _userprog = re.compile('^([^@]*)@(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000768
Guido van Rossuma08faba1998-03-30 17:17:24 +0000769 match = _userprog.match(host)
Guido van Rossum332e1441997-09-29 23:23:46 +0000770 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000771 return None, host
772
Guido van Rossum332e1441997-09-29 23:23:46 +0000773_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000774def splitpasswd(user):
Guido van Rossum332e1441997-09-29 23:23:46 +0000775 global _passwdprog
776 if _passwdprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000777 import re
778 _passwdprog = re.compile('^([^:]*):(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000779
Guido van Rossuma08faba1998-03-30 17:17:24 +0000780 match = _passwdprog.match(user)
Guido van Rossum332e1441997-09-29 23:23:46 +0000781 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000782 return user, None
783
Guido van Rossum332e1441997-09-29 23:23:46 +0000784_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000785def splitport(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000786 global _portprog
787 if _portprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000788 import re
789 _portprog = re.compile('^(.*):([0-9]+)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000790
Guido van Rossuma08faba1998-03-30 17:17:24 +0000791 match = _portprog.match(host)
Guido van Rossum332e1441997-09-29 23:23:46 +0000792 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000793 return host, None
794
Guido van Rossum53725a21996-06-13 19:12:35 +0000795# Split host and port, returning numeric port.
796# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000797# Return numerical port if a valid number are found after ':'.
798# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000799_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000800def splitnport(host, defport=-1):
Guido van Rossum332e1441997-09-29 23:23:46 +0000801 global _nportprog
802 if _nportprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000803 import re
804 _nportprog = re.compile('^(.*):(.*)$')
805
Guido van Rossuma08faba1998-03-30 17:17:24 +0000806 match = _nportprog.match(host)
Guido van Rossum332e1441997-09-29 23:23:46 +0000807 if match:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000808 host, port = match.group(1, 2)
809 try:
810 if not port: raise string.atoi_error, "no digits"
811 nport = string.atoi(port)
812 except string.atoi_error:
813 nport = None
814 return host, nport
Guido van Rossum53725a21996-06-13 19:12:35 +0000815 return host, defport
816
Guido van Rossum332e1441997-09-29 23:23:46 +0000817_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000818def splitquery(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000819 global _queryprog
820 if _queryprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000821 import re
822 _queryprog = re.compile('^(.*)\?([^?]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000823
Guido van Rossuma08faba1998-03-30 17:17:24 +0000824 match = _queryprog.match(url)
Guido van Rossum332e1441997-09-29 23:23:46 +0000825 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000826 return url, None
827
Guido van Rossum332e1441997-09-29 23:23:46 +0000828_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000829def splittag(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000830 global _tagprog
831 if _tagprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000832 import re
833 _tagprog = re.compile('^(.*)#([^#]*)$')
834
Guido van Rossuma08faba1998-03-30 17:17:24 +0000835 match = _tagprog.match(url)
Guido van Rossum332e1441997-09-29 23:23:46 +0000836 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000837 return url, None
838
Guido van Rossum7c395db1994-07-04 22:14:49 +0000839def splitattr(url):
840 words = string.splitfields(url, ';')
841 return words[0], words[1:]
842
Guido van Rossum332e1441997-09-29 23:23:46 +0000843_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000844def splitvalue(attr):
Guido van Rossum332e1441997-09-29 23:23:46 +0000845 global _valueprog
846 if _valueprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000847 import re
848 _valueprog = re.compile('^([^=]*)=(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000849
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000850 match = _valueprog.match(attr)
Guido van Rossum332e1441997-09-29 23:23:46 +0000851 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000852 return attr, None
853
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000854def splitgophertype(selector):
855 if selector[:1] == '/' and selector[1:2]:
856 return selector[1], selector[2:]
857 return None, selector
858
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000859def unquote(s):
Guido van Rossum52e86ad1998-06-28 23:49:35 +0000860 mychr = chr
861 myatoi = string.atoi
862 list = string.split(s, '%')
863 res = [list[0]]
864 myappend = res.append
865 del list[0]
866 for item in list:
867 if item[1:2]:
868 try:
869 myappend(mychr(myatoi(item[:2], 16))
870 + item[2:])
871 except:
Guido van Rossumc94f16f1998-06-29 00:42:54 +0000872 myappend('%' + item)
Guido van Rossum52e86ad1998-06-28 23:49:35 +0000873 else:
Guido van Rossumc94f16f1998-06-29 00:42:54 +0000874 myappend('%' + item)
Guido van Rossum52e86ad1998-06-28 23:49:35 +0000875 return string.join(res, "")
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000876
Guido van Rossum0564e121996-12-13 14:47:36 +0000877def unquote_plus(s):
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000878 if '+' in s:
879 # replace '+' with ' '
880 s = string.join(string.split(s, '+'), ' ')
881 return unquote(s)
Guido van Rossum0564e121996-12-13 14:47:36 +0000882
Guido van Rossum3bb54481994-08-29 10:52:58 +0000883always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000884def quote(s, safe = '/'):
885 safe = always_safe + safe
Guido van Rossum810a3391998-07-22 21:33:23 +0000886 res = list(s)
887 for i in range(len(res)):
888 c = res[i]
889 if c not in safe:
890 res[i] = '%%%02x' % ord(c)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000891 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000892
Guido van Rossum0564e121996-12-13 14:47:36 +0000893def quote_plus(s, safe = '/'):
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000894 if ' ' in s:
895 # replace ' ' with '+'
Guido van Rossum810a3391998-07-22 21:33:23 +0000896 l = string.split(s, ' ')
897 for i in range(len(l)):
898 l[i] = quote(l[i], safe)
899 return string.join(l, '+')
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000900 else:
901 return quote(s, safe)
Guido van Rossum0564e121996-12-13 14:47:36 +0000902
Guido van Rossum810a3391998-07-22 21:33:23 +0000903def urlencode(dict):
904 l = []
905 for k, v in dict.items():
906 k = quote_plus(str(k))
907 v = quote_plus(str(v))
908 l.append(k + '=' + v)
909 return string.join(l, '&')
910
Guido van Rossum442e7201996-03-20 15:33:11 +0000911
912# Proxy handling
Guido van Rossum4163e701998-08-06 13:39:09 +0000913if os.name == 'mac':
914 def getproxies():
915 """Return a dictionary of scheme -> proxy server URL mappings.
Guido van Rossum442e7201996-03-20 15:33:11 +0000916
Guido van Rossum4163e701998-08-06 13:39:09 +0000917 By convention the mac uses Internet Config to store
918 proxies. An HTTP proxy, for instance, is stored under
919 the HttpProxy key.
Guido van Rossum442e7201996-03-20 15:33:11 +0000920
Guido van Rossum4163e701998-08-06 13:39:09 +0000921 """
922 try:
923 import ic
924 except ImportError:
925 return {}
926
927 try:
928 config = ic.IC()
929 except ic.error:
930 return {}
931 proxies = {}
932 # HTTP:
933 if config.has_key('UseHTTPProxy') and config['UseHTTPProxy']:
934 try:
935 value = config['HTTPProxyHost']
936 except ic.error:
937 pass
938 else:
939 proxies['http'] = 'http://%s' % value
940 # FTP: XXXX To be done.
941 # Gopher: XXXX To be done.
942 return proxies
943
944else:
945 def getproxies():
946 """Return a dictionary of scheme -> proxy server URL mappings.
947
948 Scan the environment for variables named <scheme>_proxy;
949 this seems to be the standard convention. If you need a
950 different way, you can pass a proxies dictionary to the
951 [Fancy]URLopener constructor.
952
953 """
954 proxies = {}
955 for name, value in os.environ.items():
956 name = string.lower(name)
957 if value and name[-6:] == '_proxy':
958 proxies[name[:-6]] = value
959 return proxies
Guido van Rossum442e7201996-03-20 15:33:11 +0000960
961
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000962# Test and time quote() and unquote()
963def test1():
964 import time
965 s = ''
966 for i in range(256): s = s + chr(i)
967 s = s*4
968 t0 = time.time()
969 qs = quote(s)
970 uqs = unquote(qs)
971 t1 = time.time()
972 if uqs != s:
973 print 'Wrong!'
974 print `s`
975 print `qs`
976 print `uqs`
977 print round(t1 - t0, 3), 'sec'
978
979
980# Test program
Guido van Rossum23490151998-06-25 02:39:00 +0000981def test(args=[]):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000982 if not args:
983 args = [
984 '/etc/passwd',
985 'file:/etc/passwd',
986 'file://localhost/etc/passwd',
Guido van Rossum332e1441997-09-29 23:23:46 +0000987 'ftp://ftp.python.org/etc/passwd',
988 'gopher://gopher.micro.umn.edu/1/',
989 'http://www.python.org/index.html',
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000990 ]
991 try:
992 for url in args:
993 print '-'*10, url, '-'*10
994 fn, h = urlretrieve(url)
995 print fn, h
996 if h:
997 print '======'
998 for k in h.keys(): print k + ':', h[k]
999 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +00001000 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001001 data = fp.read()
1002 del fp
Guido van Rossum332e1441997-09-29 23:23:46 +00001003 if '\r' in data:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +00001004 table = string.maketrans("", "")
1005 data = string.translate(data, table, "\r")
Guido van Rossum332e1441997-09-29 23:23:46 +00001006 print data
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001007 fn, h = None, None
1008 print '-'*40
1009 finally:
1010 urlcleanup()
1011
Guido van Rossum23490151998-06-25 02:39:00 +00001012def main():
1013 import getopt, sys
1014 try:
1015 opts, args = getopt.getopt(sys.argv[1:], "th")
1016 except getopt.error, msg:
1017 print msg
1018 print "Use -h for help"
1019 return
1020 t = 0
1021 for o, a in opts:
1022 if o == '-t':
1023 t = t + 1
1024 if o == '-h':
1025 print "Usage: python urllib.py [-t] [url ...]"
1026 print "-t runs self-test;",
1027 print "otherwise, contents of urls are printed"
1028 return
1029 if t:
1030 if t > 1:
1031 test1()
1032 test(args)
1033 else:
1034 if not args:
1035 print "Use -h for help"
1036 for url in args:
1037 print urlopen(url).read(),
1038
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001039# Run test program when run as a script
1040if __name__ == '__main__':
Guido van Rossum23490151998-06-25 02:39:00 +00001041 main()