blob: a16529a5fc61a84f94cb1cbd3d28dcf226183d9d [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
500 self.ftp = ftplib.FTP()
501 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000502 self.ftp.login(self.user, self.passwd)
503 for dir in self.dirs:
504 self.ftp.cwd(dir)
505 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000506 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000507 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
508 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000509 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000510 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000511 except ftplib.all_errors:
512 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000513 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000514 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000515 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000516 try:
517 cmd = 'RETR ' + file
518 conn = self.ftp.transfercmd(cmd)
519 except ftplib.error_perm, reason:
520 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000521 raise IOError, ('ftp error', reason), \
Guido van Rossum332e1441997-09-29 23:23:46 +0000522 sys.exc_info()[2]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000523 if not conn:
524 # Try a directory listing
525 if file: cmd = 'LIST ' + file
526 else: cmd = 'LIST'
527 conn = self.ftp.transfercmd(cmd)
Guido van Rossumf668d171997-06-06 21:11:11 +0000528 return addclosehook(conn.makefile('rb'), self.endtransfer)
529 def endtransfer(self):
530 try:
531 self.ftp.voidresp()
532 except ftperrors():
533 pass
534 def close(self):
535 try:
536 self.ftp.close()
537 except ftperrors():
538 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000539
540# Base class for addinfo and addclosehook
541class addbase:
542 def __init__(self, fp):
543 self.fp = fp
544 self.read = self.fp.read
545 self.readline = self.fp.readline
546 self.readlines = self.fp.readlines
547 self.fileno = self.fp.fileno
548 def __repr__(self):
549 return '<%s at %s whose fp = %s>' % (
550 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000551 def close(self):
552 self.read = None
553 self.readline = None
554 self.readlines = None
555 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000556 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000557 self.fp = None
558
559# Class to add a close hook to an open file
560class addclosehook(addbase):
561 def __init__(self, fp, closehook, *hookargs):
562 addbase.__init__(self, fp)
563 self.closehook = closehook
564 self.hookargs = hookargs
565 def close(self):
566 if self.closehook:
567 apply(self.closehook, self.hookargs)
568 self.closehook = None
569 self.hookargs = None
570 addbase.close(self)
571
572# class to add an info() method to an open file
573class addinfo(addbase):
574 def __init__(self, fp, headers):
575 addbase.__init__(self, fp)
576 self.headers = headers
577 def info(self):
578 return self.headers
579
Guido van Rossume6ad8911996-09-10 17:02:56 +0000580# class to add info() and geturl() methods to an open file
581class addinfourl(addbase):
582 def __init__(self, fp, headers, url):
583 addbase.__init__(self, fp)
584 self.headers = headers
585 self.url = url
586 def info(self):
587 return self.headers
588 def geturl(self):
589 return self.url
590
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000591
592# Utility to combine a URL with a base URL to form a new URL
593
594def basejoin(base, url):
595 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000596 if type:
597 # if url is complete (i.e., it contains a type), return it
598 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000599 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000600 type, basepath = splittype(base) # inherit type from base
601 if host:
602 # if url contains host, just inherit type
603 if type: return type + '://' + host + path
604 else:
605 # no type inherited, so url must have started with //
606 # just return it
607 return url
608 host, basepath = splithost(basepath) # inherit host
609 basepath, basetag = splittag(basepath) # remove extraneuous cruft
610 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000611 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000612 # non-absolute path name
613 if path[:1] in ('#', '?'):
614 # path is just a tag or query, attach to basepath
615 i = len(basepath)
616 else:
617 # else replace last component
618 i = string.rfind(basepath, '/')
619 if i < 0:
620 # basepath not absolute
621 if host:
622 # host present, make absolute
623 basepath = '/'
624 else:
625 # else keep non-absolute
626 basepath = ''
627 else:
628 # remove last file component
629 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000630 # Interpret ../ (important because of symlinks)
631 while basepath and path[:3] == '../':
632 path = path[3:]
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000633 i = string.rfind(basepath[:-1], '/')
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000634 if i > 0:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000635 basepath = basepath[:i+1]
636 elif i == 0:
637 basepath = '/'
638 break
639 else:
640 basepath = ''
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000641
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000642 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000643 if type and host: return type + '://' + host + path
644 elif type: return type + ':' + path
645 elif host: return '//' + host + path # don't know what this means
646 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000647
648
Guido van Rossum7c395db1994-07-04 22:14:49 +0000649# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000650# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000651# splittype('type:opaquestring') --> 'type', 'opaquestring'
652# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000653# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
654# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000655# splitport('host:port') --> 'host', 'port'
656# splitquery('/path?query') --> '/path', 'query'
657# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000658# splitattr('/path;attr1=value1;attr2=value2;...') ->
659# '/path', ['attr1=value1', 'attr2=value2', ...]
660# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000661# splitgophertype('/Xselector') --> 'X', 'selector'
662# unquote('abc%20def') -> 'abc def'
663# quote('abc def') -> 'abc%20def')
664
665def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000666 url = string.strip(url)
667 if url[:1] == '<' and url[-1:] == '>':
668 url = string.strip(url[1:-1])
669 if url[:4] == 'URL:': url = string.strip(url[4:])
670 return url
671
Guido van Rossum332e1441997-09-29 23:23:46 +0000672_typeprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000673def splittype(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000674 global _typeprog
675 if _typeprog is None:
676 import re
677 _typeprog = re.compile('^([^/:]+):')
678
679 match = _typeprog.match(url)
680 if match:
681 scheme = match.group(1)
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000682 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000683 return None, url
684
Guido van Rossum332e1441997-09-29 23:23:46 +0000685_hostprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000686def splithost(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000687 global _hostprog
688 if _hostprog is None:
689 import re
690 _hostprog = re.compile('^//([^/]+)(.*)$')
691
692 match = _hostprog.match(url)
693 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000694 return None, url
695
Guido van Rossum332e1441997-09-29 23:23:46 +0000696_userprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000697def splituser(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000698 global _userprog
699 if _userprog is None:
700 import re
701 _userprog = re.compile('^([^@]*)@(.*)$')
702
703 match = _userprog.match(host)
704 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000705 return None, host
706
Guido van Rossum332e1441997-09-29 23:23:46 +0000707_passwdprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000708def splitpasswd(user):
Guido van Rossum332e1441997-09-29 23:23:46 +0000709 global _passwdprog
710 if _passwdprog is None:
711 import re
712 _passwdprog = re.compile('^([^:]*):(.*)$')
713
Fred Drake654451d1997-10-14 13:30:57 +0000714 match = _passwdprog.match(user)
Guido van Rossum332e1441997-09-29 23:23:46 +0000715 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000716 return user, None
717
Guido van Rossum332e1441997-09-29 23:23:46 +0000718_portprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000719def splitport(host):
Guido van Rossum332e1441997-09-29 23:23:46 +0000720 global _portprog
721 if _portprog is None:
722 import re
723 _portprog = re.compile('^(.*):([0-9]+)$')
724
725 match = _portprog.match(host)
726 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000727 return host, None
728
Guido van Rossum53725a21996-06-13 19:12:35 +0000729# Split host and port, returning numeric port.
730# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000731# Return numerical port if a valid number are found after ':'.
732# Return None if ':' but not a valid number.
Guido van Rossum332e1441997-09-29 23:23:46 +0000733_nportprog = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000734def splitnport(host, defport=-1):
Guido van Rossum332e1441997-09-29 23:23:46 +0000735 global _nportprog
736 if _nportprog is None:
737 import re
738 _nportprog = re.compile('^(.*):(.*)$')
739
740 match = _nportprog.match(host)
741 if match:
742 host, port = match.group(1, 2)
Guido van Rossum84a00a81996-06-17 17:11:40 +0000743 try:
744 if not port: raise string.atoi_error, "no digits"
745 nport = string.atoi(port)
746 except string.atoi_error:
747 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000748 return host, nport
749 return host, defport
750
Guido van Rossum332e1441997-09-29 23:23:46 +0000751_queryprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000752def splitquery(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000753 global _queryprog
754 if _queryprog is None:
755 import re
756 _queryprog = re.compile('^(.*)\?([^?]*)$')
757
758 match = _queryprog.match(url)
759 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000760 return url, None
761
Guido van Rossum332e1441997-09-29 23:23:46 +0000762_tagprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000763def splittag(url):
Guido van Rossum332e1441997-09-29 23:23:46 +0000764 global _tagprog
765 if _tagprog is None:
766 import re
767 _tagprog = re.compile('^(.*)#([^#]*)$')
768
769 match = _tagprog.match(url)
770 if match: return match.group(1, 2)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000771 return url, None
772
Guido van Rossum7c395db1994-07-04 22:14:49 +0000773def splitattr(url):
774 words = string.splitfields(url, ';')
775 return words[0], words[1:]
776
Guido van Rossum332e1441997-09-29 23:23:46 +0000777_valueprog = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000778def splitvalue(attr):
Guido van Rossum332e1441997-09-29 23:23:46 +0000779 global _valueprog
780 if _valueprog is None:
781 import re
782 _valueprog = re.compile('^([^=]*)=(.*)$')
783
784 match = _valueprog.match(attr)
785 if match: return match.group(1, 2)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000786 return attr, None
787
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000788def splitgophertype(selector):
789 if selector[:1] == '/' and selector[1:2]:
790 return selector[1], selector[2:]
791 return None, selector
792
Guido van Rossum332e1441997-09-29 23:23:46 +0000793_quoteprog = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000794def unquote(s):
Guido van Rossum332e1441997-09-29 23:23:46 +0000795 global _quoteprog
796 if _quoteprog is None:
797 import re
798 _quoteprog = re.compile('%[0-9a-fA-F][0-9a-fA-F]')
799
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000800 i = 0
801 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000802 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000803 while 0 <= i < n:
Guido van Rossum332e1441997-09-29 23:23:46 +0000804 match = _quoteprog.search(s, i)
805 if not match:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000806 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000807 break
Guido van Rossum332e1441997-09-29 23:23:46 +0000808 j = match.start(0)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000809 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000810 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000811 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000812
Guido van Rossum0564e121996-12-13 14:47:36 +0000813def unquote_plus(s):
814 if '+' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000815 # replace '+' with ' '
816 s = string.join(string.split(s, '+'), ' ')
Guido van Rossum0564e121996-12-13 14:47:36 +0000817 return unquote(s)
818
Guido van Rossum3bb54481994-08-29 10:52:58 +0000819always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000820def quote(s, safe = '/'):
821 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000822 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000823 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000824 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000825 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000826 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000827 res.append('%%%02x' % ord(c))
828 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000829
Guido van Rossum0564e121996-12-13 14:47:36 +0000830def quote_plus(s, safe = '/'):
831 if ' ' in s:
Guido van Rossum332e1441997-09-29 23:23:46 +0000832 # replace ' ' with '+'
833 s = string.join(string.split(s, ' '), '+')
Guido van Rossum0564e121996-12-13 14:47:36 +0000834 return quote(s, safe + '+')
835 else:
836 return quote(s, safe)
837
Guido van Rossum442e7201996-03-20 15:33:11 +0000838
839# Proxy handling
840def getproxies():
841 """Return a dictionary of protocol scheme -> proxy server URL mappings.
842
843 Scan the environment for variables named <scheme>_proxy;
844 this seems to be the standard convention. If you need a
845 different way, you can pass a proxies dictionary to the
846 [Fancy]URLopener constructor.
847
848 """
849 proxies = {}
850 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000851 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000852 if value and name[-6:] == '_proxy':
853 proxies[name[:-6]] = value
854 return proxies
855
856
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000857# Test and time quote() and unquote()
858def test1():
859 import time
860 s = ''
861 for i in range(256): s = s + chr(i)
862 s = s*4
863 t0 = time.time()
864 qs = quote(s)
865 uqs = unquote(qs)
866 t1 = time.time()
867 if uqs != s:
868 print 'Wrong!'
869 print `s`
870 print `qs`
871 print `uqs`
872 print round(t1 - t0, 3), 'sec'
873
874
875# Test program
876def test():
877 import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000878 args = sys.argv[1:]
879 if not args:
880 args = [
881 '/etc/passwd',
882 'file:/etc/passwd',
883 'file://localhost/etc/passwd',
Guido van Rossum332e1441997-09-29 23:23:46 +0000884 'ftp://ftp.python.org/etc/passwd',
885 'gopher://gopher.micro.umn.edu/1/',
886 'http://www.python.org/index.html',
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000887 ]
888 try:
889 for url in args:
890 print '-'*10, url, '-'*10
891 fn, h = urlretrieve(url)
892 print fn, h
893 if h:
894 print '======'
895 for k in h.keys(): print k + ':', h[k]
896 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000897 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000898 data = fp.read()
899 del fp
Guido van Rossum332e1441997-09-29 23:23:46 +0000900 if '\r' in data:
901 table = string.maketrans("", "")
902 data = string.translate(data, table, "\r")
903 print data
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000904 fn, h = None, None
905 print '-'*40
906 finally:
907 urlcleanup()
908
909# Run test program when run as a script
910if __name__ == '__main__':
Guido van Rossum332e1441997-09-29 23:23:46 +0000911 test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000912 test()