blob: 173eefcfbf9690fe6e923c45c6b94ff61c13189c [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
107
108 def __del__(self):
109 self.close()
110
111 def close(self):
112 self.cleanup()
113
114 def cleanup(self):
Guido van Rossum036309b1997-10-27 18:56:19 +0000115 # This code sometimes runs when the rest of this module
116 # has already been deleted, so it can't use any globals
117 # or import anything.
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000118 if self.__tempfiles:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000119 for file in self.__tempfiles:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000120 try:
Guido van Rossum036309b1997-10-27 18:56:19 +0000121 self.__unlink(file)
122 except:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000123 pass
Guido van Rossum036309b1997-10-27 18:56:19 +0000124 del self.__tempfiles[:]
125 if self.tempcache:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000126 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000127
128 # Add a header to be used by the HTTP interface only
129 # e.g. u.addheader('Accept', 'sound/basic')
130 def addheader(self, *args):
131 self.addheaders.append(args)
132
133 # External interface
134 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumbd013741996-12-10 16:00:28 +0000135 def open(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000136 fullurl = unwrap(fullurl)
Guido van Rossum03710d21998-02-05 16:22:27 +0000137 if self.tempcache and self.tempcache.has_key(fullurl):
138 filename, headers = self.tempcache[fullurl]
139 fp = open(filename, 'rb')
140 return addinfourl(fp, headers, fullurl)
Guido van Rossumca445401995-08-29 19:19:12 +0000141 type, url = splittype(fullurl)
Guido van Rossuma08faba1998-03-30 17:17:24 +0000142 if not type: type = 'file'
Guido van Rossum442e7201996-03-20 15:33:11 +0000143 if self.proxies.has_key(type):
144 proxy = self.proxies[type]
145 type, proxy = splittype(proxy)
146 host, selector = splithost(proxy)
147 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000148 name = 'open_' + type
149 if '-' in name:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000150 # replace - with _
Guido van Rossum332e1441997-09-29 23:23:46 +0000151 name = string.join(string.split(name, '-'), '_')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000152 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000153 if data is None:
154 return self.open_unknown(fullurl)
155 else:
156 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000157 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000158 if data is None:
159 return getattr(self, name)(url)
160 else:
161 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000162 except socket.error, msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000163 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000164
Guido van Rossumca445401995-08-29 19:19:12 +0000165 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000166 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000167 type, url = splittype(fullurl)
168 raise IOError, ('url error', 'unknown url type', type)
169
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000170 # External interface
171 # retrieve(url) returns (filename, None) for a local object
172 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000173 def retrieve(self, url, filename=None):
Guido van Rossum03710d21998-02-05 16:22:27 +0000174 url = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000175 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000176 return self.tempcache[url]
Guido van Rossum03710d21998-02-05 16:22:27 +0000177 type, url1 = splittype(url)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000178 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000179 try:
180 fp = self.open_local_file(url1)
181 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000182 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000183 except IOError, msg:
184 pass
185 fp = self.open(url)
186 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000187 if not filename:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000188 import tempfile
189 filename = tempfile.mktemp()
190 self.__tempfiles.append(filename)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000191 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000192 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000193 self.tempcache[url] = result
Guido van Rossumc511aee1997-04-11 19:01:48 +0000194 tfp = open(filename, 'wb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000195 bs = 1024*8
196 block = fp.read(bs)
197 while block:
198 tfp.write(block)
199 block = fp.read(bs)
Guido van Rossumab0abdc1997-08-26 19:06:40 +0000200 fp.close()
201 tfp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000202 del fp
203 del tfp
204 return result
205
206 # Each method named open_<type> knows how to open that type of URL
207
208 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000209 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000210 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000211 if type(url) is type(""):
212 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000213 user_passwd, host = splituser(host)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000214 realhost = host
Guido van Rossum442e7201996-03-20 15:33:11 +0000215 else:
216 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000217 urltype, rest = splittype(selector)
Guido van Rossumfd795661997-04-02 05:46:35 +0000218 user_passwd = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000219 if string.lower(urltype) != 'http':
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000220 realhost = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000221 else:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000222 realhost, rest = splithost(rest)
223 user_passwd, realhost = splituser(realhost)
224 if user_passwd:
225 selector = "%s://%s%s" % (urltype,
226 realhost,
227 rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000228 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000229 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000230 if user_passwd:
231 import base64
232 auth = string.strip(base64.encodestring(user_passwd))
233 else:
234 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000235 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000236 if data is not None:
237 h.putrequest('POST', selector)
238 h.putheader('Content-type',
239 'application/x-www-form-urlencoded')
240 h.putheader('Content-length', '%d' % len(data))
241 else:
242 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000243 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000244 if realhost: h.putheader('Host', realhost)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000245 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000246 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000247 if data is not None:
248 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000249 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000250 fp = h.getfile()
251 if errcode == 200:
Guido van Rossum8a666e71998-02-13 01:39:16 +0000252 return addinfourl(fp, headers, "http:" + url)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000253 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000254 return self.http_error(url,
255 fp, errcode, errmsg, headers)
256
257 # Handle http errors.
258 # Derived class can override this, or provide specific handlers
259 # named http_error_DDD where DDD is the 3-digit error code
260 def http_error(self, url, fp, errcode, errmsg, headers):
261 # First check if there's a specific handler for this error
262 name = 'http_error_%d' % errcode
263 if hasattr(self, name):
264 method = getattr(self, name)
265 result = method(url, fp, errcode, errmsg, headers)
266 if result: return result
267 return self.http_error_default(
268 url, fp, errcode, errmsg, headers)
269
270 # Default http error handler: close the connection and raises IOError
271 def http_error_default(self, url, fp, errcode, errmsg, headers):
272 void = fp.read()
273 fp.close()
274 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000275
276 # Use Gopher protocol
277 def open_gopher(self, url):
278 import gopherlib
279 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000280 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000281 type, selector = splitgophertype(selector)
282 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000283 selector = unquote(selector)
284 if query:
285 query = unquote(query)
286 fp = gopherlib.send_query(selector, query, host)
287 else:
288 fp = gopherlib.send_selector(selector, host)
Guido van Rossum8a666e71998-02-13 01:39:16 +0000289 return addinfourl(fp, noheaders(), "gopher:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000290
291 # Use local file or FTP depending on form of URL
292 def open_file(self, url):
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000293 if url[:2] == '//' and url[2:3] != '/':
294 return self.open_ftp(url)
295 else:
296 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000297
298 # Use local file
299 def open_local_file(self, url):
300 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000301 if not host:
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 host, port = splitport(host)
306 if not port and socket.gethostbyname(host) in (
307 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000308 file = unquote(file)
Guido van Rossum2966b321997-06-06 17:44:07 +0000309 return addinfourl(
310 open(url2pathname(file), 'rb'),
311 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000312 raise IOError, ('local file error', 'not on local host')
313
314 # Use FTP protocol
315 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000316 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000317 if not host: raise IOError, ('ftp error', 'no host given')
318 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000319 user, host = splituser(host)
320 if user: user, passwd = splitpasswd(user)
321 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000322 host = socket.gethostbyname(host)
323 if not port:
324 import ftplib
325 port = ftplib.FTP_PORT
Guido van Rossumc0f29c21997-12-02 20:26:21 +0000326 else:
327 port = int(port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000328 path, attrs = splitattr(path)
329 dirs = string.splitfields(path, '/')
330 dirs, file = dirs[:-1], dirs[-1]
331 if dirs and not dirs[0]: dirs = dirs[1:]
332 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossumf668d171997-06-06 21:11:11 +0000333 if len(self.ftpcache) > MAXFTPCACHE:
334 # Prune the cache, rather arbitrarily
335 for k in self.ftpcache.keys():
336 if k != key:
337 v = self.ftpcache[k]
338 del self.ftpcache[k]
339 v.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000340 try:
341 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000342 self.ftpcache[key] = \
Guido van Rossum8a666e71998-02-13 01:39:16 +0000343 ftpwrapper(user, passwd,
344 host, port, dirs)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000345 if not file: type = 'D'
346 else: type = 'I'
347 for attr in attrs:
348 attr, value = splitvalue(attr)
349 if string.lower(attr) == 'type' and \
350 value in ('a', 'A', 'i', 'I', 'd', 'D'):
351 type = string.upper(value)
Guido van Rossum2966b321997-06-06 17:44:07 +0000352 return addinfourl(
353 self.ftpcache[key].retrfile(file, type),
Guido van Rossum8a666e71998-02-13 01:39:16 +0000354 noheaders(), "ftp:" + url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000355 except ftperrors(), msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000356 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000357
Guido van Rossum6d4d1c21998-03-12 14:32:55 +0000358 # Use "data" URL
359 def open_data(self, url, data=None):
360 # ignore POSTed data
361 #
362 # syntax of data URLs:
363 # dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
364 # mediatype := [ type "/" subtype ] *( ";" parameter )
365 # data := *urlchar
366 # parameter := attribute "=" value
367 import StringIO, mimetools, time
368 try:
369 [type, data] = string.split(url, ',', 1)
370 except ValueError:
371 raise IOError, ('data error', 'bad data URL')
372 if not type:
373 type = 'text/plain;charset=US-ASCII'
374 semi = string.rfind(type, ';')
375 if semi >= 0 and '=' not in type[semi:]:
376 encoding = type[semi+1:]
377 type = type[:semi]
378 else:
379 encoding = ''
380 msg = []
381 msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
382 time.gmtime(time.time())))
383 msg.append('Content-type: %s' % type)
384 if encoding == 'base64':
385 import base64
386 data = base64.decodestring(data)
387 else:
388 data = unquote(data)
389 msg.append('Content-length: %d' % len(data))
390 msg.append('')
391 msg.append(data)
392 msg = string.join(msg, '\n')
393 f = StringIO.StringIO(msg)
394 headers = mimetools.Message(f, 0)
395 f.fileno = None # needed for addinfourl
396 return addinfourl(f, headers, url)
397
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000398
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000399# Derived class with handlers for errors we can handle (perhaps)
400class FancyURLopener(URLopener):
401
402 def __init__(self, *args):
403 apply(URLopener.__init__, (self,) + args)
404 self.auth_cache = {}
405
406 # Default error handling -- don't raise an exception
407 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000408 return addinfourl(fp, headers, "http:" + url)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000409
Guido van Rossume6ad8911996-09-10 17:02:56 +0000410 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000411 def http_error_302(self, url, fp, errcode, errmsg, headers):
412 # XXX The server can force infinite recursion here!
413 if headers.has_key('location'):
414 newurl = headers['location']
415 elif headers.has_key('uri'):
416 newurl = headers['uri']
417 else:
418 return
419 void = fp.read()
420 fp.close()
421 return self.open(newurl)
422
Guido van Rossume6ad8911996-09-10 17:02:56 +0000423 # Error 301 -- also relocated (permanently)
424 http_error_301 = http_error_302
425
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000426 # Error 401 -- authentication required
427 # See this URL for a description of the basic authentication scheme:
428 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
429 def http_error_401(self, url, fp, errcode, errmsg, headers):
430 if headers.has_key('www-authenticate'):
431 stuff = headers['www-authenticate']
Guido van Rossum332e1441997-09-29 23:23:46 +0000432 import re
433 match = re.match(
434 '[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
435 if match:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000436 scheme, realm = match.groups()
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000437 if string.lower(scheme) == 'basic':
438 return self.retry_http_basic_auth(
439 url, realm)
440
441 def retry_http_basic_auth(self, url, realm):
442 host, selector = splithost(url)
443 i = string.find(host, '@') + 1
444 host = host[i:]
445 user, passwd = self.get_user_passwd(host, realm, i)
446 if not (user or passwd): return None
447 host = user + ':' + passwd + '@' + host
448 newurl = '//' + host + selector
449 return self.open_http(newurl)
450
451 def get_user_passwd(self, host, realm, clear_cache = 0):
452 key = realm + '@' + string.lower(host)
453 if self.auth_cache.has_key(key):
454 if clear_cache:
455 del self.auth_cache[key]
456 else:
457 return self.auth_cache[key]
458 user, passwd = self.prompt_user_passwd(host, realm)
459 if user or passwd: self.auth_cache[key] = (user, passwd)
460 return user, passwd
461
462 def prompt_user_passwd(self, host, realm):
463 # Override this in a GUI environment!
464 try:
465 user = raw_input("Enter username for %s at %s: " %
466 (realm, host))
467 self.echo_off()
468 try:
469 passwd = raw_input(
470 "Enter password for %s in %s at %s: " %
471 (user, realm, host))
472 finally:
473 self.echo_on()
474 return user, passwd
475 except KeyboardInterrupt:
476 return None, None
477
478 def echo_off(self):
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000479 # XXX Is this sufficient???
480 if hasattr(os, "system"):
481 os.system("stty -echo")
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000482
483 def echo_on(self):
Guido van Rossumc5d8fed1998-02-05 16:21:28 +0000484 # XXX Is this sufficient???
485 if hasattr(os, "system"):
486 print
487 os.system("stty echo")
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000488
489
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000490# Utility functions
491
492# Return the IP address of the magic hostname 'localhost'
493_localhost = None
494def localhost():
495 global _localhost
496 if not _localhost:
497 _localhost = socket.gethostbyname('localhost')
498 return _localhost
499
500# Return the IP address of the current host
501_thishost = None
502def thishost():
503 global _thishost
504 if not _thishost:
505 _thishost = socket.gethostbyname(socket.gethostname())
506 return _thishost
507
508# Return the set of errors raised by the FTP class
509_ftperrors = None
510def ftperrors():
511 global _ftperrors
512 if not _ftperrors:
513 import ftplib
Guido van Rossum2966b321997-06-06 17:44:07 +0000514 _ftperrors = ftplib.all_errors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000515 return _ftperrors
516
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000517# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000518_noheaders = None
519def noheaders():
520 global _noheaders
521 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000522 import mimetools
523 import StringIO
524 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000525 _noheaders.fp.close() # Recycle file descriptor
526 return _noheaders
527
528
529# Utility classes
530
531# Class used by open_ftp() for cache of open FTP connections
532class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000533 def __init__(self, user, passwd, host, port, dirs):
534 self.user = unquote(user or '')
535 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000536 self.host = host
537 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000538 self.dirs = []
539 for dir in dirs:
540 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000541 self.init()
542 def init(self):
543 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000544 self.busy = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000545 self.ftp = ftplib.FTP()
546 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000547 self.ftp.login(self.user, self.passwd)
548 for dir in self.dirs:
549 self.ftp.cwd(dir)
550 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000551 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000552 self.endtransfer()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000553 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
554 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000555 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000556 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000557 except ftplib.all_errors:
558 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000559 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000560 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000561 if file and not isdir:
Guido van Rossumd4990041997-12-28 04:21:20 +0000562 # Use nlst to see if the file exists at all
563 try:
564 self.ftp.nlst(file)
565 except ftplib.error_perm, reason:
566 raise IOError, ('ftp error', reason), \
567 sys.exc_info()[2]
Guido van Rossume7579621998-01-19 22:26:54 +0000568 # Restore the transfer mode!
569 self.ftp.voidcmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000570 # Try to retrieve as a file
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000571 try:
572 cmd = 'RETR ' + file
573 conn = self.ftp.transfercmd(cmd)
574 except ftplib.error_perm, reason:
575 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000576 raise IOError, ('ftp error', reason), \
Guido van Rossum332e1441997-09-29 23:23:46 +0000577 sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000578 if not conn:
Guido van Rossume7579621998-01-19 22:26:54 +0000579 # Set transfer mode to ASCII!
580 self.ftp.voidcmd('TYPE A')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000581 # Try a directory listing
582 if file: cmd = 'LIST ' + file
583 else: cmd = 'LIST'
584 conn = self.ftp.transfercmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000585 self.busy = 1
Guido van Rossumf668d171997-06-06 21:11:11 +0000586 return addclosehook(conn.makefile('rb'), self.endtransfer)
587 def endtransfer(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000588 if not self.busy:
589 return
590 self.busy = 0
Guido van Rossumf668d171997-06-06 21:11:11 +0000591 try:
592 self.ftp.voidresp()
593 except ftperrors():
594 pass
595 def close(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000596 self.endtransfer()
Guido van Rossumf668d171997-06-06 21:11:11 +0000597 try:
598 self.ftp.close()
599 except ftperrors():
600 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000601
602# Base class for addinfo and addclosehook
603class addbase:
604 def __init__(self, fp):
605 self.fp = fp
606 self.read = self.fp.read
607 self.readline = self.fp.readline
608 self.readlines = self.fp.readlines
609 self.fileno = self.fp.fileno
610 def __repr__(self):
611 return '<%s at %s whose fp = %s>' % (
612 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000613 def close(self):
614 self.read = None
615 self.readline = None
616 self.readlines = None
617 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000618 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000619 self.fp = None
620
621# Class to add a close hook to an open file
622class addclosehook(addbase):
623 def __init__(self, fp, closehook, *hookargs):
624 addbase.__init__(self, fp)
625 self.closehook = closehook
626 self.hookargs = hookargs
627 def close(self):
628 if self.closehook:
629 apply(self.closehook, self.hookargs)
630 self.closehook = None
631 self.hookargs = None
632 addbase.close(self)
633
634# class to add an info() method to an open file
635class addinfo(addbase):
636 def __init__(self, fp, headers):
637 addbase.__init__(self, fp)
638 self.headers = headers
639 def info(self):
640 return self.headers
641
Guido van Rossume6ad8911996-09-10 17:02:56 +0000642# class to add info() and geturl() methods to an open file
643class addinfourl(addbase):
644 def __init__(self, fp, headers, url):
645 addbase.__init__(self, fp)
646 self.headers = headers
647 self.url = url
648 def info(self):
649 return self.headers
650 def geturl(self):
651 return self.url
652
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000653
654# Utility to combine a URL with a base URL to form a new URL
655
656def basejoin(base, url):
657 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000658 if type:
659 # if url is complete (i.e., it contains a type), return it
660 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000661 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000662 type, basepath = splittype(base) # inherit type from base
663 if host:
664 # if url contains host, just inherit type
665 if type: return type + '://' + host + path
666 else:
667 # no type inherited, so url must have started with //
668 # just return it
669 return url
670 host, basepath = splithost(basepath) # inherit host
671 basepath, basetag = splittag(basepath) # remove extraneuous cruft
672 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000673 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000674 # non-absolute path name
675 if path[:1] in ('#', '?'):
676 # path is just a tag or query, attach to basepath
677 i = len(basepath)
678 else:
679 # else replace last component
680 i = string.rfind(basepath, '/')
681 if i < 0:
682 # basepath not absolute
683 if host:
684 # host present, make absolute
685 basepath = '/'
686 else:
687 # else keep non-absolute
688 basepath = ''
689 else:
690 # remove last file component
691 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000692 # Interpret ../ (important because of symlinks)
693 while basepath and path[:3] == '../':
694 path = path[3:]
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000695 i = string.rfind(basepath[:-1], '/')
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000696 if i > 0:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000697 basepath = basepath[:i+1]
698 elif i == 0:
699 basepath = '/'
700 break
701 else:
702 basepath = ''
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000703
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000704 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000705 if type and host: return type + '://' + host + path
706 elif type: return type + ':' + path
707 elif host: return '//' + host + path # don't know what this means
708 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000709
710
Guido van Rossum7c395db1994-07-04 22:14:49 +0000711# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000712# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000713# splittype('type:opaquestring') --> 'type', 'opaquestring'
714# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000715# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
716# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000717# splitport('host:port') --> 'host', 'port'
718# splitquery('/path?query') --> '/path', 'query'
719# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000720# splitattr('/path;attr1=value1;attr2=value2;...') ->
721# '/path', ['attr1=value1', 'attr2=value2', ...]
722# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000723# splitgophertype('/Xselector') --> 'X', 'selector'
724# unquote('abc%20def') -> 'abc def'
725# quote('abc def') -> 'abc%20def')
726
727def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000728 url = string.strip(url)
729 if url[:1] == '<' and url[-1:] == '>':
730 url = string.strip(url[1:-1])
731 if url[:4] == 'URL:': url = string.strip(url[4:])
732 return url
733
Guido van Rossum332e1441997-09-29 23:23:46 +0000734_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000735def splittype(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000736 global _typeprog
737 if _typeprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000738 import re
739 _typeprog = re.compile('^([^/:]+):')
Guido van Rossum332e1441997-09-29 23:23:46 +0000740
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000741 match = _typeprog.match(url)
Guido van Rossum332e1441997-09-29 23:23:46 +0000742 if match:
743 scheme = match.group(1)
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000744 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000745 return None, url
746
Guido van Rossum332e1441997-09-29 23:23:46 +0000747_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000748def splithost(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000749 global _hostprog
750 if _hostprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000751 import re
752 _hostprog = re.compile('^//([^/]+)(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000753
Guido van Rossuma08faba1998-03-30 17:17:24 +0000754 match = _hostprog.match(url)
Guido van Rossum332e1441997-09-29 23:23:46 +0000755 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000756 return None, url
757
Guido van Rossum332e1441997-09-29 23:23:46 +0000758_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000759def splituser(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000760 global _userprog
761 if _userprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000762 import re
763 _userprog = re.compile('^([^@]*)@(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000764
Guido van Rossuma08faba1998-03-30 17:17:24 +0000765 match = _userprog.match(host)
Guido van Rossum332e1441997-09-29 23:23:46 +0000766 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000767 return None, host
768
Guido van Rossum332e1441997-09-29 23:23:46 +0000769_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000770def splitpasswd(user):
Guido van Rossum332e1441997-09-29 23:23:46 +0000771 global _passwdprog
772 if _passwdprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000773 import re
774 _passwdprog = re.compile('^([^:]*):(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000775
Guido van Rossuma08faba1998-03-30 17:17:24 +0000776 match = _passwdprog.match(user)
Guido van Rossum332e1441997-09-29 23:23:46 +0000777 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000778 return user, None
779
Guido van Rossum332e1441997-09-29 23:23:46 +0000780_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000781def splitport(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000782 global _portprog
783 if _portprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000784 import re
785 _portprog = re.compile('^(.*):([0-9]+)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000786
Guido van Rossuma08faba1998-03-30 17:17:24 +0000787 match = _portprog.match(host)
Guido van Rossum332e1441997-09-29 23:23:46 +0000788 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000789 return host, None
790
Guido van Rossum53725a21996-06-13 19:12:35 +0000791# Split host and port, returning numeric port.
792# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000793# Return numerical port if a valid number are found after ':'.
794# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000795_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000796def splitnport(host, defport=-1):
Guido van Rossum332e1441997-09-29 23:23:46 +0000797 global _nportprog
798 if _nportprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000799 import re
800 _nportprog = re.compile('^(.*):(.*)$')
801
Guido van Rossuma08faba1998-03-30 17:17:24 +0000802 match = _nportprog.match(host)
Guido van Rossum332e1441997-09-29 23:23:46 +0000803 if match:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000804 host, port = match.group(1, 2)
805 try:
806 if not port: raise string.atoi_error, "no digits"
807 nport = string.atoi(port)
808 except string.atoi_error:
809 nport = None
810 return host, nport
Guido van Rossum53725a21996-06-13 19:12:35 +0000811 return host, defport
812
Guido van Rossum332e1441997-09-29 23:23:46 +0000813_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000814def splitquery(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000815 global _queryprog
816 if _queryprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000817 import re
818 _queryprog = re.compile('^(.*)\?([^?]*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000819
Guido van Rossuma08faba1998-03-30 17:17:24 +0000820 match = _queryprog.match(url)
Guido van Rossum332e1441997-09-29 23:23:46 +0000821 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000822 return url, None
823
Guido van Rossum332e1441997-09-29 23:23:46 +0000824_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000825def splittag(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000826 global _tagprog
827 if _tagprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000828 import re
829 _tagprog = re.compile('^(.*)#([^#]*)$')
830
Guido van Rossuma08faba1998-03-30 17:17:24 +0000831 match = _tagprog.match(url)
Guido van Rossum332e1441997-09-29 23:23:46 +0000832 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000833 return url, None
834
Guido van Rossum7c395db1994-07-04 22:14:49 +0000835def splitattr(url):
836 words = string.splitfields(url, ';')
837 return words[0], words[1:]
838
Guido van Rossum332e1441997-09-29 23:23:46 +0000839_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000840def splitvalue(attr):
Guido van Rossum332e1441997-09-29 23:23:46 +0000841 global _valueprog
842 if _valueprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000843 import re
844 _valueprog = re.compile('^([^=]*)=(.*)$')
Guido van Rossum332e1441997-09-29 23:23:46 +0000845
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000846 match = _valueprog.match(attr)
Guido van Rossum332e1441997-09-29 23:23:46 +0000847 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000848 return attr, None
849
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000850def splitgophertype(selector):
851 if selector[:1] == '/' and selector[1:2]:
852 return selector[1], selector[2:]
853 return None, selector
854
Guido van Rossum332e1441997-09-29 23:23:46 +0000855_quoteprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000856def unquote(s):
Guido van Rossum332e1441997-09-29 23:23:46 +0000857 global _quoteprog
858 if _quoteprog is None:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000859 import re
860 _quoteprog = re.compile('%[0-9a-fA-F][0-9a-fA-F]')
861
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000862 i = 0
863 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000864 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000865 while 0 <= i < n:
Guido van Rossum332e1441997-09-29 23:23:46 +0000866 match = _quoteprog.search(s, i)
867 if not match:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000868 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000869 break
Guido van Rossum332e1441997-09-29 23:23:46 +0000870 j = match.start(0)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000871 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000872 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000873 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000874
Guido van Rossum0564e121996-12-13 14:47:36 +0000875def unquote_plus(s):
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000876 if '+' in s:
877 # replace '+' with ' '
878 s = string.join(string.split(s, '+'), ' ')
879 return unquote(s)
Guido van Rossum0564e121996-12-13 14:47:36 +0000880
Guido van Rossum3bb54481994-08-29 10:52:58 +0000881always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000882def quote(s, safe = '/'):
883 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000884 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000885 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000886 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000887 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000888 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000889 res.append('%%%02x' % ord(c))
890 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000891
Guido van Rossum0564e121996-12-13 14:47:36 +0000892def quote_plus(s, safe = '/'):
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000893 if ' ' in s:
894 # replace ' ' with '+'
895 s = string.join(string.split(s, ' '), '+')
896 return quote(s, safe + '+')
897 else:
898 return quote(s, safe)
Guido van Rossum0564e121996-12-13 14:47:36 +0000899
Guido van Rossum442e7201996-03-20 15:33:11 +0000900
901# Proxy handling
902def getproxies():
903 """Return a dictionary of protocol scheme -> proxy server URL mappings.
904
905 Scan the environment for variables named <scheme>_proxy;
906 this seems to be the standard convention. If you need a
907 different way, you can pass a proxies dictionary to the
908 [Fancy]URLopener constructor.
909
910 """
911 proxies = {}
912 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000913 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000914 if value and name[-6:] == '_proxy':
915 proxies[name[:-6]] = value
916 return proxies
917
918
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000919# Test and time quote() and unquote()
920def test1():
921 import time
922 s = ''
923 for i in range(256): s = s + chr(i)
924 s = s*4
925 t0 = time.time()
926 qs = quote(s)
927 uqs = unquote(qs)
928 t1 = time.time()
929 if uqs != s:
930 print 'Wrong!'
931 print `s`
932 print `qs`
933 print `uqs`
934 print round(t1 - t0, 3), 'sec'
935
936
937# Test program
938def test():
939 import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000940 args = sys.argv[1:]
941 if not args:
942 args = [
943 '/etc/passwd',
944 'file:/etc/passwd',
945 'file://localhost/etc/passwd',
Guido van Rossum332e1441997-09-29 23:23:46 +0000946 'ftp://ftp.python.org/etc/passwd',
947 'gopher://gopher.micro.umn.edu/1/',
948 'http://www.python.org/index.html',
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000949 ]
950 try:
951 for url in args:
952 print '-'*10, url, '-'*10
953 fn, h = urlretrieve(url)
954 print fn, h
955 if h:
956 print '======'
957 for k in h.keys(): print k + ':', h[k]
958 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000959 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000960 data = fp.read()
961 del fp
Guido van Rossum332e1441997-09-29 23:23:46 +0000962 if '\r' in data:
Guido van Rossum7e7ca0b1998-03-26 21:01:39 +0000963 table = string.maketrans("", "")
964 data = string.translate(data, table, "\r")
Guido van Rossum332e1441997-09-29 23:23:46 +0000965 print data
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000966 fn, h = None, None
967 print '-'*40
968 finally:
969 urlcleanup()
970
971# Run test program when run as a script
972if __name__ == '__main__':
Guido van Rossum332e1441997-09-29 23:23:46 +0000973 test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000974 test()