blob: af943545d28a53f2e5f2992cca232c1b4e8b94c1 [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 Rossuma7e4b281996-06-11 00:16:27 +0000186 tfp = open(filename, 'w')
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)
207 if string.lower(urltype) == 'http':
208 realhost, rest = splithost(rest)
209 user_passwd, realhost = splituser(realhost)
210 if user_passwd:
211 selector = "%s://%s%s" % (urltype,
212 realhost, rest)
Guido van Rossum442e7201996-03-20 15:33:11 +0000213 print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000214 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000215 if user_passwd:
216 import base64
217 auth = string.strip(base64.encodestring(user_passwd))
218 else:
219 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000220 h = httplib.HTTP(host)
Guido van Rossumbd013741996-12-10 16:00:28 +0000221 if data is not None:
222 h.putrequest('POST', selector)
223 h.putheader('Content-type',
224 'application/x-www-form-urlencoded')
225 h.putheader('Content-length', '%d' % len(data))
226 else:
227 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000228 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000229 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000230 h.endheaders()
Guido van Rossumbd013741996-12-10 16:00:28 +0000231 if data is not None:
232 h.send(data + '\r\n')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000233 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000234 fp = h.getfile()
235 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000236 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000237 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000238 return self.http_error(url,
239 fp, errcode, errmsg, headers)
240
241 # Handle http errors.
242 # Derived class can override this, or provide specific handlers
243 # named http_error_DDD where DDD is the 3-digit error code
244 def http_error(self, url, fp, errcode, errmsg, headers):
245 # First check if there's a specific handler for this error
246 name = 'http_error_%d' % errcode
247 if hasattr(self, name):
248 method = getattr(self, name)
249 result = method(url, fp, errcode, errmsg, headers)
250 if result: return result
251 return self.http_error_default(
252 url, fp, errcode, errmsg, headers)
253
254 # Default http error handler: close the connection and raises IOError
255 def http_error_default(self, url, fp, errcode, errmsg, headers):
256 void = fp.read()
257 fp.close()
258 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000259
260 # Use Gopher protocol
261 def open_gopher(self, url):
262 import gopherlib
263 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000264 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000265 type, selector = splitgophertype(selector)
266 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000267 selector = unquote(selector)
268 if query:
269 query = unquote(query)
270 fp = gopherlib.send_query(selector, query, host)
271 else:
272 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000273 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000274
275 # Use local file or FTP depending on form of URL
276 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000277 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000278 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000279 else:
280 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000281
282 # Use local file
283 def open_local_file(self, url):
284 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000285 if not host:
286 return addinfourl(open(url2pathname(file), 'r'), noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000287 host, port = splitport(host)
288 if not port and socket.gethostbyname(host) in (
289 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000290 file = unquote(file)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000291 return addinfourl(open(url2pathname(file), 'r'), noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000292 raise IOError, ('local file error', 'not on local host')
293
294 # Use FTP protocol
295 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000296 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000297 if not host: raise IOError, ('ftp error', 'no host given')
298 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000299 user, host = splituser(host)
300 if user: user, passwd = splitpasswd(user)
301 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000302 host = socket.gethostbyname(host)
303 if not port:
304 import ftplib
305 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000306 path, attrs = splitattr(path)
307 dirs = string.splitfields(path, '/')
308 dirs, file = dirs[:-1], dirs[-1]
309 if dirs and not dirs[0]: dirs = dirs[1:]
310 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000311 try:
312 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000313 self.ftpcache[key] = \
314 ftpwrapper(user, passwd,
315 host, port, dirs)
316 if not file: type = 'D'
317 else: type = 'I'
318 for attr in attrs:
319 attr, value = splitvalue(attr)
320 if string.lower(attr) == 'type' and \
321 value in ('a', 'A', 'i', 'I', 'd', 'D'):
322 type = string.upper(value)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000323 return addinfourl(self.ftpcache[key].retrfile(file, type),
324 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000325 except ftperrors(), msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000326 raise IOError, ('ftp error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000327
328
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000329# Derived class with handlers for errors we can handle (perhaps)
330class FancyURLopener(URLopener):
331
332 def __init__(self, *args):
333 apply(URLopener.__init__, (self,) + args)
334 self.auth_cache = {}
335
336 # Default error handling -- don't raise an exception
337 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000338 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000339
Guido van Rossume6ad8911996-09-10 17:02:56 +0000340 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000341 def http_error_302(self, url, fp, errcode, errmsg, headers):
342 # XXX The server can force infinite recursion here!
343 if headers.has_key('location'):
344 newurl = headers['location']
345 elif headers.has_key('uri'):
346 newurl = headers['uri']
347 else:
348 return
349 void = fp.read()
350 fp.close()
351 return self.open(newurl)
352
Guido van Rossume6ad8911996-09-10 17:02:56 +0000353 # Error 301 -- also relocated (permanently)
354 http_error_301 = http_error_302
355
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000356 # Error 401 -- authentication required
357 # See this URL for a description of the basic authentication scheme:
358 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
359 def http_error_401(self, url, fp, errcode, errmsg, headers):
360 if headers.has_key('www-authenticate'):
361 stuff = headers['www-authenticate']
362 p = regex.compile(
363 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
364 if p.match(stuff) >= 0:
365 scheme, realm = p.group(1, 2)
366 if string.lower(scheme) == 'basic':
367 return self.retry_http_basic_auth(
368 url, realm)
369
370 def retry_http_basic_auth(self, url, realm):
371 host, selector = splithost(url)
372 i = string.find(host, '@') + 1
373 host = host[i:]
374 user, passwd = self.get_user_passwd(host, realm, i)
375 if not (user or passwd): return None
376 host = user + ':' + passwd + '@' + host
377 newurl = '//' + host + selector
378 return self.open_http(newurl)
379
380 def get_user_passwd(self, host, realm, clear_cache = 0):
381 key = realm + '@' + string.lower(host)
382 if self.auth_cache.has_key(key):
383 if clear_cache:
384 del self.auth_cache[key]
385 else:
386 return self.auth_cache[key]
387 user, passwd = self.prompt_user_passwd(host, realm)
388 if user or passwd: self.auth_cache[key] = (user, passwd)
389 return user, passwd
390
391 def prompt_user_passwd(self, host, realm):
392 # Override this in a GUI environment!
393 try:
394 user = raw_input("Enter username for %s at %s: " %
395 (realm, host))
396 self.echo_off()
397 try:
398 passwd = raw_input(
399 "Enter password for %s in %s at %s: " %
400 (user, realm, host))
401 finally:
402 self.echo_on()
403 return user, passwd
404 except KeyboardInterrupt:
405 return None, None
406
407 def echo_off(self):
408 import os
409 os.system("stty -echo")
410
411 def echo_on(self):
412 import os
413 print
414 os.system("stty echo")
415
416
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000417# Utility functions
418
419# Return the IP address of the magic hostname 'localhost'
420_localhost = None
421def localhost():
422 global _localhost
423 if not _localhost:
424 _localhost = socket.gethostbyname('localhost')
425 return _localhost
426
427# Return the IP address of the current host
428_thishost = None
429def thishost():
430 global _thishost
431 if not _thishost:
432 _thishost = socket.gethostbyname(socket.gethostname())
433 return _thishost
434
435# Return the set of errors raised by the FTP class
436_ftperrors = None
437def ftperrors():
438 global _ftperrors
439 if not _ftperrors:
440 import ftplib
441 _ftperrors = (ftplib.error_reply,
442 ftplib.error_temp,
443 ftplib.error_perm,
444 ftplib.error_proto)
445 return _ftperrors
446
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000447# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000448_noheaders = None
449def noheaders():
450 global _noheaders
451 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000452 import mimetools
453 import StringIO
454 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000455 _noheaders.fp.close() # Recycle file descriptor
456 return _noheaders
457
458
459# Utility classes
460
461# Class used by open_ftp() for cache of open FTP connections
462class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000463 def __init__(self, user, passwd, host, port, dirs):
464 self.user = unquote(user or '')
465 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000466 self.host = host
467 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000468 self.dirs = []
469 for dir in dirs:
470 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000471 self.init()
472 def init(self):
473 import ftplib
474 self.ftp = ftplib.FTP()
475 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000476 self.ftp.login(self.user, self.passwd)
477 for dir in self.dirs:
478 self.ftp.cwd(dir)
479 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000480 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000481 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
482 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000483 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000484 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000485 except ftplib.all_errors:
486 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000487 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000488 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000489 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000490 try:
491 cmd = 'RETR ' + file
492 conn = self.ftp.transfercmd(cmd)
493 except ftplib.error_perm, reason:
494 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000495 raise IOError, ('ftp error', reason), \
496 sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000497 if not conn:
498 # Try a directory listing
499 if file: cmd = 'LIST ' + file
500 else: cmd = 'LIST'
501 conn = self.ftp.transfercmd(cmd)
Jack Jansen0d12ead1996-02-14 16:05:20 +0000502 return addclosehook(conn.makefile('rb'), self.ftp.voidresp)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000503
504# Base class for addinfo and addclosehook
505class addbase:
506 def __init__(self, fp):
507 self.fp = fp
508 self.read = self.fp.read
509 self.readline = self.fp.readline
510 self.readlines = self.fp.readlines
511 self.fileno = self.fp.fileno
512 def __repr__(self):
513 return '<%s at %s whose fp = %s>' % (
514 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000515 def close(self):
516 self.read = None
517 self.readline = None
518 self.readlines = None
519 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000520 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000521 self.fp = None
522
523# Class to add a close hook to an open file
524class addclosehook(addbase):
525 def __init__(self, fp, closehook, *hookargs):
526 addbase.__init__(self, fp)
527 self.closehook = closehook
528 self.hookargs = hookargs
529 def close(self):
530 if self.closehook:
531 apply(self.closehook, self.hookargs)
532 self.closehook = None
533 self.hookargs = None
534 addbase.close(self)
535
536# class to add an info() method to an open file
537class addinfo(addbase):
538 def __init__(self, fp, headers):
539 addbase.__init__(self, fp)
540 self.headers = headers
541 def info(self):
542 return self.headers
543
Guido van Rossume6ad8911996-09-10 17:02:56 +0000544# class to add info() and geturl() methods to an open file
545class addinfourl(addbase):
546 def __init__(self, fp, headers, url):
547 addbase.__init__(self, fp)
548 self.headers = headers
549 self.url = url
550 def info(self):
551 return self.headers
552 def geturl(self):
553 return self.url
554
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000555
556# Utility to combine a URL with a base URL to form a new URL
557
558def basejoin(base, url):
559 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000560 if type:
561 # if url is complete (i.e., it contains a type), return it
562 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000563 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000564 type, basepath = splittype(base) # inherit type from base
565 if host:
566 # if url contains host, just inherit type
567 if type: return type + '://' + host + path
568 else:
569 # no type inherited, so url must have started with //
570 # just return it
571 return url
572 host, basepath = splithost(basepath) # inherit host
573 basepath, basetag = splittag(basepath) # remove extraneuous cruft
574 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000575 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000576 # non-absolute path name
577 if path[:1] in ('#', '?'):
578 # path is just a tag or query, attach to basepath
579 i = len(basepath)
580 else:
581 # else replace last component
582 i = string.rfind(basepath, '/')
583 if i < 0:
584 # basepath not absolute
585 if host:
586 # host present, make absolute
587 basepath = '/'
588 else:
589 # else keep non-absolute
590 basepath = ''
591 else:
592 # remove last file component
593 basepath = basepath[:i+1]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000594 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000595 if type and host: return type + '://' + host + path
596 elif type: return type + ':' + path
597 elif host: return '//' + host + path # don't know what this means
598 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000599
600
Guido van Rossum7c395db1994-07-04 22:14:49 +0000601# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000602# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000603# splittype('type:opaquestring') --> 'type', 'opaquestring'
604# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000605# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
606# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000607# splitport('host:port') --> 'host', 'port'
608# splitquery('/path?query') --> '/path', 'query'
609# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000610# splitattr('/path;attr1=value1;attr2=value2;...') ->
611# '/path', ['attr1=value1', 'attr2=value2', ...]
612# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000613# splitgophertype('/Xselector') --> 'X', 'selector'
614# unquote('abc%20def') -> 'abc def'
615# quote('abc def') -> 'abc%20def')
616
617def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000618 url = string.strip(url)
619 if url[:1] == '<' and url[-1:] == '>':
620 url = string.strip(url[1:-1])
621 if url[:4] == 'URL:': url = string.strip(url[4:])
622 return url
623
624_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
625def splittype(url):
626 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
627 return None, url
628
629_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
630def splithost(url):
631 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
632 return None, url
633
Guido van Rossum7c395db1994-07-04 22:14:49 +0000634_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
635def splituser(host):
636 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
637 return None, host
638
639_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
640def splitpasswd(user):
641 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
642 return user, None
643
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000644_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
645def splitport(host):
646 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
647 return host, None
648
Guido van Rossum53725a21996-06-13 19:12:35 +0000649# Split host and port, returning numeric port.
650# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000651# Return numerical port if a valid number are found after ':'.
652# Return None if ':' but not a valid number.
653_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000654def splitnport(host, defport=-1):
655 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000656 host, port = _nportprog.group(1, 2)
657 try:
658 if not port: raise string.atoi_error, "no digits"
659 nport = string.atoi(port)
660 except string.atoi_error:
661 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000662 return host, nport
663 return host, defport
664
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000665_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
666def splitquery(url):
667 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
668 return url, None
669
670_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
671def splittag(url):
672 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
673 return url, None
674
Guido van Rossum7c395db1994-07-04 22:14:49 +0000675def splitattr(url):
676 words = string.splitfields(url, ';')
677 return words[0], words[1:]
678
679_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
680def splitvalue(attr):
681 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
682 return attr, None
683
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000684def splitgophertype(selector):
685 if selector[:1] == '/' and selector[1:2]:
686 return selector[1], selector[2:]
687 return None, selector
688
689_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
690def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000691 i = 0
692 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000693 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000694 while 0 <= i < n:
695 j = _quoteprog.search(s, i)
696 if j < 0:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000697 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000698 break
Guido van Rossumf8abb381996-08-26 15:56:12 +0000699 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000700 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000701 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000702
Guido van Rossum0564e121996-12-13 14:47:36 +0000703def unquote_plus(s):
704 if '+' in s:
705 import regsub
706 s = regsub.gsub('+', ' ', s)
707 return unquote(s)
708
Guido van Rossum3bb54481994-08-29 10:52:58 +0000709always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000710def quote(s, safe = '/'):
711 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000712 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000713 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000714 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000715 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000716 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000717 res.append('%%%02x' % ord(c))
718 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000719
Guido van Rossum0564e121996-12-13 14:47:36 +0000720def quote_plus(s, safe = '/'):
721 if ' ' in s:
722 import regsub
723 s = regsub.gsub(' ', '+', s)
724 return quote(s, safe + '+')
725 else:
726 return quote(s, safe)
727
Guido van Rossum442e7201996-03-20 15:33:11 +0000728
729# Proxy handling
730def getproxies():
731 """Return a dictionary of protocol scheme -> proxy server URL mappings.
732
733 Scan the environment for variables named <scheme>_proxy;
734 this seems to be the standard convention. If you need a
735 different way, you can pass a proxies dictionary to the
736 [Fancy]URLopener constructor.
737
738 """
739 proxies = {}
740 for name, value in os.environ.items():
741 if value and name[-6:] == '_proxy':
742 proxies[name[:-6]] = value
743 return proxies
744
745
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000746# Test and time quote() and unquote()
747def test1():
748 import time
749 s = ''
750 for i in range(256): s = s + chr(i)
751 s = s*4
752 t0 = time.time()
753 qs = quote(s)
754 uqs = unquote(qs)
755 t1 = time.time()
756 if uqs != s:
757 print 'Wrong!'
758 print `s`
759 print `qs`
760 print `uqs`
761 print round(t1 - t0, 3), 'sec'
762
763
764# Test program
765def test():
766 import sys
767 import regsub
768 args = sys.argv[1:]
769 if not args:
770 args = [
771 '/etc/passwd',
772 'file:/etc/passwd',
773 'file://localhost/etc/passwd',
774 'ftp://ftp.cwi.nl/etc/passwd',
775 'gopher://gopher.cwi.nl/11/',
776 'http://www.cwi.nl/index.html',
777 ]
778 try:
779 for url in args:
780 print '-'*10, url, '-'*10
781 fn, h = urlretrieve(url)
782 print fn, h
783 if h:
784 print '======'
785 for k in h.keys(): print k + ':', h[k]
786 print '======'
787 fp = open(fn, 'r')
788 data = fp.read()
789 del fp
790 print regsub.gsub('\r', '', data)
791 fn, h = None, None
792 print '-'*40
793 finally:
794 urlcleanup()
795
796# Run test program when run as a script
797if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000798## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000799 test()