blob: 0366bda4534c8db38948a5f4611a8aaa3ab914a4 [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 = []
51 self.ftpcache = ftpcache
Guido van Rossumd5b9ea11994-02-24 13:50:39 +000052 self.tempfiles = []
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)
87 meth = getattr(self, name)
88 try:
89 return meth(url)
90 except socket.error, msg:
91 raise IOError, ('socket error', msg)
92
Guido van Rossumd5b9ea11994-02-24 13:50:39 +000093 # External interface
94 # retrieve(url) returns (filename, None) for a local object
95 # or (tempfilename, headers) for a remote object
96 def retrieve(self, url):
97 type, url1 = splittype(unwrap(url))
98 if not type or type == 'file':
99 try:
100 fp = self.open_local_file(url1)
101 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()
115 fp.close()
116 tfp.close()
117 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
261 def __del__(self):
262 self.close()
263 def close(self):
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000264 self.read = None
265 self.readline = None
266 self.readlines = None
267 self.fileno = None
268 self.fp.close()
Guido van Rossum23acc951994-02-21 16:36:04 +0000269 self.fp = None
Guido van Rossum749057b1994-02-22 19:03:38 +0000270
271# Class to add a close hook to an open file
272class addclosehook(addbase):
273 def __init__(self, fp, closehook, *hookargs):
274 addbase.__init__(self, fp)
275 self.closehook = closehook
276 self.hookargs = hookargs
277 def close(self):
278 if self.closehook:
279 apply(self.closehook, self.hookargs)
280 self.closehook = None
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000281 self.hookargs = None
282 addbase.close(self)
Guido van Rossum749057b1994-02-22 19:03:38 +0000283
284# class to add an info() method to an open file
285class addinfo(addbase):
286 def __init__(self, fp, headers):
287 addbase.__init__(self, fp)
288 self.headers = headers
289 def info(self):
290 return self.headers
Guido van Rossum23acc951994-02-21 16:36:04 +0000291
292
Guido van Rossum749057b1994-02-22 19:03:38 +0000293# Utilities to parse URLs:
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000294# unwrap('<URL:type//host/path>') --> 'type//host/path'
Guido van Rossum23acc951994-02-21 16:36:04 +0000295# splittype('type:opaquestring') --> 'type', 'opaquestring'
296# splithost('//host[:port]/path') --> 'host[:port]', '/path'
297# splitport('host:port') --> 'host', 'port'
298# splitquery('/path?query') --> '/path', 'query'
299# splittag('/path#tag') --> '/path', 'tag'
300# splitgophertype('/Xselector') --> 'X', 'selector'
301
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000302def unwrap(url):
303 import string
304 url = string.strip(url)
305 if url[:1] == '<' and url[-1:] == '>':
306 url = string.strip(url[1:-1])
307 if url[:4] == 'URL:': url = string.strip(url[4:])
308 return url
309
Guido van Rossum749057b1994-02-22 19:03:38 +0000310_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000311def splittype(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000312 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000313 return None, url
314
Guido van Rossum749057b1994-02-22 19:03:38 +0000315_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000316def splithost(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000317 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000318 return None, url
319
Guido van Rossum749057b1994-02-22 19:03:38 +0000320_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000321def splitport(host):
Guido van Rossum749057b1994-02-22 19:03:38 +0000322 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000323 return host, None
324
Guido van Rossum749057b1994-02-22 19:03:38 +0000325_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000326def splitquery(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000327 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000328 return url, None
329
Guido van Rossum749057b1994-02-22 19:03:38 +0000330_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000331def splittag(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000332 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000333 return url, None
334
335def splitgophertype(selector):
336 if selector[:1] == '/' and selector[1:2]:
337 return selector[1], selector[2:]
338 return None, selector
339
340
341# Test program
342def test():
343 import sys
Guido van Rossum749057b1994-02-22 19:03:38 +0000344 import regsub
Guido van Rossum23acc951994-02-21 16:36:04 +0000345 args = sys.argv[1:]
346 if not args:
347 args = [
348 '/etc/passwd',
349 'file:/etc/passwd',
350 'file://localhost/etc/passwd',
351 'ftp://ftp.cwi.nl/etc/passwd',
352 'gopher://gopher.cwi.nl/11/',
353 'http://www.cwi.nl/index.html',
354 ]
Guido van Rossumd5b9ea11994-02-24 13:50:39 +0000355 try:
356 for url in args:
357 print '-'*10, url, '-'*10
358 fn, h = urlretrieve(url)
359 print fn, h
360 if h:
361 print '======'
362 for k in h.keys(): print k + ':', h[k]
363 print '======'
364 fp = open(fn, 'r')
365 data = fp.read()
366 print regsub.gsub('\r', '', data)
367 print '-'*40
368 finally:
369 _urlopener.cleanup()
Guido van Rossum23acc951994-02-21 16:36:04 +0000370
371# Run test program when run as a script
372if __name__ == '__main__':
373 test()