blob: 4f455f8c33ba5c9ccd139ae247547630ac601db5 [file] [log] [blame]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +00001# Open an arbitrary URL
2#
3# See the following document for a tentative description of URLs:
4# Uniform Resource Locators Tim Berners-Lee
5# INTERNET DRAFT CERN
6# IETF URL Working Group 14 July 1993
7# draft-ietf-uri-url-01.txt
8#
9# The object returned by URLopener().open(file) will differ per
10# protocol. All you know is that is has methods read(), readline(),
11# readlines(), fileno(), close() and info(). The read*(), fileno()
12# and close() methods work like those of open files.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000013# The info() method returns an mimetools.Message object which can be
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000014# used to query various info about the object, if available.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000015# (mimetools.Message objects are queried with the getheader() method.)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000016
Guido van Rossum7c395db1994-07-04 22:14:49 +000017import string
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000018import socket
19import regex
Jack Jansendc3e3f61995-12-15 13:22:13 +000020import os
Guido van Rossum3c8484e1996-11-20 22:02:24 +000021import sys
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000022
23
Guido van Rossume6ad8911996-09-10 17:02:56 +000024__version__ = '1.5'
Guido van Rossum6cb15a01995-06-22 19:00:13 +000025
Jack Jansendc3e3f61995-12-15 13:22:13 +000026# Helper for non-unix systems
27if os.name == 'mac':
Guido van Rossum71ac9451996-03-21 16:31:41 +000028 from macurl2path import url2pathname, pathname2url
Guido van Rossum2281d351996-06-26 19:47:37 +000029elif os.name == 'nt':
30 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000031else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000032 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000033 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000034 def pathname2url(pathname):
35 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000036
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000037# This really consists of two pieces:
38# (1) a class which handles opening of all sorts of URLs
39# (plus assorted utilities etc.)
40# (2) a set of functions for parsing URLs
41# XXX Should these be separated out into different modules?
42
43
44# Shortcut for basic usage
45_urlopener = None
46def urlopen(url):
47 global _urlopener
48 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000049 _urlopener = FancyURLopener()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000050 return _urlopener.open(url)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000051def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000052 global _urlopener
53 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000054 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000055 if filename:
56 return _urlopener.retrieve(url, filename)
57 else:
58 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000059def urlcleanup():
60 if _urlopener:
61 _urlopener.cleanup()
62
63
64# Class to open URLs.
65# This is a class rather than just a subroutine because we may need
66# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000067# Note -- this is a base class for those who don't want the
68# automatic handling of errors type 302 (relocated) and 401
69# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000070ftpcache = {}
71class URLopener:
72
Guido van Rossum29e77811996-11-27 19:39:58 +000073 tempcache = None # So close() in __del__() won't fail
74
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000075 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000076 def __init__(self, proxies=None):
77 if proxies is None:
78 proxies = getproxies()
79 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +000080 server_version = "Python-urllib/%s" % __version__
81 self.addheaders = [('User-agent', server_version)]
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000082 self.tempcache = None
83 # Undocumented feature: if you assign {} to tempcache,
84 # it is used to cache files retrieved with
85 # self.retrieve(). This is not enabled by default
86 # since it does not work for changing documents (and I
87 # haven't got the logic to check expiration headers
88 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000089 self.ftpcache = ftpcache
90 # Undocumented feature: you can use a different
91 # ftp cache by assigning to the .ftpcache member;
92 # in case you want logically independent URL openers
93
94 def __del__(self):
95 self.close()
96
97 def close(self):
98 self.cleanup()
99
100 def cleanup(self):
101 import os
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000102 if self.tempcache:
103 for url in self.tempcache.keys():
104 try:
105 os.unlink(self.tempcache[url][0])
106 except os.error:
107 pass
108 del self.tempcache[url]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000109
110 # Add a header to be used by the HTTP interface only
111 # e.g. u.addheader('Accept', 'sound/basic')
112 def addheader(self, *args):
113 self.addheaders.append(args)
114
115 # External interface
116 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumca445401995-08-29 19:19:12 +0000117 def open(self, fullurl):
118 fullurl = unwrap(fullurl)
119 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000120 if not type: type = 'file'
Guido van Rossume6ad8911996-09-10 17:02:56 +0000121 self.openedurl = '%s:%s' % (type, url)
Guido van Rossum442e7201996-03-20 15:33:11 +0000122 if self.proxies.has_key(type):
123 proxy = self.proxies[type]
124 type, proxy = splittype(proxy)
125 host, selector = splithost(proxy)
126 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000127 name = 'open_' + type
128 if '-' in name:
129 import regsub
130 name = regsub.gsub('-', '_', name)
131 if not hasattr(self, name):
Guido van Rossumca445401995-08-29 19:19:12 +0000132 return self.open_unknown(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000133 try:
134 return getattr(self, name)(url)
135 except socket.error, msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000136 raise IOError, ('socket error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000137
Guido van Rossumca445401995-08-29 19:19:12 +0000138 # Overridable interface to open unknown URL type
139 def open_unknown(self, fullurl):
140 type, url = splittype(fullurl)
141 raise IOError, ('url error', 'unknown url type', type)
142
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000143 # External interface
144 # retrieve(url) returns (filename, None) for a local object
145 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000146 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000147 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000148 return self.tempcache[url]
149 url1 = unwrap(url)
Guido van Rossum5b1b33c1996-10-22 13:28:37 +0000150 self.openedurl = url1
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000151 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000152 self.tempcache[url] = self.tempcache[url1]
153 return self.tempcache[url1]
154 type, url1 = splittype(url1)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000155 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000156 try:
157 fp = self.open_local_file(url1)
158 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000159 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000160 except IOError, msg:
161 pass
162 fp = self.open(url)
163 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000164 if not filename:
165 import tempfile
166 filename = tempfile.mktemp()
167 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000168 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000169 self.tempcache[url] = result
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000170 tfp = open(filename, 'w')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000171 bs = 1024*8
172 block = fp.read(bs)
173 while block:
174 tfp.write(block)
175 block = fp.read(bs)
176 del fp
177 del tfp
178 return result
179
180 # Each method named open_<type> knows how to open that type of URL
181
182 # Use HTTP protocol
183 def open_http(self, url):
184 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000185 if type(url) is type(""):
186 host, selector = splithost(url)
Guido van Rossum78c96371996-08-26 18:09:59 +0000187 user_passwd, host = splituser(host)
Guido van Rossum442e7201996-03-20 15:33:11 +0000188 else:
189 host, selector = url
Guido van Rossum78c96371996-08-26 18:09:59 +0000190 urltype, rest = splittype(selector)
191 if string.lower(urltype) == 'http':
192 realhost, rest = splithost(rest)
193 user_passwd, realhost = splituser(realhost)
194 if user_passwd:
195 selector = "%s://%s%s" % (urltype,
196 realhost, rest)
Guido van Rossum442e7201996-03-20 15:33:11 +0000197 print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000198 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000199 if user_passwd:
200 import base64
201 auth = string.strip(base64.encodestring(user_passwd))
202 else:
203 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000204 h = httplib.HTTP(host)
205 h.putrequest('GET', selector)
Guido van Rossumc5d7e801996-11-11 19:01:17 +0000206 if auth: h.putheader('Authorization', 'Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000207 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000208 h.endheaders()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000209 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000210 fp = h.getfile()
211 if errcode == 200:
Guido van Rossume6ad8911996-09-10 17:02:56 +0000212 return addinfourl(fp, headers, self.openedurl)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000213 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000214 return self.http_error(url,
215 fp, errcode, errmsg, headers)
216
217 # Handle http errors.
218 # Derived class can override this, or provide specific handlers
219 # named http_error_DDD where DDD is the 3-digit error code
220 def http_error(self, url, fp, errcode, errmsg, headers):
221 # First check if there's a specific handler for this error
222 name = 'http_error_%d' % errcode
223 if hasattr(self, name):
224 method = getattr(self, name)
225 result = method(url, fp, errcode, errmsg, headers)
226 if result: return result
227 return self.http_error_default(
228 url, fp, errcode, errmsg, headers)
229
230 # Default http error handler: close the connection and raises IOError
231 def http_error_default(self, url, fp, errcode, errmsg, headers):
232 void = fp.read()
233 fp.close()
234 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000235
236 # Use Gopher protocol
237 def open_gopher(self, url):
238 import gopherlib
239 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000240 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000241 type, selector = splitgophertype(selector)
242 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000243 selector = unquote(selector)
244 if query:
245 query = unquote(query)
246 fp = gopherlib.send_query(selector, query, host)
247 else:
248 fp = gopherlib.send_selector(selector, host)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000249 return addinfourl(fp, noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000250
251 # Use local file or FTP depending on form of URL
252 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000253 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000254 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000255 else:
256 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000257
258 # Use local file
259 def open_local_file(self, url):
260 host, file = splithost(url)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000261 if not host:
262 return addinfourl(open(url2pathname(file), 'r'), noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000263 host, port = splitport(host)
264 if not port and socket.gethostbyname(host) in (
265 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000266 file = unquote(file)
Guido van Rossumb030bc01996-10-10 16:01:16 +0000267 return addinfourl(open(url2pathname(file), 'r'), noheaders(), 'file:'+file)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000268 raise IOError, ('local file error', 'not on local host')
269
270 # Use FTP protocol
271 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000272 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000273 if not host: raise IOError, ('ftp error', 'no host given')
274 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000275 user, host = splituser(host)
276 if user: user, passwd = splitpasswd(user)
277 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000278 host = socket.gethostbyname(host)
279 if not port:
280 import ftplib
281 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000282 path, attrs = splitattr(path)
283 dirs = string.splitfields(path, '/')
284 dirs, file = dirs[:-1], dirs[-1]
285 if dirs and not dirs[0]: dirs = dirs[1:]
286 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000287 try:
288 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000289 self.ftpcache[key] = \
290 ftpwrapper(user, passwd,
291 host, port, dirs)
292 if not file: type = 'D'
293 else: type = 'I'
294 for attr in attrs:
295 attr, value = splitvalue(attr)
296 if string.lower(attr) == 'type' and \
297 value in ('a', 'A', 'i', 'I', 'd', 'D'):
298 type = string.upper(value)
Guido van Rossume6ad8911996-09-10 17:02:56 +0000299 return addinfourl(self.ftpcache[key].retrfile(file, type),
300 noheaders(), self.openedurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000301 except ftperrors(), msg:
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000302 raise IOError, ('ftp error', msg), sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000303
304
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000305# Derived class with handlers for errors we can handle (perhaps)
306class FancyURLopener(URLopener):
307
308 def __init__(self, *args):
309 apply(URLopener.__init__, (self,) + args)
310 self.auth_cache = {}
311
312 # Default error handling -- don't raise an exception
313 def http_error_default(self, url, fp, errcode, errmsg, headers):
Guido van Rossume6ad8911996-09-10 17:02:56 +0000314 return addinfourl(fp, headers, self.openedurl)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000315
Guido van Rossume6ad8911996-09-10 17:02:56 +0000316 # Error 302 -- relocated (temporarily)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000317 def http_error_302(self, url, fp, errcode, errmsg, headers):
318 # XXX The server can force infinite recursion here!
319 if headers.has_key('location'):
320 newurl = headers['location']
321 elif headers.has_key('uri'):
322 newurl = headers['uri']
323 else:
324 return
325 void = fp.read()
326 fp.close()
327 return self.open(newurl)
328
Guido van Rossume6ad8911996-09-10 17:02:56 +0000329 # Error 301 -- also relocated (permanently)
330 http_error_301 = http_error_302
331
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000332 # Error 401 -- authentication required
333 # See this URL for a description of the basic authentication scheme:
334 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
335 def http_error_401(self, url, fp, errcode, errmsg, headers):
336 if headers.has_key('www-authenticate'):
337 stuff = headers['www-authenticate']
338 p = regex.compile(
339 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
340 if p.match(stuff) >= 0:
341 scheme, realm = p.group(1, 2)
342 if string.lower(scheme) == 'basic':
343 return self.retry_http_basic_auth(
344 url, realm)
345
346 def retry_http_basic_auth(self, url, realm):
347 host, selector = splithost(url)
348 i = string.find(host, '@') + 1
349 host = host[i:]
350 user, passwd = self.get_user_passwd(host, realm, i)
351 if not (user or passwd): return None
352 host = user + ':' + passwd + '@' + host
353 newurl = '//' + host + selector
354 return self.open_http(newurl)
355
356 def get_user_passwd(self, host, realm, clear_cache = 0):
357 key = realm + '@' + string.lower(host)
358 if self.auth_cache.has_key(key):
359 if clear_cache:
360 del self.auth_cache[key]
361 else:
362 return self.auth_cache[key]
363 user, passwd = self.prompt_user_passwd(host, realm)
364 if user or passwd: self.auth_cache[key] = (user, passwd)
365 return user, passwd
366
367 def prompt_user_passwd(self, host, realm):
368 # Override this in a GUI environment!
369 try:
370 user = raw_input("Enter username for %s at %s: " %
371 (realm, host))
372 self.echo_off()
373 try:
374 passwd = raw_input(
375 "Enter password for %s in %s at %s: " %
376 (user, realm, host))
377 finally:
378 self.echo_on()
379 return user, passwd
380 except KeyboardInterrupt:
381 return None, None
382
383 def echo_off(self):
384 import os
385 os.system("stty -echo")
386
387 def echo_on(self):
388 import os
389 print
390 os.system("stty echo")
391
392
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000393# Utility functions
394
395# Return the IP address of the magic hostname 'localhost'
396_localhost = None
397def localhost():
398 global _localhost
399 if not _localhost:
400 _localhost = socket.gethostbyname('localhost')
401 return _localhost
402
403# Return the IP address of the current host
404_thishost = None
405def thishost():
406 global _thishost
407 if not _thishost:
408 _thishost = socket.gethostbyname(socket.gethostname())
409 return _thishost
410
411# Return the set of errors raised by the FTP class
412_ftperrors = None
413def ftperrors():
414 global _ftperrors
415 if not _ftperrors:
416 import ftplib
417 _ftperrors = (ftplib.error_reply,
418 ftplib.error_temp,
419 ftplib.error_perm,
420 ftplib.error_proto)
421 return _ftperrors
422
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000423# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000424_noheaders = None
425def noheaders():
426 global _noheaders
427 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000428 import mimetools
429 import StringIO
430 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000431 _noheaders.fp.close() # Recycle file descriptor
432 return _noheaders
433
434
435# Utility classes
436
437# Class used by open_ftp() for cache of open FTP connections
438class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000439 def __init__(self, user, passwd, host, port, dirs):
440 self.user = unquote(user or '')
441 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000442 self.host = host
443 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000444 self.dirs = []
445 for dir in dirs:
446 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000447 self.init()
448 def init(self):
449 import ftplib
450 self.ftp = ftplib.FTP()
451 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000452 self.ftp.login(self.user, self.passwd)
453 for dir in self.dirs:
454 self.ftp.cwd(dir)
455 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000456 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000457 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
458 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000459 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000460 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000461 except ftplib.all_errors:
462 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000463 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000464 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000465 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000466 try:
467 cmd = 'RETR ' + file
468 conn = self.ftp.transfercmd(cmd)
469 except ftplib.error_perm, reason:
470 if reason[:3] != '550':
Guido van Rossum3c8484e1996-11-20 22:02:24 +0000471 raise IOError, ('ftp error', reason), \
472 sys.exc_traceback
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000473 if not conn:
474 # Try a directory listing
475 if file: cmd = 'LIST ' + file
476 else: cmd = 'LIST'
477 conn = self.ftp.transfercmd(cmd)
Jack Jansen0d12ead1996-02-14 16:05:20 +0000478 return addclosehook(conn.makefile('rb'), self.ftp.voidresp)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000479
480# Base class for addinfo and addclosehook
481class addbase:
482 def __init__(self, fp):
483 self.fp = fp
484 self.read = self.fp.read
485 self.readline = self.fp.readline
486 self.readlines = self.fp.readlines
487 self.fileno = self.fp.fileno
488 def __repr__(self):
489 return '<%s at %s whose fp = %s>' % (
490 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000491 def close(self):
492 self.read = None
493 self.readline = None
494 self.readlines = None
495 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000496 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000497 self.fp = None
498
499# Class to add a close hook to an open file
500class addclosehook(addbase):
501 def __init__(self, fp, closehook, *hookargs):
502 addbase.__init__(self, fp)
503 self.closehook = closehook
504 self.hookargs = hookargs
505 def close(self):
506 if self.closehook:
507 apply(self.closehook, self.hookargs)
508 self.closehook = None
509 self.hookargs = None
510 addbase.close(self)
511
512# class to add an info() method to an open file
513class addinfo(addbase):
514 def __init__(self, fp, headers):
515 addbase.__init__(self, fp)
516 self.headers = headers
517 def info(self):
518 return self.headers
519
Guido van Rossume6ad8911996-09-10 17:02:56 +0000520# class to add info() and geturl() methods to an open file
521class addinfourl(addbase):
522 def __init__(self, fp, headers, url):
523 addbase.__init__(self, fp)
524 self.headers = headers
525 self.url = url
526 def info(self):
527 return self.headers
528 def geturl(self):
529 return self.url
530
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000531
532# Utility to combine a URL with a base URL to form a new URL
533
534def basejoin(base, url):
535 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000536 if type:
537 # if url is complete (i.e., it contains a type), return it
538 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000539 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000540 type, basepath = splittype(base) # inherit type from base
541 if host:
542 # if url contains host, just inherit type
543 if type: return type + '://' + host + path
544 else:
545 # no type inherited, so url must have started with //
546 # just return it
547 return url
548 host, basepath = splithost(basepath) # inherit host
549 basepath, basetag = splittag(basepath) # remove extraneuous cruft
550 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000551 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000552 # non-absolute path name
553 if path[:1] in ('#', '?'):
554 # path is just a tag or query, attach to basepath
555 i = len(basepath)
556 else:
557 # else replace last component
558 i = string.rfind(basepath, '/')
559 if i < 0:
560 # basepath not absolute
561 if host:
562 # host present, make absolute
563 basepath = '/'
564 else:
565 # else keep non-absolute
566 basepath = ''
567 else:
568 # remove last file component
569 basepath = basepath[:i+1]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000570 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000571 if type and host: return type + '://' + host + path
572 elif type: return type + ':' + path
573 elif host: return '//' + host + path # don't know what this means
574 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000575
576
Guido van Rossum7c395db1994-07-04 22:14:49 +0000577# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000578# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000579# splittype('type:opaquestring') --> 'type', 'opaquestring'
580# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000581# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
582# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000583# splitport('host:port') --> 'host', 'port'
584# splitquery('/path?query') --> '/path', 'query'
585# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000586# splitattr('/path;attr1=value1;attr2=value2;...') ->
587# '/path', ['attr1=value1', 'attr2=value2', ...]
588# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000589# splitgophertype('/Xselector') --> 'X', 'selector'
590# unquote('abc%20def') -> 'abc def'
591# quote('abc def') -> 'abc%20def')
592
593def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000594 url = string.strip(url)
595 if url[:1] == '<' and url[-1:] == '>':
596 url = string.strip(url[1:-1])
597 if url[:4] == 'URL:': url = string.strip(url[4:])
598 return url
599
600_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
601def splittype(url):
602 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
603 return None, url
604
605_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
606def splithost(url):
607 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
608 return None, url
609
Guido van Rossum7c395db1994-07-04 22:14:49 +0000610_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
611def splituser(host):
612 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
613 return None, host
614
615_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
616def splitpasswd(user):
617 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
618 return user, None
619
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000620_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
621def splitport(host):
622 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
623 return host, None
624
Guido van Rossum53725a21996-06-13 19:12:35 +0000625# Split host and port, returning numeric port.
626# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000627# Return numerical port if a valid number are found after ':'.
628# Return None if ':' but not a valid number.
629_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000630def splitnport(host, defport=-1):
631 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000632 host, port = _nportprog.group(1, 2)
633 try:
634 if not port: raise string.atoi_error, "no digits"
635 nport = string.atoi(port)
636 except string.atoi_error:
637 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000638 return host, nport
639 return host, defport
640
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000641_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
642def splitquery(url):
643 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
644 return url, None
645
646_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
647def splittag(url):
648 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
649 return url, None
650
Guido van Rossum7c395db1994-07-04 22:14:49 +0000651def splitattr(url):
652 words = string.splitfields(url, ';')
653 return words[0], words[1:]
654
655_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
656def splitvalue(attr):
657 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
658 return attr, None
659
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000660def splitgophertype(selector):
661 if selector[:1] == '/' and selector[1:2]:
662 return selector[1], selector[2:]
663 return None, selector
664
665_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
666def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000667 i = 0
668 n = len(s)
Guido van Rossumf8abb381996-08-26 15:56:12 +0000669 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000670 while 0 <= i < n:
671 j = _quoteprog.search(s, i)
672 if j < 0:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000673 res.append(s[i:])
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000674 break
Guido van Rossumf8abb381996-08-26 15:56:12 +0000675 res.append(s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000676 i = j+3
Guido van Rossumf8abb381996-08-26 15:56:12 +0000677 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000678
Guido van Rossum3bb54481994-08-29 10:52:58 +0000679always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000680def quote(s, safe = '/'):
681 safe = always_safe + safe
Guido van Rossumf8abb381996-08-26 15:56:12 +0000682 res = []
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000683 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000684 if c in safe:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000685 res.append(c)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000686 else:
Guido van Rossumf8abb381996-08-26 15:56:12 +0000687 res.append('%%%02x' % ord(c))
688 return string.joinfields(res, '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000689
Guido van Rossum442e7201996-03-20 15:33:11 +0000690
691# Proxy handling
692def getproxies():
693 """Return a dictionary of protocol scheme -> proxy server URL mappings.
694
695 Scan the environment for variables named <scheme>_proxy;
696 this seems to be the standard convention. If you need a
697 different way, you can pass a proxies dictionary to the
698 [Fancy]URLopener constructor.
699
700 """
701 proxies = {}
702 for name, value in os.environ.items():
703 if value and name[-6:] == '_proxy':
704 proxies[name[:-6]] = value
705 return proxies
706
707
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000708# Test and time quote() and unquote()
709def test1():
710 import time
711 s = ''
712 for i in range(256): s = s + chr(i)
713 s = s*4
714 t0 = time.time()
715 qs = quote(s)
716 uqs = unquote(qs)
717 t1 = time.time()
718 if uqs != s:
719 print 'Wrong!'
720 print `s`
721 print `qs`
722 print `uqs`
723 print round(t1 - t0, 3), 'sec'
724
725
726# Test program
727def test():
728 import sys
729 import regsub
730 args = sys.argv[1:]
731 if not args:
732 args = [
733 '/etc/passwd',
734 'file:/etc/passwd',
735 'file://localhost/etc/passwd',
736 'ftp://ftp.cwi.nl/etc/passwd',
737 'gopher://gopher.cwi.nl/11/',
738 'http://www.cwi.nl/index.html',
739 ]
740 try:
741 for url in args:
742 print '-'*10, url, '-'*10
743 fn, h = urlretrieve(url)
744 print fn, h
745 if h:
746 print '======'
747 for k in h.keys(): print k + ':', h[k]
748 print '======'
749 fp = open(fn, 'r')
750 data = fp.read()
751 del fp
752 print regsub.gsub('\r', '', data)
753 fn, h = None, None
754 print '-'*40
755 finally:
756 urlcleanup()
757
758# Run test program when run as a script
759if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000760## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000761 test()