blob: a818adfd58dd175d6c2e3c74f9f81d0901e28c1e [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 Rossum036309b1997-10-27 18:56:19 +000030__version__ = '1.9'
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 Rossum2281d351996-06-26 19:47:37 +000037elif os.name == 'nt':
38 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:
67 return _urlopener.retrieve(url, filename)
68 else:
69 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()
90 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +000091 server_version = "Python-urllib/%s" % __version__
92 self.addheaders = [('User-agent', server_version)]
Guido van Rossum10499321997-09-08 02:16:33 +000093 self.__tempfiles = []
Guido van Rossum036309b1997-10-27 18:56:19 +000094 self.__unlink = os.unlink # See cleanup()
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000095 self.tempcache = None
96 # Undocumented feature: if you assign {} to tempcache,
97 # it is used to cache files retrieved with
98 # self.retrieve(). This is not enabled by default
99 # since it does not work for changing documents (and I
100 # haven't got the logic to check expiration headers
101 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000102 self.ftpcache = ftpcache
103 # Undocumented feature: you can use a different
104 # ftp cache by assigning to the .ftpcache member;
105 # in case you want logically independent URL openers
106
107 def __del__(self):
108 self.close()
109
110 def close(self):
111 self.cleanup()
112
113 def cleanup(self):
Guido van Rossum036309b1997-10-27 18:56:19 +0000114 # This code sometimes runs when the rest of this module
115 # has already been deleted, so it can't use any globals
116 # or import anything.
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000117 if self.__tempfiles:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000118 for file in self.__tempfiles:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000119 try:
Guido van Rossum036309b1997-10-27 18:56:19 +0000120 self.__unlink(file)
121 except:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000122 pass
Guido van Rossum036309b1997-10-27 18:56:19 +0000123 del self.__tempfiles[:]
124 if self.tempcache:
125 self.tempcache.clear()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000126
127 # Add a header to be used by the HTTP interface only
128 # e.g. u.addheader('Accept', 'sound/basic')
129 def addheader(self, *args):
130 self.addheaders.append(args)
131
132 # External interface
133 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumbd013741996-12-10 16:00:28 +0000134 def open(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000135 fullurl = unwrap(fullurl)
136 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000137 if not type: type = 'file'
Guido van Rossume6ad8911996-09-10 17:02:56 +0000138 self.openedurl = '%s:%s' % (type, url)
Guido van Rossum442e7201996-03-20 15:33:11 +0000139 if self.proxies.has_key(type):
140 proxy = self.proxies[type]
141 type, proxy = splittype(proxy)
142 host, selector = splithost(proxy)
143 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000144 name = 'open_' + type
145 if '-' in name:
Guido van Rossum332e1441997-09-29 23:23:46 +0000146 # replace - with _
147 name = string.join(string.split(name, '-'), '_')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000148 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000149 if data is None:
150 return self.open_unknown(fullurl)
151 else:
152 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000153 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000154 if data is None:
155 return getattr(self, name)(url)
156 else:
157 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000158 except socket.error, msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000159 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000160
Guido van Rossumca445401995-08-29 19:19:12 +0000161 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000162 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000163 type, url = splittype(fullurl)
164 raise IOError, ('url error', 'unknown url type', type)
165
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000166 # External interface
167 # retrieve(url) returns (filename, None) for a local object
168 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000169 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000170 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000171 return self.tempcache[url]
172 url1 = unwrap(url)
Guido van Rossum5b1b33c1996-10-22 13:28:37 +0000173 self.openedurl = url1
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000174 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000175 self.tempcache[url] = self.tempcache[url1]
176 return self.tempcache[url1]
177 type, url1 = splittype(url1)
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:
188 import tempfile
189 filename = tempfile.mktemp()
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000190 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':
220 realhost = None
221 else:
Guido van Rossum78c96371996-08-26 18:09:59 +0000222 realhost, rest = splithost(rest)
223 user_passwd, realhost = splituser(realhost)
224 if user_passwd:
225 selector = "%s://%s%s" % (urltype,
226 realhost, rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000227 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000228 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000229 if user_passwd:
230 import base64
231 auth = string.strip(base64.encodestring(user_passwd))
232 else:
233 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000234 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000235 if data is not None:
236 h.putrequest('POST', selector)
237 h.putheader('Content-type',
238 'application/x-www-form-urlencoded')
239 h.putheader('Content-length', '%d' % len(data))
240 else:
241 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000242 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000243 if realhost: h.putheader('Host', realhost)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000244 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000245 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000246 if data is not None:
247 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000248 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000249 fp = h.getfile()
250 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000251 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000252 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000253 return self.http_error(url,
254 fp, errcode, errmsg, headers)
255
256 # Handle http errors.
257 # Derived class can override this, or provide specific handlers
258 # named http_error_DDD where DDD is the 3-digit error code
259 def http_error(self, url, fp, errcode, errmsg, headers):
260 # First check if there's a specific handler for this error
261 name = 'http_error_%d' % errcode
262 if hasattr(self, name):
263 method = getattr(self, name)
264 result = method(url, fp, errcode, errmsg, headers)
265 if result: return result
266 return self.http_error_default(
267 url, fp, errcode, errmsg, headers)
268
269 # Default http error handler: close the connection and raises IOError
270 def http_error_default(self, url, fp, errcode, errmsg, headers):
271 void = fp.read()
272 fp.close()
273 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000274
275 # Use Gopher protocol
276 def open_gopher(self, url):
277 import gopherlib
278 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000279 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000280 type, selector = splitgophertype(selector)
281 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000282 selector = unquote(selector)
283 if query:
284 query = unquote(query)
285 fp = gopherlib.send_query(selector, query, host)
286 else:
287 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000288 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000289
290 # Use local file or FTP depending on form of URL
291 def open_file(self, url):
Guido van Rossumb6784dc1997-08-20 23:34:01 +0000292 if url[:2] == '//' and url[2:3] != '/':
293 return self.open_ftp(url)
294 else:
295 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000296
297 # Use local file
298 def open_local_file(self, url):
299 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000300 if not host:
Guido van Rossum2966b321997-06-06 17:44:07 +0000301 return addinfourl(
302 open(url2pathname(file), 'rb'),
303 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000304 host, port = splitport(host)
305 if not port and socket.gethostbyname(host) in (
306 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000307 file = unquote(file)
Guido van Rossum2966b321997-06-06 17:44:07 +0000308 return addinfourl(
309 open(url2pathname(file), 'rb'),
310 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000311 raise IOError, ('local file error', 'not on local host')
312
313 # Use FTP protocol
314 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000315 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000316 if not host: raise IOError, ('ftp error', 'no host given')
317 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000318 user, host = splituser(host)
319 if user: user, passwd = splitpasswd(user)
320 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000321 host = socket.gethostbyname(host)
322 if not port:
323 import ftplib
324 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000325 path, attrs = splitattr(path)
326 dirs = string.splitfields(path, '/')
327 dirs, file = dirs[:-1], dirs[-1]
328 if dirs and not dirs[0]: dirs = dirs[1:]
329 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossumf668d171997-06-06 21:11:11 +0000330 if len(self.ftpcache) > MAXFTPCACHE:
331 # Prune the cache, rather arbitrarily
332 for k in self.ftpcache.keys():
333 if k != key:
334 v = self.ftpcache[k]
335 del self.ftpcache[k]
336 v.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000337 try:
338 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000339 self.ftpcache[key] = \
340 ftpwrapper(user, passwd,
341 host, port, dirs)
342 if not file: type = 'D'
343 else: type = 'I'
344 for attr in attrs:
345 attr, value = splitvalue(attr)
346 if string.lower(attr) == 'type' and \
347 value in ('a', 'A', 'i', 'I', 'd', 'D'):
348 type = string.upper(value)
Guido van Rossum2966b321997-06-06 17:44:07 +0000349 return addinfourl(
350 self.ftpcache[key].retrfile(file, type),
351 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000352 except ftperrors(), msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000353 raise IOError, ('ftp error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000354
355
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000356# Derived class with handlers for errors we can handle (perhaps)
357class FancyURLopener(URLopener):
358
359 def __init__(self, *args):
360 apply(URLopener.__init__, (self,) + args)
361 self.auth_cache = {}
362
363 # Default error handling -- don't raise an exception
364 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000365 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000366
Guido van Rossume6ad8911996-09-10 17:02:56 +0000367 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000368 def http_error_302(self, url, fp, errcode, errmsg, headers):
369 # XXX The server can force infinite recursion here!
370 if headers.has_key('location'):
371 newurl = headers['location']
372 elif headers.has_key('uri'):
373 newurl = headers['uri']
374 else:
375 return
376 void = fp.read()
377 fp.close()
378 return self.open(newurl)
379
Guido van Rossume6ad8911996-09-10 17:02:56 +0000380 # Error 301 -- also relocated (permanently)
381 http_error_301 = http_error_302
382
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000383 # Error 401 -- authentication required
384 # See this URL for a description of the basic authentication scheme:
385 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
386 def http_error_401(self, url, fp, errcode, errmsg, headers):
387 if headers.has_key('www-authenticate'):
388 stuff = headers['www-authenticate']
Guido van Rossum332e1441997-09-29 23:23:46 +0000389 import re
390 match = re.match(
391 '[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
392 if match:
393 scheme, realm = match.group()
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000394 if string.lower(scheme) == 'basic':
395 return self.retry_http_basic_auth(
396 url, realm)
397
398 def retry_http_basic_auth(self, url, realm):
399 host, selector = splithost(url)
400 i = string.find(host, '@') + 1
401 host = host[i:]
402 user, passwd = self.get_user_passwd(host, realm, i)
403 if not (user or passwd): return None
404 host = user + ':' + passwd + '@' + host
405 newurl = '//' + host + selector
406 return self.open_http(newurl)
407
408 def get_user_passwd(self, host, realm, clear_cache = 0):
409 key = realm + '@' + string.lower(host)
410 if self.auth_cache.has_key(key):
411 if clear_cache:
412 del self.auth_cache[key]
413 else:
414 return self.auth_cache[key]
415 user, passwd = self.prompt_user_passwd(host, realm)
416 if user or passwd: self.auth_cache[key] = (user, passwd)
417 return user, passwd
418
419 def prompt_user_passwd(self, host, realm):
420 # Override this in a GUI environment!
421 try:
422 user = raw_input("Enter username for %s at %s: " %
423 (realm, host))
424 self.echo_off()
425 try:
426 passwd = raw_input(
427 "Enter password for %s in %s at %s: " %
428 (user, realm, host))
429 finally:
430 self.echo_on()
431 return user, passwd
432 except KeyboardInterrupt:
433 return None, None
434
435 def echo_off(self):
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000436 os.system("stty -echo")
437
438 def echo_on(self):
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000439 print
440 os.system("stty echo")
441
442
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000443# Utility functions
444
445# Return the IP address of the magic hostname 'localhost'
446_localhost = None
447def localhost():
448 global _localhost
449 if not _localhost:
450 _localhost = socket.gethostbyname('localhost')
451 return _localhost
452
453# Return the IP address of the current host
454_thishost = None
455def thishost():
456 global _thishost
457 if not _thishost:
458 _thishost = socket.gethostbyname(socket.gethostname())
459 return _thishost
460
461# Return the set of errors raised by the FTP class
462_ftperrors = None
463def ftperrors():
464 global _ftperrors
465 if not _ftperrors:
466 import ftplib
Guido van Rossum2966b321997-06-06 17:44:07 +0000467 _ftperrors = ftplib.all_errors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000468 return _ftperrors
469
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000470# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000471_noheaders = None
472def noheaders():
473 global _noheaders
474 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000475 import mimetools
476 import StringIO
477 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000478 _noheaders.fp.close() # Recycle file descriptor
479 return _noheaders
480
481
482# Utility classes
483
484# Class used by open_ftp() for cache of open FTP connections
485class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000486 def __init__(self, user, passwd, host, port, dirs):
487 self.user = unquote(user or '')
488 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000489 self.host = host
490 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000491 self.dirs = []
492 for dir in dirs:
493 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000494 self.init()
495 def init(self):
496 import ftplib
497 self.ftp = ftplib.FTP()
498 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000499 self.ftp.login(self.user, self.passwd)
500 for dir in self.dirs:
501 self.ftp.cwd(dir)
502 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000503 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000504 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
505 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000506 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000507 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000508 except ftplib.all_errors:
509 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000510 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000511 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000512 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000513 try:
514 cmd = 'RETR ' + file
515 conn = self.ftp.transfercmd(cmd)
516 except ftplib.error_perm, reason:
517 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000518 raise IOError, ('ftp error', reason), \
Guido van Rossum332e1441997-09-29 23:23:46 +0000519 sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000520 if not conn:
521 # Try a directory listing
522 if file: cmd = 'LIST ' + file
523 else: cmd = 'LIST'
524 conn = self.ftp.transfercmd(cmd)
Guido van Rossumf668d171997-06-06 21:11:11 +0000525 return addclosehook(conn.makefile('rb'), self.endtransfer)
526 def endtransfer(self):
527 try:
528 self.ftp.voidresp()
529 except ftperrors():
530 pass
531 def close(self):
532 try:
533 self.ftp.close()
534 except ftperrors():
535 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000536
537# Base class for addinfo and addclosehook
538class addbase:
539 def __init__(self, fp):
540 self.fp = fp
541 self.read = self.fp.read
542 self.readline = self.fp.readline
543 self.readlines = self.fp.readlines
544 self.fileno = self.fp.fileno
545 def __repr__(self):
546 return '<%s at %s whose fp = %s>' % (
547 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000548 def close(self):
549 self.read = None
550 self.readline = None
551 self.readlines = None
552 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000553 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000554 self.fp = None
555
556# Class to add a close hook to an open file
557class addclosehook(addbase):
558 def __init__(self, fp, closehook, *hookargs):
559 addbase.__init__(self, fp)
560 self.closehook = closehook
561 self.hookargs = hookargs
562 def close(self):
563 if self.closehook:
564 apply(self.closehook, self.hookargs)
565 self.closehook = None
566 self.hookargs = None
567 addbase.close(self)
568
569# class to add an info() method to an open file
570class addinfo(addbase):
571 def __init__(self, fp, headers):
572 addbase.__init__(self, fp)
573 self.headers = headers
574 def info(self):
575 return self.headers
576
Guido van Rossume6ad8911996-09-10 17:02:56 +0000577# class to add info() and geturl() methods to an open file
578class addinfourl(addbase):
579 def __init__(self, fp, headers, url):
580 addbase.__init__(self, fp)
581 self.headers = headers
582 self.url = url
583 def info(self):
584 return self.headers
585 def geturl(self):
586 return self.url
587
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000588
589# Utility to combine a URL with a base URL to form a new URL
590
591def basejoin(base, url):
592 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000593 if type:
594 # if url is complete (i.e., it contains a type), return it
595 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000596 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000597 type, basepath = splittype(base) # inherit type from base
598 if host:
599 # if url contains host, just inherit type
600 if type: return type + '://' + host + path
601 else:
602 # no type inherited, so url must have started with //
603 # just return it
604 return url
605 host, basepath = splithost(basepath) # inherit host
606 basepath, basetag = splittag(basepath) # remove extraneuous cruft
607 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000608 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000609 # non-absolute path name
610 if path[:1] in ('#', '?'):
611 # path is just a tag or query, attach to basepath
612 i = len(basepath)
613 else:
614 # else replace last component
615 i = string.rfind(basepath, '/')
616 if i < 0:
617 # basepath not absolute
618 if host:
619 # host present, make absolute
620 basepath = '/'
621 else:
622 # else keep non-absolute
623 basepath = ''
624 else:
625 # remove last file component
626 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000627 # Interpret ../ (important because of symlinks)
628 while basepath and path[:3] == '../':
629 path = path[3:]
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000630 i = string.rfind(basepath[:-1], '/')
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000631 if i > 0:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000632 basepath = basepath[:i+1]
633 elif i == 0:
634 basepath = '/'
635 break
636 else:
637 basepath = ''
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000638
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000639 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000640 if type and host: return type + '://' + host + path
641 elif type: return type + ':' + path
642 elif host: return '//' + host + path # don't know what this means
643 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000644
645
Guido van Rossum7c395db1994-07-04 22:14:49 +0000646# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000647# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000648# splittype('type:opaquestring') --> 'type', 'opaquestring'
649# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000650# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
651# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000652# splitport('host:port') --> 'host', 'port'
653# splitquery('/path?query') --> '/path', 'query'
654# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000655# splitattr('/path;attr1=value1;attr2=value2;...') ->
656# '/path', ['attr1=value1', 'attr2=value2', ...]
657# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000658# splitgophertype('/Xselector') --> 'X', 'selector'
659# unquote('abc%20def') -> 'abc def'
660# quote('abc def') -> 'abc%20def')
661
662def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000663 url = string.strip(url)
664 if url[:1] == '<' and url[-1:] == '>':
665 url = string.strip(url[1:-1])
666 if url[:4] == 'URL:': url = string.strip(url[4:])
667 return url
668
Guido van Rossum332e1441997-09-29 23:23:46 +0000669_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000670def splittype(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000671 global _typeprog
672 if _typeprog is None:
673 import re
674 _typeprog = re.compile('^([^/:]+):')
675
676 match = _typeprog.match(url)
677 if match:
678 scheme = match.group(1)
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000679 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000680 return None, url
681
Guido van Rossum332e1441997-09-29 23:23:46 +0000682_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000683def splithost(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000684 global _hostprog
685 if _hostprog is None:
686 import re
687 _hostprog = re.compile('^//([^/]+)(.*)$')
688
689 match = _hostprog.match(url)
690 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000691 return None, url
692
Guido van Rossum332e1441997-09-29 23:23:46 +0000693_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000694def splituser(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000695 global _userprog
696 if _userprog is None:
697 import re
698 _userprog = re.compile('^([^@]*)@(.*)$')
699
700 match = _userprog.match(host)
701 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000702 return None, host
703
Guido van Rossum332e1441997-09-29 23:23:46 +0000704_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000705def splitpasswd(user):
Guido van Rossum332e1441997-09-29 23:23:46 +0000706 global _passwdprog
707 if _passwdprog is None:
708 import re
709 _passwdprog = re.compile('^([^:]*):(.*)$')
710
Fred Drake654451d1997-10-14 13:30:57 +0000711 match = _passwdprog.match(user)
Guido van Rossum332e1441997-09-29 23:23:46 +0000712 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000713 return user, None
714
Guido van Rossum332e1441997-09-29 23:23:46 +0000715_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000716def splitport(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000717 global _portprog
718 if _portprog is None:
719 import re
720 _portprog = re.compile('^(.*):([0-9]+)$')
721
722 match = _portprog.match(host)
723 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000724 return host, None
725
Guido van Rossum53725a21996-06-13 19:12:35 +0000726# Split host and port, returning numeric port.
727# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000728# Return numerical port if a valid number are found after ':'.
729# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000730_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000731def splitnport(host, defport=-1):
Guido van Rossum332e1441997-09-29 23:23:46 +0000732 global _nportprog
733 if _nportprog is None:
734 import re
735 _nportprog = re.compile('^(.*):(.*)$')
736
737 match = _nportprog.match(host)
738 if match:
739 host, port = match.group(1, 2)
Guido van Rossum84a00a81996-06-17 17:11:40 +0000740 try:
741 if not port: raise string.atoi_error, "no digits"
742 nport = string.atoi(port)
743 except string.atoi_error:
744 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000745 return host, nport
746 return host, defport
747
Guido van Rossum332e1441997-09-29 23:23:46 +0000748_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000749def splitquery(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000750 global _queryprog
751 if _queryprog is None:
752 import re
753 _queryprog = re.compile('^(.*)\?([^?]*)$')
754
755 match = _queryprog.match(url)
756 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000757 return url, None
758
Guido van Rossum332e1441997-09-29 23:23:46 +0000759_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000760def splittag(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000761 global _tagprog
762 if _tagprog is None:
763 import re
764 _tagprog = re.compile('^(.*)#([^#]*)$')
765
766 match = _tagprog.match(url)
767 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000768 return url, None
769
Guido van Rossum7c395db1994-07-04 22:14:49 +0000770def splitattr(url):
771 words = string.splitfields(url, ';')
772 return words[0], words[1:]
773
Guido van Rossum332e1441997-09-29 23:23:46 +0000774_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000775def splitvalue(attr):
Guido van Rossum332e1441997-09-29 23:23:46 +0000776 global _valueprog
777 if _valueprog is None:
778 import re
779 _valueprog = re.compile('^([^=]*)=(.*)$')
780
781 match = _valueprog.match(attr)
782 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000783 return attr, None
784
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000785def splitgophertype(selector):
786 if selector[:1] == '/' and selector[1:2]:
787 return selector[1], selector[2:]
788 return None, selector
789
Guido van Rossum332e1441997-09-29 23:23:46 +0000790_quoteprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000791def unquote(s):
Guido van Rossum332e1441997-09-29 23:23:46 +0000792 global _quoteprog
793 if _quoteprog is None:
794 import re
795 _quoteprog = re.compile('%[0-9a-fA-F][0-9a-fA-F]')
796
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000797 i = 0
798 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000799 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000800 while 0 <= i < n:
Guido van Rossum332e1441997-09-29 23:23:46 +0000801 match = _quoteprog.search(s, i)
802 if not match:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000803 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000804 break
Guido van Rossum332e1441997-09-29 23:23:46 +0000805 j = match.start(0)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000806 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000807 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000808 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000809
Guido van Rossum0564e121996-12-13 14:47:36 +0000810def unquote_plus(s):
811 if '+' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000812 # replace '+' with ' '
813 s = string.join(string.split(s, '+'), ' ')
Guido van Rossum0564e121996-12-13 14:47:36 +0000814 return unquote(s)
815
Guido van Rossum3bb54481994-08-29 10:52:58 +0000816always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000817def quote(s, safe = '/'):
818 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000819 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000820 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000821 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000822 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000823 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000824 res.append('%%%02x' % ord(c))
825 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000826
Guido van Rossum0564e121996-12-13 14:47:36 +0000827def quote_plus(s, safe = '/'):
828 if ' ' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000829 # replace ' ' with '+'
830 s = string.join(string.split(s, ' '), '+')
Guido van Rossum0564e121996-12-13 14:47:36 +0000831 return quote(s, safe + '+')
832 else:
833 return quote(s, safe)
834
Guido van Rossum442e7201996-03-20 15:33:11 +0000835
836# Proxy handling
837def getproxies():
838 """Return a dictionary of protocol scheme -> proxy server URL mappings.
839
840 Scan the environment for variables named <scheme>_proxy;
841 this seems to be the standard convention. If you need a
842 different way, you can pass a proxies dictionary to the
843 [Fancy]URLopener constructor.
844
845 """
846 proxies = {}
847 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000848 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000849 if value and name[-6:] == '_proxy':
850 proxies[name[:-6]] = value
851 return proxies
852
853
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000854# Test and time quote() and unquote()
855def test1():
856 import time
857 s = ''
858 for i in range(256): s = s + chr(i)
859 s = s*4
860 t0 = time.time()
861 qs = quote(s)
862 uqs = unquote(qs)
863 t1 = time.time()
864 if uqs != s:
865 print 'Wrong!'
866 print `s`
867 print `qs`
868 print `uqs`
869 print round(t1 - t0, 3), 'sec'
870
871
872# Test program
873def test():
874 import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000875 args = sys.argv[1:]
876 if not args:
877 args = [
878 '/etc/passwd',
879 'file:/etc/passwd',
880 'file://localhost/etc/passwd',
Guido van Rossum332e1441997-09-29 23:23:46 +0000881 'ftp://ftp.python.org/etc/passwd',
882 'gopher://gopher.micro.umn.edu/1/',
883 'http://www.python.org/index.html',
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000884 ]
885 try:
886 for url in args:
887 print '-'*10, url, '-'*10
888 fn, h = urlretrieve(url)
889 print fn, h
890 if h:
891 print '======'
892 for k in h.keys(): print k + ':', h[k]
893 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000894 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000895 data = fp.read()
896 del fp
Guido van Rossum332e1441997-09-29 23:23:46 +0000897 if '\r' in data:
898 table = string.maketrans("", "")
899 data = string.translate(data, table, "\r")
900 print data
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000901 fn, h = None, None
902 print '-'*40
903 finally:
904 urlcleanup()
905
906# Run test program when run as a script
907if __name__ == '__main__':
Guido van Rossum332e1441997-09-29 23:23:46 +0000908 test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000909 test()