blob: b9a82d169211213f9fd153c3bcb59ba7815f099c [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()
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:
126 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)
137 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000138 if not type: type = 'file'
Guido van Rossume6ad8911996-09-10 17:02:56 +0000139 self.openedurl = '%s:%s' % (type, url)
Guido van Rossum442e7201996-03-20 15:33:11 +0000140 if self.proxies.has_key(type):
141 proxy = self.proxies[type]
142 type, proxy = splittype(proxy)
143 host, selector = splithost(proxy)
144 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000145 name = 'open_' + type
146 if '-' in name:
Guido van Rossum332e1441997-09-29 23:23:46 +0000147 # replace - with _
148 name = string.join(string.split(name, '-'), '_')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000149 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000150 if data is None:
151 return self.open_unknown(fullurl)
152 else:
153 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000154 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000155 if data is None:
156 return getattr(self, name)(url)
157 else:
158 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000159 except socket.error, msg:
Guido van Rossum332e1441997-09-29 23:23:46 +0000160 raise IOError, ('socket error', msg), sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000161
Guido van Rossumca445401995-08-29 19:19:12 +0000162 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000163 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000164 type, url = splittype(fullurl)
165 raise IOError, ('url error', 'unknown url type', type)
166
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000167 # External interface
168 # retrieve(url) returns (filename, None) for a local object
169 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000170 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000171 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000172 return self.tempcache[url]
173 url1 = unwrap(url)
Guido van Rossum5b1b33c1996-10-22 13:28:37 +0000174 self.openedurl = url1
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000175 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000176 self.tempcache[url] = self.tempcache[url1]
177 return self.tempcache[url1]
178 type, url1 = splittype(url1)
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)
182 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000183 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000184 except IOError, msg:
185 pass
186 fp = self.open(url)
187 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000188 if not filename:
189 import tempfile
190 filename = tempfile.mktemp()
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000191 self.__tempfiles.append(filename)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000192 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000193 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000194 self.tempcache[url] = result
Guido van Rossumc511aee1997-04-11 19:01:48 +0000195 tfp = open(filename, 'wb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000196 bs = 1024*8
197 block = fp.read(bs)
198 while block:
199 tfp.write(block)
200 block = fp.read(bs)
Guido van Rossumab0abdc1997-08-26 19:06:40 +0000201 fp.close()
202 tfp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000203 del fp
204 del tfp
205 return result
206
207 # Each method named open_<type> knows how to open that type of URL
208
209 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000210 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000211 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000212 if type(url) is type(""):
213 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000214 user_passwd, host = splituser(host)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000215 realhost = host
Guido van Rossum442e7201996-03-20 15:33:11 +0000216 else:
217 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000218 urltype, rest = splittype(selector)
Guido van Rossumfd795661997-04-02 05:46:35 +0000219 user_passwd = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000220 if string.lower(urltype) != 'http':
221 realhost = None
222 else:
Guido van Rossum78c96371996-08-26 18:09:59 +0000223 realhost, rest = splithost(rest)
224 user_passwd, realhost = splituser(realhost)
225 if user_passwd:
226 selector = "%s://%s%s" % (urltype,
227 realhost, 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 Rossume6ad8911996-09-10 17:02:56 +0000252 return addinfourl(fp, headers, self.openedurl)
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 Rossume6ad8911996-09-10 17:02:56 +0000289 return addinfourl(fp, noheaders(), self.openedurl)
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 Rossumb6784dc1997-08-20 23:34:01 +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] = \
343 ftpwrapper(user, passwd,
344 host, port, dirs)
345 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),
354 noheaders(), self.openedurl)
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
358
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000359# Derived class with handlers for errors we can handle (perhaps)
360class FancyURLopener(URLopener):
361
362 def __init__(self, *args):
363 apply(URLopener.__init__, (self,) + args)
364 self.auth_cache = {}
365
366 # Default error handling -- don't raise an exception
367 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000368 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000369
Guido van Rossume6ad8911996-09-10 17:02:56 +0000370 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000371 def http_error_302(self, url, fp, errcode, errmsg, headers):
372 # XXX The server can force infinite recursion here!
373 if headers.has_key('location'):
374 newurl = headers['location']
375 elif headers.has_key('uri'):
376 newurl = headers['uri']
377 else:
378 return
379 void = fp.read()
380 fp.close()
381 return self.open(newurl)
382
Guido van Rossume6ad8911996-09-10 17:02:56 +0000383 # Error 301 -- also relocated (permanently)
384 http_error_301 = http_error_302
385
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000386 # Error 401 -- authentication required
387 # See this URL for a description of the basic authentication scheme:
388 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
389 def http_error_401(self, url, fp, errcode, errmsg, headers):
390 if headers.has_key('www-authenticate'):
391 stuff = headers['www-authenticate']
Guido van Rossum332e1441997-09-29 23:23:46 +0000392 import re
393 match = re.match(
394 '[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
395 if match:
396 scheme, realm = match.group()
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000397 if string.lower(scheme) == 'basic':
398 return self.retry_http_basic_auth(
399 url, realm)
400
401 def retry_http_basic_auth(self, url, realm):
402 host, selector = splithost(url)
403 i = string.find(host, '@') + 1
404 host = host[i:]
405 user, passwd = self.get_user_passwd(host, realm, i)
406 if not (user or passwd): return None
407 host = user + ':' + passwd + '@' + host
408 newurl = '//' + host + selector
409 return self.open_http(newurl)
410
411 def get_user_passwd(self, host, realm, clear_cache = 0):
412 key = realm + '@' + string.lower(host)
413 if self.auth_cache.has_key(key):
414 if clear_cache:
415 del self.auth_cache[key]
416 else:
417 return self.auth_cache[key]
418 user, passwd = self.prompt_user_passwd(host, realm)
419 if user or passwd: self.auth_cache[key] = (user, passwd)
420 return user, passwd
421
422 def prompt_user_passwd(self, host, realm):
423 # Override this in a GUI environment!
424 try:
425 user = raw_input("Enter username for %s at %s: " %
426 (realm, host))
427 self.echo_off()
428 try:
429 passwd = raw_input(
430 "Enter password for %s in %s at %s: " %
431 (user, realm, host))
432 finally:
433 self.echo_on()
434 return user, passwd
435 except KeyboardInterrupt:
436 return None, None
437
438 def echo_off(self):
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000439 os.system("stty -echo")
440
441 def echo_on(self):
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000442 print
443 os.system("stty echo")
444
445
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000446# Utility functions
447
448# Return the IP address of the magic hostname 'localhost'
449_localhost = None
450def localhost():
451 global _localhost
452 if not _localhost:
453 _localhost = socket.gethostbyname('localhost')
454 return _localhost
455
456# Return the IP address of the current host
457_thishost = None
458def thishost():
459 global _thishost
460 if not _thishost:
461 _thishost = socket.gethostbyname(socket.gethostname())
462 return _thishost
463
464# Return the set of errors raised by the FTP class
465_ftperrors = None
466def ftperrors():
467 global _ftperrors
468 if not _ftperrors:
469 import ftplib
Guido van Rossum2966b321997-06-06 17:44:07 +0000470 _ftperrors = ftplib.all_errors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000471 return _ftperrors
472
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000473# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000474_noheaders = None
475def noheaders():
476 global _noheaders
477 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000478 import mimetools
479 import StringIO
480 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000481 _noheaders.fp.close() # Recycle file descriptor
482 return _noheaders
483
484
485# Utility classes
486
487# Class used by open_ftp() for cache of open FTP connections
488class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000489 def __init__(self, user, passwd, host, port, dirs):
490 self.user = unquote(user or '')
491 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000492 self.host = host
493 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000494 self.dirs = []
495 for dir in dirs:
496 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000497 self.init()
498 def init(self):
499 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000500 self.busy = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000501 self.ftp = ftplib.FTP()
502 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000503 self.ftp.login(self.user, self.passwd)
504 for dir in self.dirs:
505 self.ftp.cwd(dir)
506 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000507 import ftplib
Guido van Rossumd4990041997-12-28 04:21:20 +0000508 self.endtransfer()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000509 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
510 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000511 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000512 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000513 except ftplib.all_errors:
514 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000515 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000516 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000517 if file and not isdir:
Guido van Rossumd4990041997-12-28 04:21:20 +0000518 # Use nlst to see if the file exists at all
519 try:
520 self.ftp.nlst(file)
521 except ftplib.error_perm, reason:
522 raise IOError, ('ftp error', reason), \
523 sys.exc_info()[2]
524 # Try to retrieve as a file
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000525 try:
526 cmd = 'RETR ' + file
527 conn = self.ftp.transfercmd(cmd)
528 except ftplib.error_perm, reason:
529 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000530 raise IOError, ('ftp error', reason), \
Guido van Rossum332e1441997-09-29 23:23:46 +0000531 sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000532 if not conn:
533 # Try a directory listing
534 if file: cmd = 'LIST ' + file
535 else: cmd = 'LIST'
536 conn = self.ftp.transfercmd(cmd)
Guido van Rossumd4990041997-12-28 04:21:20 +0000537 self.busy = 1
Guido van Rossumf668d171997-06-06 21:11:11 +0000538 return addclosehook(conn.makefile('rb'), self.endtransfer)
539 def endtransfer(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000540 if not self.busy:
541 return
542 self.busy = 0
Guido van Rossumf668d171997-06-06 21:11:11 +0000543 try:
544 self.ftp.voidresp()
545 except ftperrors():
546 pass
547 def close(self):
Guido van Rossumd4990041997-12-28 04:21:20 +0000548 self.endtransfer()
Guido van Rossumf668d171997-06-06 21:11:11 +0000549 try:
550 self.ftp.close()
551 except ftperrors():
552 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000553
554# Base class for addinfo and addclosehook
555class addbase:
556 def __init__(self, fp):
557 self.fp = fp
558 self.read = self.fp.read
559 self.readline = self.fp.readline
560 self.readlines = self.fp.readlines
561 self.fileno = self.fp.fileno
562 def __repr__(self):
563 return '<%s at %s whose fp = %s>' % (
564 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000565 def close(self):
566 self.read = None
567 self.readline = None
568 self.readlines = None
569 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000570 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000571 self.fp = None
572
573# Class to add a close hook to an open file
574class addclosehook(addbase):
575 def __init__(self, fp, closehook, *hookargs):
576 addbase.__init__(self, fp)
577 self.closehook = closehook
578 self.hookargs = hookargs
579 def close(self):
580 if self.closehook:
581 apply(self.closehook, self.hookargs)
582 self.closehook = None
583 self.hookargs = None
584 addbase.close(self)
585
586# class to add an info() method to an open file
587class addinfo(addbase):
588 def __init__(self, fp, headers):
589 addbase.__init__(self, fp)
590 self.headers = headers
591 def info(self):
592 return self.headers
593
Guido van Rossume6ad8911996-09-10 17:02:56 +0000594# class to add info() and geturl() methods to an open file
595class addinfourl(addbase):
596 def __init__(self, fp, headers, url):
597 addbase.__init__(self, fp)
598 self.headers = headers
599 self.url = url
600 def info(self):
601 return self.headers
602 def geturl(self):
603 return self.url
604
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000605
606# Utility to combine a URL with a base URL to form a new URL
607
608def basejoin(base, url):
609 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000610 if type:
611 # if url is complete (i.e., it contains a type), return it
612 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000613 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000614 type, basepath = splittype(base) # inherit type from base
615 if host:
616 # if url contains host, just inherit type
617 if type: return type + '://' + host + path
618 else:
619 # no type inherited, so url must have started with //
620 # just return it
621 return url
622 host, basepath = splithost(basepath) # inherit host
623 basepath, basetag = splittag(basepath) # remove extraneuous cruft
624 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000625 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000626 # non-absolute path name
627 if path[:1] in ('#', '?'):
628 # path is just a tag or query, attach to basepath
629 i = len(basepath)
630 else:
631 # else replace last component
632 i = string.rfind(basepath, '/')
633 if i < 0:
634 # basepath not absolute
635 if host:
636 # host present, make absolute
637 basepath = '/'
638 else:
639 # else keep non-absolute
640 basepath = ''
641 else:
642 # remove last file component
643 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000644 # Interpret ../ (important because of symlinks)
645 while basepath and path[:3] == '../':
646 path = path[3:]
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000647 i = string.rfind(basepath[:-1], '/')
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000648 if i > 0:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000649 basepath = basepath[:i+1]
650 elif i == 0:
651 basepath = '/'
652 break
653 else:
654 basepath = ''
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000655
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000656 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000657 if type and host: return type + '://' + host + path
658 elif type: return type + ':' + path
659 elif host: return '//' + host + path # don't know what this means
660 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000661
662
Guido van Rossum7c395db1994-07-04 22:14:49 +0000663# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000664# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000665# splittype('type:opaquestring') --> 'type', 'opaquestring'
666# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000667# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
668# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000669# splitport('host:port') --> 'host', 'port'
670# splitquery('/path?query') --> '/path', 'query'
671# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000672# splitattr('/path;attr1=value1;attr2=value2;...') ->
673# '/path', ['attr1=value1', 'attr2=value2', ...]
674# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000675# splitgophertype('/Xselector') --> 'X', 'selector'
676# unquote('abc%20def') -> 'abc def'
677# quote('abc def') -> 'abc%20def')
678
679def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000680 url = string.strip(url)
681 if url[:1] == '<' and url[-1:] == '>':
682 url = string.strip(url[1:-1])
683 if url[:4] == 'URL:': url = string.strip(url[4:])
684 return url
685
Guido van Rossum332e1441997-09-29 23:23:46 +0000686_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000687def splittype(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000688 global _typeprog
689 if _typeprog is None:
690 import re
691 _typeprog = re.compile('^([^/:]+):')
692
693 match = _typeprog.match(url)
694 if match:
695 scheme = match.group(1)
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000696 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000697 return None, url
698
Guido van Rossum332e1441997-09-29 23:23:46 +0000699_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000700def splithost(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000701 global _hostprog
702 if _hostprog is None:
703 import re
704 _hostprog = re.compile('^//([^/]+)(.*)$')
705
706 match = _hostprog.match(url)
707 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000708 return None, url
709
Guido van Rossum332e1441997-09-29 23:23:46 +0000710_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000711def splituser(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000712 global _userprog
713 if _userprog is None:
714 import re
715 _userprog = re.compile('^([^@]*)@(.*)$')
716
717 match = _userprog.match(host)
718 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000719 return None, host
720
Guido van Rossum332e1441997-09-29 23:23:46 +0000721_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000722def splitpasswd(user):
Guido van Rossum332e1441997-09-29 23:23:46 +0000723 global _passwdprog
724 if _passwdprog is None:
725 import re
726 _passwdprog = re.compile('^([^:]*):(.*)$')
727
Fred Drake654451d1997-10-14 13:30:57 +0000728 match = _passwdprog.match(user)
Guido van Rossum332e1441997-09-29 23:23:46 +0000729 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000730 return user, None
731
Guido van Rossum332e1441997-09-29 23:23:46 +0000732_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000733def splitport(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000734 global _portprog
735 if _portprog is None:
736 import re
737 _portprog = re.compile('^(.*):([0-9]+)$')
738
739 match = _portprog.match(host)
740 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000741 return host, None
742
Guido van Rossum53725a21996-06-13 19:12:35 +0000743# Split host and port, returning numeric port.
744# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000745# Return numerical port if a valid number are found after ':'.
746# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000747_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000748def splitnport(host, defport=-1):
Guido van Rossum332e1441997-09-29 23:23:46 +0000749 global _nportprog
750 if _nportprog is None:
751 import re
752 _nportprog = re.compile('^(.*):(.*)$')
753
754 match = _nportprog.match(host)
755 if match:
756 host, port = match.group(1, 2)
Guido van Rossum84a00a81996-06-17 17:11:40 +0000757 try:
758 if not port: raise string.atoi_error, "no digits"
759 nport = string.atoi(port)
760 except string.atoi_error:
761 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000762 return host, nport
763 return host, defport
764
Guido van Rossum332e1441997-09-29 23:23:46 +0000765_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000766def splitquery(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000767 global _queryprog
768 if _queryprog is None:
769 import re
770 _queryprog = re.compile('^(.*)\?([^?]*)$')
771
772 match = _queryprog.match(url)
773 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000774 return url, None
775
Guido van Rossum332e1441997-09-29 23:23:46 +0000776_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000777def splittag(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000778 global _tagprog
779 if _tagprog is None:
780 import re
781 _tagprog = re.compile('^(.*)#([^#]*)$')
782
783 match = _tagprog.match(url)
784 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000785 return url, None
786
Guido van Rossum7c395db1994-07-04 22:14:49 +0000787def splitattr(url):
788 words = string.splitfields(url, ';')
789 return words[0], words[1:]
790
Guido van Rossum332e1441997-09-29 23:23:46 +0000791_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000792def splitvalue(attr):
Guido van Rossum332e1441997-09-29 23:23:46 +0000793 global _valueprog
794 if _valueprog is None:
795 import re
796 _valueprog = re.compile('^([^=]*)=(.*)$')
797
798 match = _valueprog.match(attr)
799 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000800 return attr, None
801
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000802def splitgophertype(selector):
803 if selector[:1] == '/' and selector[1:2]:
804 return selector[1], selector[2:]
805 return None, selector
806
Guido van Rossum332e1441997-09-29 23:23:46 +0000807_quoteprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000808def unquote(s):
Guido van Rossum332e1441997-09-29 23:23:46 +0000809 global _quoteprog
810 if _quoteprog is None:
811 import re
812 _quoteprog = re.compile('%[0-9a-fA-F][0-9a-fA-F]')
813
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000814 i = 0
815 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000816 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000817 while 0 <= i < n:
Guido van Rossum332e1441997-09-29 23:23:46 +0000818 match = _quoteprog.search(s, i)
819 if not match:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000820 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000821 break
Guido van Rossum332e1441997-09-29 23:23:46 +0000822 j = match.start(0)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000823 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000824 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000825 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000826
Guido van Rossum0564e121996-12-13 14:47:36 +0000827def unquote_plus(s):
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 unquote(s)
832
Guido van Rossum3bb54481994-08-29 10:52:58 +0000833always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000834def quote(s, safe = '/'):
835 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000836 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000837 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000838 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000839 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000840 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000841 res.append('%%%02x' % ord(c))
842 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000843
Guido van Rossum0564e121996-12-13 14:47:36 +0000844def quote_plus(s, safe = '/'):
845 if ' ' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000846 # replace ' ' with '+'
847 s = string.join(string.split(s, ' '), '+')
Guido van Rossum0564e121996-12-13 14:47:36 +0000848 return quote(s, safe + '+')
849 else:
850 return quote(s, safe)
851
Guido van Rossum442e7201996-03-20 15:33:11 +0000852
853# Proxy handling
854def getproxies():
855 """Return a dictionary of protocol scheme -> proxy server URL mappings.
856
857 Scan the environment for variables named <scheme>_proxy;
858 this seems to be the standard convention. If you need a
859 different way, you can pass a proxies dictionary to the
860 [Fancy]URLopener constructor.
861
862 """
863 proxies = {}
864 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000865 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000866 if value and name[-6:] == '_proxy':
867 proxies[name[:-6]] = value
868 return proxies
869
870
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000871# Test and time quote() and unquote()
872def test1():
873 import time
874 s = ''
875 for i in range(256): s = s + chr(i)
876 s = s*4
877 t0 = time.time()
878 qs = quote(s)
879 uqs = unquote(qs)
880 t1 = time.time()
881 if uqs != s:
882 print 'Wrong!'
883 print `s`
884 print `qs`
885 print `uqs`
886 print round(t1 - t0, 3), 'sec'
887
888
889# Test program
890def test():
891 import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000892 args = sys.argv[1:]
893 if not args:
894 args = [
895 '/etc/passwd',
896 'file:/etc/passwd',
897 'file://localhost/etc/passwd',
Guido van Rossum332e1441997-09-29 23:23:46 +0000898 'ftp://ftp.python.org/etc/passwd',
899 'gopher://gopher.micro.umn.edu/1/',
900 'http://www.python.org/index.html',
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000901 ]
902 try:
903 for url in args:
904 print '-'*10, url, '-'*10
905 fn, h = urlretrieve(url)
906 print fn, h
907 if h:
908 print '======'
909 for k in h.keys(): print k + ':', h[k]
910 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000911 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000912 data = fp.read()
913 del fp
Guido van Rossum332e1441997-09-29 23:23:46 +0000914 if '\r' in data:
915 table = string.maketrans("", "")
916 data = string.translate(data, table, "\r")
917 print data
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000918 fn, h = None, None
919 print '-'*40
920 finally:
921 urlcleanup()
922
923# Run test program when run as a script
924if __name__ == '__main__':
Guido van Rossum332e1441997-09-29 23:23:46 +0000925 test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000926 test()