blob: 6922f22936108fa4c8ccaddae3aaa758b55dadea [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
26import regex
Jack Jansendc3e3f61995-12-15 13:22:13 +000027import os
Guido van Rossum3c8484e1996-11-20 22:02:24 +000028import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000029
30
Guido van Rossumf668d171997-06-06 21:11:11 +000031__version__ = '1.7'
32
33MAXFTPCACHE = 10 # Trim the ftp cache beyond this size
Guido van Rossum6cb15a01995-06-22 19:00:13 +000034
Jack Jansendc3e3f61995-12-15 13:22:13 +000035# Helper for non-unix systems
36if os.name == 'mac':
Guido van Rossum71ac9451996-03-21 16:31:41 +000037 from macurl2path import url2pathname, pathname2url
Guido van Rossum2281d351996-06-26 19:47:37 +000038elif os.name == 'nt':
39 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000040else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000041 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000042 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000043 def pathname2url(pathname):
44 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000045
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000046# This really consists of two pieces:
47# (1) a class which handles opening of all sorts of URLs
48# (plus assorted utilities etc.)
49# (2) a set of functions for parsing URLs
50# XXX Should these be separated out into different modules?
51
52
53# Shortcut for basic usage
54_urlopener = None
Guido van Rossumbd013741996-12-10 16:00:28 +000055def urlopen(url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000056 global _urlopener
57 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000058 _urlopener = FancyURLopener()
Guido van Rossumbd013741996-12-10 16:00:28 +000059 if data is None:
60 return _urlopener.open(url)
61 else:
62 return _urlopener.open(url, data)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000063def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000064 global _urlopener
65 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000066 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000067 if filename:
68 return _urlopener.retrieve(url, filename)
69 else:
70 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000071def urlcleanup():
72 if _urlopener:
73 _urlopener.cleanup()
74
75
76# Class to open URLs.
77# This is a class rather than just a subroutine because we may need
78# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000079# Note -- this is a base class for those who don't want the
80# automatic handling of errors type 302 (relocated) and 401
81# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000082ftpcache = {}
83class URLopener:
84
Guido van Rossum2b3fd761997-09-03 22:36:15 +000085 __tempfiles = []
Guido van Rossum29e77811996-11-27 19:39:58 +000086
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000087 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000088 def __init__(self, proxies=None):
89 if proxies is None:
90 proxies = getproxies()
91 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 Rossum7aeb4b91994-08-23 13:32:20 +000094 self.tempcache = None
95 # Undocumented feature: if you assign {} to tempcache,
96 # it is used to cache files retrieved with
97 # self.retrieve(). This is not enabled by default
98 # since it does not work for changing documents (and I
99 # haven't got the logic to check expiration headers
100 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000101 self.ftpcache = ftpcache
102 # Undocumented feature: you can use a different
103 # ftp cache by assigning to the .ftpcache member;
104 # in case you want logically independent URL openers
105
106 def __del__(self):
107 self.close()
108
109 def close(self):
110 self.cleanup()
111
112 def cleanup(self):
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000113 if self.__tempfiles:
Guido van Rossumd23d9401997-01-30 15:54:58 +0000114 import os
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000115 for file in self.__tempfiles:
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000116 try:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000117 os.unlink(file)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000118 except os.error:
119 pass
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000120 URLopener.__tempfiles = []
121 self.tempcache = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000122
123 # Add a header to be used by the HTTP interface only
124 # e.g. u.addheader('Accept', 'sound/basic')
125 def addheader(self, *args):
126 self.addheaders.append(args)
127
128 # External interface
129 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumbd013741996-12-10 16:00:28 +0000130 def open(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000131 fullurl = unwrap(fullurl)
132 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000133 if not type: type = 'file'
Guido van Rossume6ad8911996-09-10 17:02:56 +0000134 self.openedurl = '%s:%s' % (type, url)
Guido van Rossum442e7201996-03-20 15:33:11 +0000135 if self.proxies.has_key(type):
136 proxy = self.proxies[type]
137 type, proxy = splittype(proxy)
138 host, selector = splithost(proxy)
139 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000140 name = 'open_' + type
141 if '-' in name:
142 import regsub
143 name = regsub.gsub('-', '_', name)
144 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000145 if data is None:
146 return self.open_unknown(fullurl)
147 else:
148 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000149 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000150 if data is None:
151 return getattr(self, name)(url)
152 else:
153 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000154 except socket.error, msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000155 raise IOError, ('socket error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000156
Guido van Rossumca445401995-08-29 19:19:12 +0000157 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000158 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000159 type, url = splittype(fullurl)
160 raise IOError, ('url error', 'unknown url type', type)
161
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000162 # External interface
163 # retrieve(url) returns (filename, None) for a local object
164 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000165 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000166 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000167 return self.tempcache[url]
168 url1 = unwrap(url)
Guido van Rossum5b1b33c1996-10-22 13:28:37 +0000169 self.openedurl = url1
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000170 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000171 self.tempcache[url] = self.tempcache[url1]
172 return self.tempcache[url1]
173 type, url1 = splittype(url1)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000174 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000175 try:
176 fp = self.open_local_file(url1)
177 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000178 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000179 except IOError, msg:
180 pass
181 fp = self.open(url)
182 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000183 if not filename:
184 import tempfile
185 filename = tempfile.mktemp()
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000186 self.__tempfiles.append(filename)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000187 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000188 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000189 self.tempcache[url] = result
Guido van Rossumc511aee1997-04-11 19:01:48 +0000190 tfp = open(filename, 'wb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000191 bs = 1024*8
192 block = fp.read(bs)
193 while block:
194 tfp.write(block)
195 block = fp.read(bs)
Guido van Rossumab0abdc1997-08-26 19:06:40 +0000196 fp.close()
197 tfp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000198 del fp
199 del tfp
200 return result
201
202 # Each method named open_<type> knows how to open that type of URL
203
204 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000205 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000206 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000207 if type(url) is type(""):
208 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000209 user_passwd, host = splituser(host)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000210 realhost = host
Guido van Rossum442e7201996-03-20 15:33:11 +0000211 else:
212 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000213 urltype, rest = splittype(selector)
Guido van Rossumfd795661997-04-02 05:46:35 +0000214 user_passwd = None
Guido van Rossumc24751b1997-06-03 14:34:19 +0000215 if string.lower(urltype) != 'http':
216 realhost = None
217 else:
Guido van Rossum78c96371996-08-26 18:09:59 +0000218 realhost, rest = splithost(rest)
219 user_passwd, realhost = splituser(realhost)
220 if user_passwd:
221 selector = "%s://%s%s" % (urltype,
222 realhost, rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000223 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000224 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000225 if user_passwd:
226 import base64
227 auth = string.strip(base64.encodestring(user_passwd))
228 else:
229 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000230 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000231 if data is not None:
232 h.putrequest('POST', selector)
233 h.putheader('Content-type',
234 'application/x-www-form-urlencoded')
235 h.putheader('Content-length', '%d' % len(data))
236 else:
237 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000238 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossumc24751b1997-06-03 14:34:19 +0000239 if realhost: h.putheader('Host', realhost)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000240 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000241 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000242 if data is not None:
243 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000244 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000245 fp = h.getfile()
246 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000247 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000248 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000249 return self.http_error(url,
250 fp, errcode, errmsg, headers)
251
252 # Handle http errors.
253 # Derived class can override this, or provide specific handlers
254 # named http_error_DDD where DDD is the 3-digit error code
255 def http_error(self, url, fp, errcode, errmsg, headers):
256 # First check if there's a specific handler for this error
257 name = 'http_error_%d' % errcode
258 if hasattr(self, name):
259 method = getattr(self, name)
260 result = method(url, fp, errcode, errmsg, headers)
261 if result: return result
262 return self.http_error_default(
263 url, fp, errcode, errmsg, headers)
264
265 # Default http error handler: close the connection and raises IOError
266 def http_error_default(self, url, fp, errcode, errmsg, headers):
267 void = fp.read()
268 fp.close()
269 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000270
271 # Use Gopher protocol
272 def open_gopher(self, url):
273 import gopherlib
274 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000275 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000276 type, selector = splitgophertype(selector)
277 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000278 selector = unquote(selector)
279 if query:
280 query = unquote(query)
281 fp = gopherlib.send_query(selector, query, host)
282 else:
283 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000284 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000285
286 # Use local file or FTP depending on form of URL
287 def open_file(self, url):
Guido van Rossumb6784dc1997-08-20 23:34:01 +0000288 if url[:2] == '//' and url[2:3] != '/':
289 return self.open_ftp(url)
290 else:
291 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000292
293 # Use local file
294 def open_local_file(self, url):
295 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000296 if not host:
Guido van Rossum2966b321997-06-06 17:44:07 +0000297 return addinfourl(
298 open(url2pathname(file), 'rb'),
299 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000300 host, port = splitport(host)
301 if not port and socket.gethostbyname(host) in (
302 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000303 file = unquote(file)
Guido van Rossum2966b321997-06-06 17:44:07 +0000304 return addinfourl(
305 open(url2pathname(file), 'rb'),
306 noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000307 raise IOError, ('local file error', 'not on local host')
308
309 # Use FTP protocol
310 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000311 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000312 if not host: raise IOError, ('ftp error', 'no host given')
313 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000314 user, host = splituser(host)
315 if user: user, passwd = splitpasswd(user)
316 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000317 host = socket.gethostbyname(host)
318 if not port:
319 import ftplib
320 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000321 path, attrs = splitattr(path)
322 dirs = string.splitfields(path, '/')
323 dirs, file = dirs[:-1], dirs[-1]
324 if dirs and not dirs[0]: dirs = dirs[1:]
325 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossumf668d171997-06-06 21:11:11 +0000326 if len(self.ftpcache) > MAXFTPCACHE:
327 # Prune the cache, rather arbitrarily
328 for k in self.ftpcache.keys():
329 if k != key:
330 v = self.ftpcache[k]
331 del self.ftpcache[k]
332 v.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000333 try:
334 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000335 self.ftpcache[key] = \
336 ftpwrapper(user, passwd,
337 host, port, dirs)
338 if not file: type = 'D'
339 else: type = 'I'
340 for attr in attrs:
341 attr, value = splitvalue(attr)
342 if string.lower(attr) == 'type' and \
343 value in ('a', 'A', 'i', 'I', 'd', 'D'):
344 type = string.upper(value)
Guido van Rossum2966b321997-06-06 17:44:07 +0000345 return addinfourl(
346 self.ftpcache[key].retrfile(file, type),
347 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000348 except ftperrors(), msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000349 raise IOError, ('ftp error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000350
351
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000352# Derived class with handlers for errors we can handle (perhaps)
353class FancyURLopener(URLopener):
354
355 def __init__(self, *args):
356 apply(URLopener.__init__, (self,) + args)
357 self.auth_cache = {}
358
359 # Default error handling -- don't raise an exception
360 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000361 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000362
Guido van Rossume6ad8911996-09-10 17:02:56 +0000363 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000364 def http_error_302(self, url, fp, errcode, errmsg, headers):
365 # XXX The server can force infinite recursion here!
366 if headers.has_key('location'):
367 newurl = headers['location']
368 elif headers.has_key('uri'):
369 newurl = headers['uri']
370 else:
371 return
372 void = fp.read()
373 fp.close()
374 return self.open(newurl)
375
Guido van Rossume6ad8911996-09-10 17:02:56 +0000376 # Error 301 -- also relocated (permanently)
377 http_error_301 = http_error_302
378
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000379 # Error 401 -- authentication required
380 # See this URL for a description of the basic authentication scheme:
381 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
382 def http_error_401(self, url, fp, errcode, errmsg, headers):
383 if headers.has_key('www-authenticate'):
384 stuff = headers['www-authenticate']
385 p = regex.compile(
386 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
387 if p.match(stuff) >= 0:
388 scheme, realm = p.group(1, 2)
389 if string.lower(scheme) == 'basic':
390 return self.retry_http_basic_auth(
391 url, realm)
392
393 def retry_http_basic_auth(self, url, realm):
394 host, selector = splithost(url)
395 i = string.find(host, '@') + 1
396 host = host[i:]
397 user, passwd = self.get_user_passwd(host, realm, i)
398 if not (user or passwd): return None
399 host = user + ':' + passwd + '@' + host
400 newurl = '//' + host + selector
401 return self.open_http(newurl)
402
403 def get_user_passwd(self, host, realm, clear_cache = 0):
404 key = realm + '@' + string.lower(host)
405 if self.auth_cache.has_key(key):
406 if clear_cache:
407 del self.auth_cache[key]
408 else:
409 return self.auth_cache[key]
410 user, passwd = self.prompt_user_passwd(host, realm)
411 if user or passwd: self.auth_cache[key] = (user, passwd)
412 return user, passwd
413
414 def prompt_user_passwd(self, host, realm):
415 # Override this in a GUI environment!
416 try:
417 user = raw_input("Enter username for %s at %s: " %
418 (realm, host))
419 self.echo_off()
420 try:
421 passwd = raw_input(
422 "Enter password for %s in %s at %s: " %
423 (user, realm, host))
424 finally:
425 self.echo_on()
426 return user, passwd
427 except KeyboardInterrupt:
428 return None, None
429
430 def echo_off(self):
431 import os
432 os.system("stty -echo")
433
434 def echo_on(self):
435 import os
436 print
437 os.system("stty echo")
438
439
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000440# Utility functions
441
442# Return the IP address of the magic hostname 'localhost'
443_localhost = None
444def localhost():
445 global _localhost
446 if not _localhost:
447 _localhost = socket.gethostbyname('localhost')
448 return _localhost
449
450# Return the IP address of the current host
451_thishost = None
452def thishost():
453 global _thishost
454 if not _thishost:
455 _thishost = socket.gethostbyname(socket.gethostname())
456 return _thishost
457
458# Return the set of errors raised by the FTP class
459_ftperrors = None
460def ftperrors():
461 global _ftperrors
462 if not _ftperrors:
463 import ftplib
Guido van Rossum2966b321997-06-06 17:44:07 +0000464 _ftperrors = ftplib.all_errors
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000465 return _ftperrors
466
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000467# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000468_noheaders = None
469def noheaders():
470 global _noheaders
471 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000472 import mimetools
473 import StringIO
474 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000475 _noheaders.fp.close() # Recycle file descriptor
476 return _noheaders
477
478
479# Utility classes
480
481# Class used by open_ftp() for cache of open FTP connections
482class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000483 def __init__(self, user, passwd, host, port, dirs):
484 self.user = unquote(user or '')
485 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000486 self.host = host
487 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000488 self.dirs = []
489 for dir in dirs:
490 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000491 self.init()
492 def init(self):
493 import ftplib
494 self.ftp = ftplib.FTP()
495 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000496 self.ftp.login(self.user, self.passwd)
497 for dir in self.dirs:
498 self.ftp.cwd(dir)
499 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000500 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000501 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
502 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000503 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000504 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000505 except ftplib.all_errors:
506 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000507 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000508 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000509 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000510 try:
511 cmd = 'RETR ' + file
512 conn = self.ftp.transfercmd(cmd)
513 except ftplib.error_perm, reason:
514 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000515 raise IOError, ('ftp error', reason), \
516 sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000517 if not conn:
518 # Try a directory listing
519 if file: cmd = 'LIST ' + file
520 else: cmd = 'LIST'
521 conn = self.ftp.transfercmd(cmd)
Guido van Rossumf668d171997-06-06 21:11:11 +0000522 return addclosehook(conn.makefile('rb'), self.endtransfer)
523 def endtransfer(self):
524 try:
525 self.ftp.voidresp()
526 except ftperrors():
527 pass
528 def close(self):
529 try:
530 self.ftp.close()
531 except ftperrors():
532 pass
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000533
534# Base class for addinfo and addclosehook
535class addbase:
536 def __init__(self, fp):
537 self.fp = fp
538 self.read = self.fp.read
539 self.readline = self.fp.readline
540 self.readlines = self.fp.readlines
541 self.fileno = self.fp.fileno
542 def __repr__(self):
543 return '<%s at %s whose fp = %s>' % (
544 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000545 def close(self):
546 self.read = None
547 self.readline = None
548 self.readlines = None
549 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000550 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000551 self.fp = None
552
553# Class to add a close hook to an open file
554class addclosehook(addbase):
555 def __init__(self, fp, closehook, *hookargs):
556 addbase.__init__(self, fp)
557 self.closehook = closehook
558 self.hookargs = hookargs
559 def close(self):
560 if self.closehook:
561 apply(self.closehook, self.hookargs)
562 self.closehook = None
563 self.hookargs = None
564 addbase.close(self)
565
566# class to add an info() method to an open file
567class addinfo(addbase):
568 def __init__(self, fp, headers):
569 addbase.__init__(self, fp)
570 self.headers = headers
571 def info(self):
572 return self.headers
573
Guido van Rossume6ad8911996-09-10 17:02:56 +0000574# class to add info() and geturl() methods to an open file
575class addinfourl(addbase):
576 def __init__(self, fp, headers, url):
577 addbase.__init__(self, fp)
578 self.headers = headers
579 self.url = url
580 def info(self):
581 return self.headers
582 def geturl(self):
583 return self.url
584
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000585
586# Utility to combine a URL with a base URL to form a new URL
587
588def basejoin(base, url):
589 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000590 if type:
591 # if url is complete (i.e., it contains a type), return it
592 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000593 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000594 type, basepath = splittype(base) # inherit type from base
595 if host:
596 # if url contains host, just inherit type
597 if type: return type + '://' + host + path
598 else:
599 # no type inherited, so url must have started with //
600 # just return it
601 return url
602 host, basepath = splithost(basepath) # inherit host
603 basepath, basetag = splittag(basepath) # remove extraneuous cruft
604 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000605 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000606 # non-absolute path name
607 if path[:1] in ('#', '?'):
608 # path is just a tag or query, attach to basepath
609 i = len(basepath)
610 else:
611 # else replace last component
612 i = string.rfind(basepath, '/')
613 if i < 0:
614 # basepath not absolute
615 if host:
616 # host present, make absolute
617 basepath = '/'
618 else:
619 # else keep non-absolute
620 basepath = ''
621 else:
622 # remove last file component
623 basepath = basepath[:i+1]
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000624 # Interpret ../ (important because of symlinks)
625 while basepath and path[:3] == '../':
626 path = path[3:]
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000627 i = string.rfind(basepath[:-1], '/')
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000628 if i > 0:
Guido van Rossum2b3fd761997-09-03 22:36:15 +0000629 basepath = basepath[:i+1]
630 elif i == 0:
631 basepath = '/'
632 break
633 else:
634 basepath = ''
Guido van Rossum54a1d0b1997-04-11 19:09:51 +0000635
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000636 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000637 if type and host: return type + '://' + host + path
638 elif type: return type + ':' + path
639 elif host: return '//' + host + path # don't know what this means
640 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000641
642
Guido van Rossum7c395db1994-07-04 22:14:49 +0000643# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000644# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000645# splittype('type:opaquestring') --> 'type', 'opaquestring'
646# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000647# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
648# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000649# splitport('host:port') --> 'host', 'port'
650# splitquery('/path?query') --> '/path', 'query'
651# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000652# splitattr('/path;attr1=value1;attr2=value2;...') ->
653# '/path', ['attr1=value1', 'attr2=value2', ...]
654# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000655# splitgophertype('/Xselector') --> 'X', 'selector'
656# unquote('abc%20def') -> 'abc def'
657# quote('abc def') -> 'abc%20def')
658
659def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000660 url = string.strip(url)
661 if url[:1] == '<' and url[-1:] == '>':
662 url = string.strip(url[1:-1])
663 if url[:4] == 'URL:': url = string.strip(url[4:])
664 return url
665
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000666_typeprog = regex.compile('^\([^/:]+\):')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000667def splittype(url):
Guido van Rossumab0d1af1997-04-16 15:17:06 +0000668 if _typeprog.match(url) >= 0:
669 scheme = _typeprog.group(1)
670 return scheme, url[len(scheme) + 1:]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000671 return None, url
672
673_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
674def splithost(url):
675 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
676 return None, url
677
Guido van Rossum7c395db1994-07-04 22:14:49 +0000678_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
679def splituser(host):
680 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
681 return None, host
682
683_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
684def splitpasswd(user):
685 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
686 return user, None
687
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000688_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
689def splitport(host):
690 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
691 return host, None
692
Guido van Rossum53725a21996-06-13 19:12:35 +0000693# Split host and port, returning numeric port.
694# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000695# Return numerical port if a valid number are found after ':'.
696# Return None if ':' but not a valid number.
697_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000698def splitnport(host, defport=-1):
699 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000700 host, port = _nportprog.group(1, 2)
701 try:
702 if not port: raise string.atoi_error, "no digits"
703 nport = string.atoi(port)
704 except string.atoi_error:
705 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000706 return host, nport
707 return host, defport
708
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000709_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
710def splitquery(url):
711 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
712 return url, None
713
714_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
715def splittag(url):
716 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
717 return url, None
718
Guido van Rossum7c395db1994-07-04 22:14:49 +0000719def splitattr(url):
720 words = string.splitfields(url, ';')
721 return words[0], words[1:]
722
723_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
724def splitvalue(attr):
725 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
726 return attr, None
727
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000728def splitgophertype(selector):
729 if selector[:1] == '/' and selector[1:2]:
730 return selector[1], selector[2:]
731 return None, selector
732
733_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
734def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000735 i = 0
736 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000737 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000738 while 0 <= i < n:
739 j = _quoteprog.search(s, i)
740 if j < 0:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000741 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000742 break
Guido van Rossumf8abb381996-08-26 15:56:12 +0000743 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000744 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000745 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000746
Guido van Rossum0564e121996-12-13 14:47:36 +0000747def unquote_plus(s):
748 if '+' in s:
749 import regsub
750 s = regsub.gsub('+', ' ', s)
751 return unquote(s)
752
Guido van Rossum3bb54481994-08-29 10:52:58 +0000753always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000754def quote(s, safe = '/'):
755 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000756 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000757 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000758 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000759 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000760 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000761 res.append('%%%02x' % ord(c))
762 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000763
Guido van Rossum0564e121996-12-13 14:47:36 +0000764def quote_plus(s, safe = '/'):
765 if ' ' in s:
766 import regsub
767 s = regsub.gsub(' ', '+', s)
768 return quote(s, safe + '+')
769 else:
770 return quote(s, safe)
771
Guido van Rossum442e7201996-03-20 15:33:11 +0000772
773# Proxy handling
774def getproxies():
775 """Return a dictionary of protocol scheme -> proxy server URL mappings.
776
777 Scan the environment for variables named <scheme>_proxy;
778 this seems to be the standard convention. If you need a
779 different way, you can pass a proxies dictionary to the
780 [Fancy]URLopener constructor.
781
782 """
783 proxies = {}
784 for name, value in os.environ.items():
Guido van Rossum1aec3f01997-05-28 15:37:19 +0000785 name = string.lower(name)
Guido van Rossum442e7201996-03-20 15:33:11 +0000786 if value and name[-6:] == '_proxy':
787 proxies[name[:-6]] = value
788 return proxies
789
790
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000791# Test and time quote() and unquote()
792def test1():
793 import time
794 s = ''
795 for i in range(256): s = s + chr(i)
796 s = s*4
797 t0 = time.time()
798 qs = quote(s)
799 uqs = unquote(qs)
800 t1 = time.time()
801 if uqs != s:
802 print 'Wrong!'
803 print `s`
804 print `qs`
805 print `uqs`
806 print round(t1 - t0, 3), 'sec'
807
808
809# Test program
810def test():
811 import sys
812 import regsub
813 args = sys.argv[1:]
814 if not args:
815 args = [
816 '/etc/passwd',
817 'file:/etc/passwd',
818 'file://localhost/etc/passwd',
819 'ftp://ftp.cwi.nl/etc/passwd',
820 'gopher://gopher.cwi.nl/11/',
821 'http://www.cwi.nl/index.html',
822 ]
823 try:
824 for url in args:
825 print '-'*10, url, '-'*10
826 fn, h = urlretrieve(url)
827 print fn, h
828 if h:
829 print '======'
830 for k in h.keys(): print k + ':', h[k]
831 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000832 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000833 data = fp.read()
834 del fp
835 print regsub.gsub('\r', '', data)
836 fn, h = None, None
837 print '-'*40
838 finally:
839 urlcleanup()
840
841# Run test program when run as a script
842if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000843## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000844 test()