blob: e57311b519b5105d5c2788e56e038409ccc80cc4 [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 Rossumbd013741996-12-10 16:00:28 +000031__version__ = '1.6'
Guido van Rossum6cb15a01995-06-22 19:00:13 +000032
Jack Jansendc3e3f61995-12-15 13:22:13 +000033# Helper for non-unix systems
34if os.name == 'mac':
Guido van Rossum71ac9451996-03-21 16:31:41 +000035 from macurl2path import url2pathname, pathname2url
Guido van Rossum2281d351996-06-26 19:47:37 +000036elif os.name == 'nt':
37 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000038else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000039 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000040 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000041 def pathname2url(pathname):
42 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000043
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000044# This really consists of two pieces:
45# (1) a class which handles opening of all sorts of URLs
46# (plus assorted utilities etc.)
47# (2) a set of functions for parsing URLs
48# XXX Should these be separated out into different modules?
49
50
51# Shortcut for basic usage
52_urlopener = None
Guido van Rossumbd013741996-12-10 16:00:28 +000053def urlopen(url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000054 global _urlopener
55 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000056 _urlopener = FancyURLopener()
Guido van Rossumbd013741996-12-10 16:00:28 +000057 if data is None:
58 return _urlopener.open(url)
59 else:
60 return _urlopener.open(url, data)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000061def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000062 global _urlopener
63 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000064 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000065 if filename:
66 return _urlopener.retrieve(url, filename)
67 else:
68 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000069def urlcleanup():
70 if _urlopener:
71 _urlopener.cleanup()
72
73
74# Class to open URLs.
75# This is a class rather than just a subroutine because we may need
76# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000077# Note -- this is a base class for those who don't want the
78# automatic handling of errors type 302 (relocated) and 401
79# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000080ftpcache = {}
81class URLopener:
82
Guido van Rossum29e77811996-11-27 19:39:58 +000083 tempcache = None # So close() in __del__() won't fail
84
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000085 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000086 def __init__(self, proxies=None):
87 if proxies is None:
88 proxies = getproxies()
89 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +000090 server_version = "Python-urllib/%s" % __version__
91 self.addheaders = [('User-agent', server_version)]
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000092 self.tempcache = None
93 # Undocumented feature: if you assign {} to tempcache,
94 # it is used to cache files retrieved with
95 # self.retrieve(). This is not enabled by default
96 # since it does not work for changing documents (and I
97 # haven't got the logic to check expiration headers
98 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000099 self.ftpcache = ftpcache
100 # Undocumented feature: you can use a different
101 # ftp cache by assigning to the .ftpcache member;
102 # in case you want logically independent URL openers
103
104 def __del__(self):
105 self.close()
106
107 def close(self):
108 self.cleanup()
109
110 def cleanup(self):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000111 if self.tempcache:
Guido van Rossumd23d9401997-01-30 15:54:58 +0000112 import os
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000113 for url in self.tempcache.keys():
114 try:
115 os.unlink(self.tempcache[url][0])
116 except os.error:
117 pass
118 del self.tempcache[url]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000119
120 # Add a header to be used by the HTTP interface only
121 # e.g. u.addheader('Accept', 'sound/basic')
122 def addheader(self, *args):
123 self.addheaders.append(args)
124
125 # External interface
126 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumbd013741996-12-10 16:00:28 +0000127 def open(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000128 fullurl = unwrap(fullurl)
129 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000130 if not type: type = 'file'
Guido van Rossume6ad8911996-09-10 17:02:56 +0000131 self.openedurl = '%s:%s' % (type, url)
Guido van Rossum442e7201996-03-20 15:33:11 +0000132 if self.proxies.has_key(type):
133 proxy = self.proxies[type]
134 type, proxy = splittype(proxy)
135 host, selector = splithost(proxy)
136 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000137 name = 'open_' + type
138 if '-' in name:
139 import regsub
140 name = regsub.gsub('-', '_', name)
141 if not hasattr(self, name):
Guido van Rossumbd013741996-12-10 16:00:28 +0000142 if data is None:
143 return self.open_unknown(fullurl)
144 else:
145 return self.open_unknown(fullurl, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000146 try:
Guido van Rossumbd013741996-12-10 16:00:28 +0000147 if data is None:
148 return getattr(self, name)(url)
149 else:
150 return getattr(self, name)(url, data)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000151 except socket.error, msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000152 raise IOError, ('socket error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000153
Guido van Rossumca445401995-08-29 19:19:12 +0000154 # Overridable interface to open unknown URL type
Guido van Rossumbd013741996-12-10 16:00:28 +0000155 def open_unknown(self, fullurl, data=None):
Guido van Rossumca445401995-08-29 19:19:12 +0000156 type, url = splittype(fullurl)
157 raise IOError, ('url error', 'unknown url type', type)
158
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000159 # External interface
160 # retrieve(url) returns (filename, None) for a local object
161 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000162 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000163 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000164 return self.tempcache[url]
165 url1 = unwrap(url)
Guido van Rossum5b1b33c1996-10-22 13:28:37 +0000166 self.openedurl = url1
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000167 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000168 self.tempcache[url] = self.tempcache[url1]
169 return self.tempcache[url1]
170 type, url1 = splittype(url1)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000171 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000172 try:
173 fp = self.open_local_file(url1)
174 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000175 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000176 except IOError, msg:
177 pass
178 fp = self.open(url)
179 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000180 if not filename:
181 import tempfile
182 filename = tempfile.mktemp()
183 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000184 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000185 self.tempcache[url] = result
Guido van Rossumc511aee1997-04-11 19:01:48 +0000186 tfp = open(filename, 'wb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000187 bs = 1024*8
188 block = fp.read(bs)
189 while block:
190 tfp.write(block)
191 block = fp.read(bs)
192 del fp
193 del tfp
194 return result
195
196 # Each method named open_<type> knows how to open that type of URL
197
198 # Use HTTP protocol
Guido van Rossumbd013741996-12-10 16:00:28 +0000199 def open_http(self, url, data=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000200 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000201 if type(url) is type(""):
202 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000203 user_passwd, host = splituser(host)
Guido van Rossum442e7201996-03-20 15:33:11 +0000204 else:
205 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000206 urltype, rest = splittype(selector)
Guido van Rossumfd795661997-04-02 05:46:35 +0000207 user_passwd = None
Guido van Rossum78c96371996-08-26 18:09:59 +0000208 if string.lower(urltype) == 'http':
209 realhost, rest = splithost(rest)
210 user_passwd, realhost = splituser(realhost)
211 if user_passwd:
212 selector = "%s://%s%s" % (urltype,
213 realhost, rest)
Guido van Rossumfd795661997-04-02 05:46:35 +0000214 #print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000215 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000216 if user_passwd:
217 import base64
218 auth = string.strip(base64.encodestring(user_passwd))
219 else:
220 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000221 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000222 if data is not None:
223 h.putrequest('POST', selector)
224 h.putheader('Content-type',
225 'application/x-www-form-urlencoded')
226 h.putheader('Content-length', '%d' % len(data))
227 else:
228 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000229 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000230 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000231 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000232 if data is not None:
233 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000234 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000235 fp = h.getfile()
236 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000237 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000238 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000239 return self.http_error(url,
240 fp, errcode, errmsg, headers)
241
242 # Handle http errors.
243 # Derived class can override this, or provide specific handlers
244 # named http_error_DDD where DDD is the 3-digit error code
245 def http_error(self, url, fp, errcode, errmsg, headers):
246 # First check if there's a specific handler for this error
247 name = 'http_error_%d' % errcode
248 if hasattr(self, name):
249 method = getattr(self, name)
250 result = method(url, fp, errcode, errmsg, headers)
251 if result: return result
252 return self.http_error_default(
253 url, fp, errcode, errmsg, headers)
254
255 # Default http error handler: close the connection and raises IOError
256 def http_error_default(self, url, fp, errcode, errmsg, headers):
257 void = fp.read()
258 fp.close()
259 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000260
261 # Use Gopher protocol
262 def open_gopher(self, url):
263 import gopherlib
264 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000265 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000266 type, selector = splitgophertype(selector)
267 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000268 selector = unquote(selector)
269 if query:
270 query = unquote(query)
271 fp = gopherlib.send_query(selector, query, host)
272 else:
273 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000274 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000275
276 # Use local file or FTP depending on form of URL
277 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000278 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000279 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000280 else:
281 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000282
283 # Use local file
284 def open_local_file(self, url):
285 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000286 if not host:
Guido van Rossumc511aee1997-04-11 19:01:48 +0000287 return addinfourl(open(url2pathname(file), 'rb'), noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000288 host, port = splitport(host)
289 if not port and socket.gethostbyname(host) in (
290 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000291 file = unquote(file)
Guido van Rossumc511aee1997-04-11 19:01:48 +0000292 return addinfourl(open(url2pathname(file), 'rb'), noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000293 raise IOError, ('local file error', 'not on local host')
294
295 # Use FTP protocol
296 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000297 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000298 if not host: raise IOError, ('ftp error', 'no host given')
299 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000300 user, host = splituser(host)
301 if user: user, passwd = splitpasswd(user)
302 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000303 host = socket.gethostbyname(host)
304 if not port:
305 import ftplib
306 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000307 path, attrs = splitattr(path)
308 dirs = string.splitfields(path, '/')
309 dirs, file = dirs[:-1], dirs[-1]
310 if dirs and not dirs[0]: dirs = dirs[1:]
311 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000312 try:
313 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000314 self.ftpcache[key] = \
315 ftpwrapper(user, passwd,
316 host, port, dirs)
317 if not file: type = 'D'
318 else: type = 'I'
319 for attr in attrs:
320 attr, value = splitvalue(attr)
321 if string.lower(attr) == 'type' and \
322 value in ('a', 'A', 'i', 'I', 'd', 'D'):
323 type = string.upper(value)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000324 return addinfourl(self.ftpcache[key].retrfile(file, type),
325 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000326 except ftperrors(), msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000327 raise IOError, ('ftp error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000328
329
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000330# Derived class with handlers for errors we can handle (perhaps)
331class FancyURLopener(URLopener):
332
333 def __init__(self, *args):
334 apply(URLopener.__init__, (self,) + args)
335 self.auth_cache = {}
336
337 # Default error handling -- don't raise an exception
338 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000339 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000340
Guido van Rossume6ad8911996-09-10 17:02:56 +0000341 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000342 def http_error_302(self, url, fp, errcode, errmsg, headers):
343 # XXX The server can force infinite recursion here!
344 if headers.has_key('location'):
345 newurl = headers['location']
346 elif headers.has_key('uri'):
347 newurl = headers['uri']
348 else:
349 return
350 void = fp.read()
351 fp.close()
352 return self.open(newurl)
353
Guido van Rossume6ad8911996-09-10 17:02:56 +0000354 # Error 301 -- also relocated (permanently)
355 http_error_301 = http_error_302
356
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000357 # Error 401 -- authentication required
358 # See this URL for a description of the basic authentication scheme:
359 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
360 def http_error_401(self, url, fp, errcode, errmsg, headers):
361 if headers.has_key('www-authenticate'):
362 stuff = headers['www-authenticate']
363 p = regex.compile(
364 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
365 if p.match(stuff) >= 0:
366 scheme, realm = p.group(1, 2)
367 if string.lower(scheme) == 'basic':
368 return self.retry_http_basic_auth(
369 url, realm)
370
371 def retry_http_basic_auth(self, url, realm):
372 host, selector = splithost(url)
373 i = string.find(host, '@') + 1
374 host = host[i:]
375 user, passwd = self.get_user_passwd(host, realm, i)
376 if not (user or passwd): return None
377 host = user + ':' + passwd + '@' + host
378 newurl = '//' + host + selector
379 return self.open_http(newurl)
380
381 def get_user_passwd(self, host, realm, clear_cache = 0):
382 key = realm + '@' + string.lower(host)
383 if self.auth_cache.has_key(key):
384 if clear_cache:
385 del self.auth_cache[key]
386 else:
387 return self.auth_cache[key]
388 user, passwd = self.prompt_user_passwd(host, realm)
389 if user or passwd: self.auth_cache[key] = (user, passwd)
390 return user, passwd
391
392 def prompt_user_passwd(self, host, realm):
393 # Override this in a GUI environment!
394 try:
395 user = raw_input("Enter username for %s at %s: " %
396 (realm, host))
397 self.echo_off()
398 try:
399 passwd = raw_input(
400 "Enter password for %s in %s at %s: " %
401 (user, realm, host))
402 finally:
403 self.echo_on()
404 return user, passwd
405 except KeyboardInterrupt:
406 return None, None
407
408 def echo_off(self):
409 import os
410 os.system("stty -echo")
411
412 def echo_on(self):
413 import os
414 print
415 os.system("stty echo")
416
417
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000418# Utility functions
419
420# Return the IP address of the magic hostname 'localhost'
421_localhost = None
422def localhost():
423 global _localhost
424 if not _localhost:
425 _localhost = socket.gethostbyname('localhost')
426 return _localhost
427
428# Return the IP address of the current host
429_thishost = None
430def thishost():
431 global _thishost
432 if not _thishost:
433 _thishost = socket.gethostbyname(socket.gethostname())
434 return _thishost
435
436# Return the set of errors raised by the FTP class
437_ftperrors = None
438def ftperrors():
439 global _ftperrors
440 if not _ftperrors:
441 import ftplib
442 _ftperrors = (ftplib.error_reply,
443 ftplib.error_temp,
444 ftplib.error_perm,
445 ftplib.error_proto)
446 return _ftperrors
447
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000448# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000449_noheaders = None
450def noheaders():
451 global _noheaders
452 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000453 import mimetools
454 import StringIO
455 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000456 _noheaders.fp.close() # Recycle file descriptor
457 return _noheaders
458
459
460# Utility classes
461
462# Class used by open_ftp() for cache of open FTP connections
463class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000464 def __init__(self, user, passwd, host, port, dirs):
465 self.user = unquote(user or '')
466 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000467 self.host = host
468 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000469 self.dirs = []
470 for dir in dirs:
471 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000472 self.init()
473 def init(self):
474 import ftplib
475 self.ftp = ftplib.FTP()
476 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000477 self.ftp.login(self.user, self.passwd)
478 for dir in self.dirs:
479 self.ftp.cwd(dir)
480 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000481 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000482 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
483 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000484 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000485 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000486 except ftplib.all_errors:
487 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000488 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000489 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000490 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000491 try:
492 cmd = 'RETR ' + file
493 conn = self.ftp.transfercmd(cmd)
494 except ftplib.error_perm, reason:
495 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000496 raise IOError, ('ftp error', reason), \
497 sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000498 if not conn:
499 # Try a directory listing
500 if file: cmd = 'LIST ' + file
501 else: cmd = 'LIST'
502 conn = self.ftp.transfercmd(cmd)
Jack Jansen0d12ead1996-02-14 16:05:20 +0000503 return addclosehook(conn.makefile('rb'), self.ftp.voidresp)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000504
505# Base class for addinfo and addclosehook
506class addbase:
507 def __init__(self, fp):
508 self.fp = fp
509 self.read = self.fp.read
510 self.readline = self.fp.readline
511 self.readlines = self.fp.readlines
512 self.fileno = self.fp.fileno
513 def __repr__(self):
514 return '<%s at %s whose fp = %s>' % (
515 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000516 def close(self):
517 self.read = None
518 self.readline = None
519 self.readlines = None
520 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000521 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000522 self.fp = None
523
524# Class to add a close hook to an open file
525class addclosehook(addbase):
526 def __init__(self, fp, closehook, *hookargs):
527 addbase.__init__(self, fp)
528 self.closehook = closehook
529 self.hookargs = hookargs
530 def close(self):
531 if self.closehook:
532 apply(self.closehook, self.hookargs)
533 self.closehook = None
534 self.hookargs = None
535 addbase.close(self)
536
537# class to add an info() method to an open file
538class addinfo(addbase):
539 def __init__(self, fp, headers):
540 addbase.__init__(self, fp)
541 self.headers = headers
542 def info(self):
543 return self.headers
544
Guido van Rossume6ad8911996-09-10 17:02:56 +0000545# class to add info() and geturl() methods to an open file
546class addinfourl(addbase):
547 def __init__(self, fp, headers, url):
548 addbase.__init__(self, fp)
549 self.headers = headers
550 self.url = url
551 def info(self):
552 return self.headers
553 def geturl(self):
554 return self.url
555
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000556
557# Utility to combine a URL with a base URL to form a new URL
558
559def basejoin(base, url):
560 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000561 if type:
562 # if url is complete (i.e., it contains a type), return it
563 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000564 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000565 type, basepath = splittype(base) # inherit type from base
566 if host:
567 # if url contains host, just inherit type
568 if type: return type + '://' + host + path
569 else:
570 # no type inherited, so url must have started with //
571 # just return it
572 return url
573 host, basepath = splithost(basepath) # inherit host
574 basepath, basetag = splittag(basepath) # remove extraneuous cruft
575 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000576 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000577 # non-absolute path name
578 if path[:1] in ('#', '?'):
579 # path is just a tag or query, attach to basepath
580 i = len(basepath)
581 else:
582 # else replace last component
583 i = string.rfind(basepath, '/')
584 if i < 0:
585 # basepath not absolute
586 if host:
587 # host present, make absolute
588 basepath = '/'
589 else:
590 # else keep non-absolute
591 basepath = ''
592 else:
593 # remove last file component
594 basepath = basepath[:i+1]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000595 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000596 if type and host: return type + '://' + host + path
597 elif type: return type + ':' + path
598 elif host: return '//' + host + path # don't know what this means
599 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000600
601
Guido van Rossum7c395db1994-07-04 22:14:49 +0000602# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000603# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000604# splittype('type:opaquestring') --> 'type', 'opaquestring'
605# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000606# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
607# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000608# splitport('host:port') --> 'host', 'port'
609# splitquery('/path?query') --> '/path', 'query'
610# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000611# splitattr('/path;attr1=value1;attr2=value2;...') ->
612# '/path', ['attr1=value1', 'attr2=value2', ...]
613# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000614# splitgophertype('/Xselector') --> 'X', 'selector'
615# unquote('abc%20def') -> 'abc def'
616# quote('abc def') -> 'abc%20def')
617
618def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000619 url = string.strip(url)
620 if url[:1] == '<' and url[-1:] == '>':
621 url = string.strip(url[1:-1])
622 if url[:4] == 'URL:': url = string.strip(url[4:])
623 return url
624
625_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
626def splittype(url):
627 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
628 return None, url
629
630_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
631def splithost(url):
632 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
633 return None, url
634
Guido van Rossum7c395db1994-07-04 22:14:49 +0000635_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
636def splituser(host):
637 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
638 return None, host
639
640_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
641def splitpasswd(user):
642 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
643 return user, None
644
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000645_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
646def splitport(host):
647 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
648 return host, None
649
Guido van Rossum53725a21996-06-13 19:12:35 +0000650# Split host and port, returning numeric port.
651# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000652# Return numerical port if a valid number are found after ':'.
653# Return None if ':' but not a valid number.
654_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000655def splitnport(host, defport=-1):
656 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000657 host, port = _nportprog.group(1, 2)
658 try:
659 if not port: raise string.atoi_error, "no digits"
660 nport = string.atoi(port)
661 except string.atoi_error:
662 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000663 return host, nport
664 return host, defport
665
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000666_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
667def splitquery(url):
668 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
669 return url, None
670
671_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
672def splittag(url):
673 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
674 return url, None
675
Guido van Rossum7c395db1994-07-04 22:14:49 +0000676def splitattr(url):
677 words = string.splitfields(url, ';')
678 return words[0], words[1:]
679
680_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
681def splitvalue(attr):
682 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
683 return attr, None
684
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000685def splitgophertype(selector):
686 if selector[:1] == '/' and selector[1:2]:
687 return selector[1], selector[2:]
688 return None, selector
689
690_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
691def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000692 i = 0
693 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000694 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000695 while 0 <= i < n:
696 j = _quoteprog.search(s, i)
697 if j < 0:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000698 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000699 break
Guido van Rossumf8abb381996-08-26 15:56:12 +0000700 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000701 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000702 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000703
Guido van Rossum0564e121996-12-13 14:47:36 +0000704def unquote_plus(s):
705 if '+' in s:
706 import regsub
707 s = regsub.gsub('+', ' ', s)
708 return unquote(s)
709
Guido van Rossum3bb54481994-08-29 10:52:58 +0000710always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000711def quote(s, safe = '/'):
712 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000713 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000714 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000715 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000716 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000717 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000718 res.append('%%%02x' % ord(c))
719 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000720
Guido van Rossum0564e121996-12-13 14:47:36 +0000721def quote_plus(s, safe = '/'):
722 if ' ' in s:
723 import regsub
724 s = regsub.gsub(' ', '+', s)
725 return quote(s, safe + '+')
726 else:
727 return quote(s, safe)
728
Guido van Rossum442e7201996-03-20 15:33:11 +0000729
730# Proxy handling
731def getproxies():
732 """Return a dictionary of protocol scheme -> proxy server URL mappings.
733
734 Scan the environment for variables named <scheme>_proxy;
735 this seems to be the standard convention. If you need a
736 different way, you can pass a proxies dictionary to the
737 [Fancy]URLopener constructor.
738
739 """
740 proxies = {}
741 for name, value in os.environ.items():
742 if value and name[-6:] == '_proxy':
743 proxies[name[:-6]] = value
744 return proxies
745
746
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000747# Test and time quote() and unquote()
748def test1():
749 import time
750 s = ''
751 for i in range(256): s = s + chr(i)
752 s = s*4
753 t0 = time.time()
754 qs = quote(s)
755 uqs = unquote(qs)
756 t1 = time.time()
757 if uqs != s:
758 print 'Wrong!'
759 print `s`
760 print `qs`
761 print `uqs`
762 print round(t1 - t0, 3), 'sec'
763
764
765# Test program
766def test():
767 import sys
768 import regsub
769 args = sys.argv[1:]
770 if not args:
771 args = [
772 '/etc/passwd',
773 'file:/etc/passwd',
774 'file://localhost/etc/passwd',
775 'ftp://ftp.cwi.nl/etc/passwd',
776 'gopher://gopher.cwi.nl/11/',
777 'http://www.cwi.nl/index.html',
778 ]
779 try:
780 for url in args:
781 print '-'*10, url, '-'*10
782 fn, h = urlretrieve(url)
783 print fn, h
784 if h:
785 print '======'
786 for k in h.keys(): print k + ':', h[k]
787 print '======'
Guido van Rossumc511aee1997-04-11 19:01:48 +0000788 fp = open(fn, 'rb')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000789 data = fp.read()
790 del fp
791 print regsub.gsub('\r', '', data)
792 fn, h = None, None
793 print '-'*40
794 finally:
795 urlcleanup()
796
797# Run test program when run as a script
798if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000799## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000800 test()