blob: bb0c45ecc94f2ddf1fd4e928132a91799a148012 [file] [log] [blame]
Guido van Rossum23acc951994-02-21 16:36:04 +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#
Guido van Rossum749057b1994-02-22 19:03:38 +00009# 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 Rossum23acc951994-02-21 16:36:04 +000013# The info() method returns an rfc822.Message object which can be
14# used to query various info about the object, if available.
15# (rfc822.Message objects are queried with the getheader() method.)
16
17import socket
18import regex
Guido van Rossum23acc951994-02-21 16:36:04 +000019
20
Guido van Rossum749057b1994-02-22 19:03:38 +000021# This really consists of two pieces:
22# (1) a class which handles opening of all sorts of URLs
23# (plus assorted utilities etc.)
24# (2) a set of functions for parsing URLs
25# XXX Should these be separated out into different modules?
26
27
28# Shortcut for basic usage
29_urlopener = None
Guido van Rossum23acc951994-02-21 16:36:04 +000030def urlopen(url):
Guido van Rossum749057b1994-02-22 19:03:38 +000031 global _urlopener
32 if not _urlopener:
33 _urlopener = URLopener()
34 return _urlopener.open(url)
Guido van Rossumd5b9ea11994-02-24 13:50:39 +000035def urlretrieve(url):
36 global _urlopener
37 if not _urlopener:
38 _urlopener = URLopener()
39 return _urlopener.retrieve(url)
Guido van Rossum23acc951994-02-21 16:36:04 +000040
41
Guido van Rossum749057b1994-02-22 19:03:38 +000042# Class to open URLs.
43# This is a class rather than just a subroutine because we may need
44# more than one set of global protocol-specific options.
Guido van Rossum23acc951994-02-21 16:36:04 +000045ftpcache = {}
Guido van Rossum749057b1994-02-22 19:03:38 +000046class URLopener:
47
48 # Constructor
49 def __init__(self):
50 self.addheaders = []
Guido van Rossumd5b9ea11994-02-24 13:50:39 +000051 self.tempfiles = []
Guido van Rossum914973a1994-02-24 15:55:43 +000052 self.ftpcache = ftpcache
Guido van Rossum749057b1994-02-22 19:03:38 +000053 # Undocumented feature: you can use a different
54 # ftp cache by assigning to the .ftpcache member;
55 # in case you want logically independent URL openers
56
Guido van Rossumd5b9ea11994-02-24 13:50:39 +000057 def __del__(self):
58 self.close()
59
60 def close(self):
61 self.cleanup()
62
63 def cleanup(self):
64 import os
65 for tfn in self.tempfiles:
66 try:
67 os.unlink(tfn)
68 except os.error:
69 pass
70
Guido van Rossum749057b1994-02-22 19:03:38 +000071 # Add a header to be used by the HTTP interface only
72 # e.g. u.addheader('Accept', 'sound/basic')
73 def addheader(self, *args):
74 self.addheaders.append(args)
75
76 # External interface
77 # Use URLopener().open(file) instead of open(file, 'r')
78 def open(self, url):
Guido van Rossumd5b9ea11994-02-24 13:50:39 +000079 type, url = splittype(unwrap(url))
80 if not type: type = 'file'
Guido van Rossum749057b1994-02-22 19:03:38 +000081 name = 'open_' + type
82 if '-' in name:
83 import regsub
84 name = regsub.gsub('-', '_', name)
85 if not hasattr(self, name):
86 raise IOError, ('url error', 'unknown url type', type)
Guido van Rossum749057b1994-02-22 19:03:38 +000087 try:
Guido van Rossum914973a1994-02-24 15:55:43 +000088 return getattr(self, name)(url)
Guido van Rossum749057b1994-02-22 19:03:38 +000089 except socket.error, msg:
90 raise IOError, ('socket error', msg)
91
Guido van Rossumd5b9ea11994-02-24 13:50:39 +000092 # External interface
93 # retrieve(url) returns (filename, None) for a local object
94 # or (tempfilename, headers) for a remote object
95 def retrieve(self, url):
96 type, url1 = splittype(unwrap(url))
97 if not type or type == 'file':
98 try:
99 fp = self.open_local_file(url1)
Guido van Rossum914973a1994-02-24 15:55:43 +0000100 del fp
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000101 return splithost(url1)[1], None
102 except IOError, msg:
103 pass
104 fp = self.open(url)
105 import tempfile
106 tfn = tempfile.mktemp()
107 self.tempfiles.append(tfn)
108 tfp = open(tfn, 'w')
109 bs = 1024*8
110 block = fp.read(bs)
111 while block:
112 tfp.write(block)
113 block = fp.read(bs)
114 headers = fp.info()
Guido van Rossum914973a1994-02-24 15:55:43 +0000115 del fp
116 del tfp
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000117 return tfn, headers
118
Guido van Rossum749057b1994-02-22 19:03:38 +0000119 # Each method named open_<type> knows how to open that type of URL
120
121 # Use HTTP protocol
122 def open_http(self, url):
123 import httplib
124 host, selector = splithost(url)
125 h = httplib.HTTP(host)
126 h.putrequest('GET', selector)
127 for args in self.addheaders: apply(h.putheader, args)
128 errcode, errmsg, headers = h.getreply()
129 if errcode == 200: return addinfo(h.getfile(), headers)
130 else: raise IOError, ('http error', errcode, errmsg, headers)
131
132 # Use Gopher protocol
133 def open_gopher(self, url):
134 import gopherlib
135 host, selector = splithost(url)
136 type, selector = splitgophertype(selector)
137 selector, query = splitquery(selector)
138 if query: fp = gopherlib.send_query(selector, query, host)
139 else: fp = gopherlib.send_selector(selector, host)
140 return addinfo(fp, noheaders())
141
142 # Use local file or FTP depending on form of URL
143 def open_file(self, url):
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000144 try:
145 return self.open_local_file(url)
146 except IOError:
147 return self.open_ftp(url)
148
149 # Use local file
150 def open_local_file(self, url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000151 host, file = splithost(url)
152 if not host: return addinfo(open(file, 'r'), noheaders())
153 host, port = splitport(host)
154 if not port and socket.gethostbyname(host) in (
155 localhost(), thishost()):
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000156 return addinfo(open(file, 'r'), noheaders())
157 raise IOError, ('local file error', 'not on local host')
Guido van Rossum749057b1994-02-22 19:03:38 +0000158
159 # Use FTP protocol
160 def open_ftp(self, url):
161 host, file = splithost(url)
162 host, port = splitport(host)
163 host = socket.gethostbyname(host)
164 if not port:
165 import ftplib
166 port = ftplib.FTP_PORT
167 key = (host, port)
168 try:
169 if not self.ftpcache.has_key(key):
170 self.ftpcache[key] = ftpwrapper(host, port)
171 return addinfo(self.ftpcache[key].retrfile(file),
172 noheaders())
173 except ftperrors(), msg:
174 raise IOError, ('ftp error', msg)
175
176
177# Utility functions
178
179# Return the IP address of the magic hostname 'localhost'
180_localhost = None
181def localhost():
182 global _localhost
183 if not _localhost:
184 _localhost = socket.gethostbyname('localhost')
185 return _localhost
186
187# Return the IP address of the current host
188_thishost = None
189def thishost():
190 global _thishost
191 if not _thishost:
192 _thishost = socket.gethostbyname(socket.gethostname())
193 return _thishost
194
195# Return the set of errors raised by the FTP class
196_ftperrors = None
197def ftperrors():
198 global _ftperrors
199 if not _ftperrors:
200 import ftplib
201 _ftperrors = (ftplib.error_reply,
202 ftplib.error_temp,
203 ftplib.error_perm,
204 ftplib.error_proto)
205 return _ftperrors
206
207# Return an empty rfc822.Message object
208_noheaders = None
209def noheaders():
210 global _noheaders
211 if not _noheaders:
212 import rfc822
213 _noheaders = rfc822.Message(open('/dev/null', 'r'))
214 _noheaders.fp.close() # Recycle file descriptor
215 return _noheaders
Guido van Rossum23acc951994-02-21 16:36:04 +0000216
217
218# Utility classes
219
Guido van Rossum23acc951994-02-21 16:36:04 +0000220# Class used by open_ftp() for cache of open FTP connections
221class ftpwrapper:
222 def __init__(self, host, port):
223 self.host = host
224 self.port = port
225 self.init()
226 def init(self):
Guido van Rossum749057b1994-02-22 19:03:38 +0000227 import ftplib
Guido van Rossum23acc951994-02-21 16:36:04 +0000228 self.ftp = ftplib.FTP()
229 self.ftp.connect(self.host, self.port)
230 self.ftp.login()
231 def retrfile(self, file):
Guido van Rossum749057b1994-02-22 19:03:38 +0000232 import ftplib
Guido van Rossum23acc951994-02-21 16:36:04 +0000233 try:
234 self.ftp.voidcmd('TYPE I')
235 except ftplib.all_errors:
236 self.init()
237 self.ftp.voidcmd('TYPE I')
238 conn = None
239 if file:
240 try:
241 cmd = 'RETR ' + file
242 conn = self.ftp.transfercmd(cmd)
243 except ftplib.error_perm, reason:
244 if reason[:3] != '550':
245 raise IOError, ('ftp error', reason)
246 if not conn:
247 # Try a directory listing
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000248 if file: cmd = 'LIST ' + file
249 else: cmd = 'LIST'
Guido van Rossum23acc951994-02-21 16:36:04 +0000250 conn = self.ftp.transfercmd(cmd)
Guido van Rossum749057b1994-02-22 19:03:38 +0000251 return addclosehook(conn.makefile('r'), self.ftp.voidresp)
Guido van Rossum23acc951994-02-21 16:36:04 +0000252
Guido van Rossum749057b1994-02-22 19:03:38 +0000253# Base class for addinfo and addclosehook
254class addbase:
255 def __init__(self, fp):
256 self.fp = fp
Guido van Rossum23acc951994-02-21 16:36:04 +0000257 self.read = self.fp.read
Guido van Rossum749057b1994-02-22 19:03:38 +0000258 self.readline = self.fp.readline
259 self.readlines = self.fp.readlines
Guido van Rossum23acc951994-02-21 16:36:04 +0000260 self.fileno = self.fp.fileno
Guido van Rossum914973a1994-02-24 15:55:43 +0000261 def __repr__(self):
262 return '<%s at %s whose fp = %s>' % (
263 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum23acc951994-02-21 16:36:04 +0000264 def __del__(self):
265 self.close()
266 def close(self):
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000267 self.read = None
268 self.readline = None
269 self.readlines = None
270 self.fileno = None
Guido van Rossum23acc951994-02-21 16:36:04 +0000271 self.fp = None
Guido van Rossum749057b1994-02-22 19:03:38 +0000272
273# Class to add a close hook to an open file
274class addclosehook(addbase):
275 def __init__(self, fp, closehook, *hookargs):
276 addbase.__init__(self, fp)
277 self.closehook = closehook
278 self.hookargs = hookargs
279 def close(self):
280 if self.closehook:
281 apply(self.closehook, self.hookargs)
282 self.closehook = None
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000283 self.hookargs = None
284 addbase.close(self)
Guido van Rossum749057b1994-02-22 19:03:38 +0000285
286# class to add an info() method to an open file
287class addinfo(addbase):
288 def __init__(self, fp, headers):
289 addbase.__init__(self, fp)
290 self.headers = headers
291 def info(self):
292 return self.headers
Guido van Rossum23acc951994-02-21 16:36:04 +0000293
294
Guido van Rossum749057b1994-02-22 19:03:38 +0000295# Utilities to parse URLs:
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000296# unwrap('<URL:type//host/path>') --> 'type//host/path'
Guido van Rossum23acc951994-02-21 16:36:04 +0000297# splittype('type:opaquestring') --> 'type', 'opaquestring'
298# splithost('//host[:port]/path') --> 'host[:port]', '/path'
299# splitport('host:port') --> 'host', 'port'
300# splitquery('/path?query') --> '/path', 'query'
301# splittag('/path#tag') --> '/path', 'tag'
302# splitgophertype('/Xselector') --> 'X', 'selector'
303
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000304def unwrap(url):
305 import string
306 url = string.strip(url)
307 if url[:1] == '<' and url[-1:] == '>':
308 url = string.strip(url[1:-1])
309 if url[:4] == 'URL:': url = string.strip(url[4:])
310 return url
311
Guido van Rossum749057b1994-02-22 19:03:38 +0000312_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000313def splittype(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000314 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000315 return None, url
316
Guido van Rossum749057b1994-02-22 19:03:38 +0000317_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000318def splithost(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000319 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000320 return None, url
321
Guido van Rossum749057b1994-02-22 19:03:38 +0000322_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000323def splitport(host):
Guido van Rossum749057b1994-02-22 19:03:38 +0000324 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000325 return host, None
326
Guido van Rossum749057b1994-02-22 19:03:38 +0000327_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000328def splitquery(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000329 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000330 return url, None
331
Guido van Rossum749057b1994-02-22 19:03:38 +0000332_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000333def splittag(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000334 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000335 return url, None
336
337def splitgophertype(selector):
338 if selector[:1] == '/' and selector[1:2]:
339 return selector[1], selector[2:]
340 return None, selector
341
342
343# Test program
344def test():
345 import sys
Guido van Rossum749057b1994-02-22 19:03:38 +0000346 import regsub
Guido van Rossum23acc951994-02-21 16:36:04 +0000347 args = sys.argv[1:]
348 if not args:
349 args = [
350 '/etc/passwd',
351 'file:/etc/passwd',
352 'file://localhost/etc/passwd',
353 'ftp://ftp.cwi.nl/etc/passwd',
354 'gopher://gopher.cwi.nl/11/',
355 'http://www.cwi.nl/index.html',
356 ]
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000357 try:
358 for url in args:
359 print '-'*10, url, '-'*10
360 fn, h = urlretrieve(url)
361 print fn, h
362 if h:
363 print '======'
364 for k in h.keys(): print k + ':', h[k]
365 print '======'
366 fp = open(fn, 'r')
367 data = fp.read()
Guido van Rossum914973a1994-02-24 15:55:43 +0000368 del fp
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000369 print regsub.gsub('\r', '', data)
Guido van Rossum914973a1994-02-24 15:55:43 +0000370 fn, h = None, None
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000371 print '-'*40
372 finally:
373 _urlopener.cleanup()
Guido van Rossum23acc951994-02-21 16:36:04 +0000374
375# Run test program when run as a script
376if __name__ == '__main__':
377 test()