blob: 2b2729df099b1f7411414329ee9943a4775425d3 [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 Rossum23acc951994-02-21 16:36:04 +000035
36
Guido van Rossum749057b1994-02-22 19:03:38 +000037# Class to open URLs.
38# This is a class rather than just a subroutine because we may need
39# more than one set of global protocol-specific options.
Guido van Rossum23acc951994-02-21 16:36:04 +000040ftpcache = {}
Guido van Rossum749057b1994-02-22 19:03:38 +000041class URLopener:
42
43 # Constructor
44 def __init__(self):
45 self.addheaders = []
46 self.ftpcache = ftpcache
47 # Undocumented feature: you can use a different
48 # ftp cache by assigning to the .ftpcache member;
49 # in case you want logically independent URL openers
50
51 # Add a header to be used by the HTTP interface only
52 # e.g. u.addheader('Accept', 'sound/basic')
53 def addheader(self, *args):
54 self.addheaders.append(args)
55
56 # External interface
57 # Use URLopener().open(file) instead of open(file, 'r')
58 def open(self, url):
59 import string
60 url = string.strip(url)
61 if url[:1] == '<' and url[-1:] == '>':
62 url = string.strip(url[1:-1])
63 if url[:4] == 'URL:': url = string.strip(url[4:])
64 type, url = splittype(url)
65 if not type: type = 'file'
66 name = 'open_' + type
67 if '-' in name:
68 import regsub
69 name = regsub.gsub('-', '_', name)
70 if not hasattr(self, name):
71 raise IOError, ('url error', 'unknown url type', type)
72 meth = getattr(self, name)
73 try:
74 return meth(url)
75 except socket.error, msg:
76 raise IOError, ('socket error', msg)
77
78 # Each method named open_<type> knows how to open that type of URL
79
80 # Use HTTP protocol
81 def open_http(self, url):
82 import httplib
83 host, selector = splithost(url)
84 h = httplib.HTTP(host)
85 h.putrequest('GET', selector)
86 for args in self.addheaders: apply(h.putheader, args)
87 errcode, errmsg, headers = h.getreply()
88 if errcode == 200: return addinfo(h.getfile(), headers)
89 else: raise IOError, ('http error', errcode, errmsg, headers)
90
91 # Use Gopher protocol
92 def open_gopher(self, url):
93 import gopherlib
94 host, selector = splithost(url)
95 type, selector = splitgophertype(selector)
96 selector, query = splitquery(selector)
97 if query: fp = gopherlib.send_query(selector, query, host)
98 else: fp = gopherlib.send_selector(selector, host)
99 return addinfo(fp, noheaders())
100
101 # Use local file or FTP depending on form of URL
102 def open_file(self, url):
103 host, file = splithost(url)
104 if not host: return addinfo(open(file, 'r'), noheaders())
105 host, port = splitport(host)
106 if not port and socket.gethostbyname(host) in (
107 localhost(), thishost()):
108 try: fp = open(file, 'r')
109 except IOError: fp = None
110 if fp: return addinfo(fp, noheaders())
111 return self.open_ftp(url)
112
113 # Use FTP protocol
114 def open_ftp(self, url):
115 host, file = splithost(url)
116 host, port = splitport(host)
117 host = socket.gethostbyname(host)
118 if not port:
119 import ftplib
120 port = ftplib.FTP_PORT
121 key = (host, port)
122 try:
123 if not self.ftpcache.has_key(key):
124 self.ftpcache[key] = ftpwrapper(host, port)
125 return addinfo(self.ftpcache[key].retrfile(file),
126 noheaders())
127 except ftperrors(), msg:
128 raise IOError, ('ftp error', msg)
129
130
131# Utility functions
132
133# Return the IP address of the magic hostname 'localhost'
134_localhost = None
135def localhost():
136 global _localhost
137 if not _localhost:
138 _localhost = socket.gethostbyname('localhost')
139 return _localhost
140
141# Return the IP address of the current host
142_thishost = None
143def thishost():
144 global _thishost
145 if not _thishost:
146 _thishost = socket.gethostbyname(socket.gethostname())
147 return _thishost
148
149# Return the set of errors raised by the FTP class
150_ftperrors = None
151def ftperrors():
152 global _ftperrors
153 if not _ftperrors:
154 import ftplib
155 _ftperrors = (ftplib.error_reply,
156 ftplib.error_temp,
157 ftplib.error_perm,
158 ftplib.error_proto)
159 return _ftperrors
160
161# Return an empty rfc822.Message object
162_noheaders = None
163def noheaders():
164 global _noheaders
165 if not _noheaders:
166 import rfc822
167 _noheaders = rfc822.Message(open('/dev/null', 'r'))
168 _noheaders.fp.close() # Recycle file descriptor
169 return _noheaders
Guido van Rossum23acc951994-02-21 16:36:04 +0000170
171
172# Utility classes
173
Guido van Rossum23acc951994-02-21 16:36:04 +0000174# Class used by open_ftp() for cache of open FTP connections
175class ftpwrapper:
176 def __init__(self, host, port):
177 self.host = host
178 self.port = port
179 self.init()
180 def init(self):
Guido van Rossum749057b1994-02-22 19:03:38 +0000181 import ftplib
Guido van Rossum23acc951994-02-21 16:36:04 +0000182 self.ftp = ftplib.FTP()
183 self.ftp.connect(self.host, self.port)
184 self.ftp.login()
185 def retrfile(self, file):
Guido van Rossum749057b1994-02-22 19:03:38 +0000186 import ftplib
Guido van Rossum23acc951994-02-21 16:36:04 +0000187 try:
188 self.ftp.voidcmd('TYPE I')
189 except ftplib.all_errors:
190 self.init()
191 self.ftp.voidcmd('TYPE I')
192 conn = None
193 if file:
194 try:
195 cmd = 'RETR ' + file
196 conn = self.ftp.transfercmd(cmd)
197 except ftplib.error_perm, reason:
198 if reason[:3] != '550':
199 raise IOError, ('ftp error', reason)
200 if not conn:
201 # Try a directory listing
202 if file: cmd = 'NLST ' + file
203 else: cmd = 'NLST'
204 conn = self.ftp.transfercmd(cmd)
Guido van Rossum749057b1994-02-22 19:03:38 +0000205 return addclosehook(conn.makefile('r'), self.ftp.voidresp)
Guido van Rossum23acc951994-02-21 16:36:04 +0000206
Guido van Rossum749057b1994-02-22 19:03:38 +0000207# Base class for addinfo and addclosehook
208class addbase:
209 def __init__(self, fp):
210 self.fp = fp
Guido van Rossum23acc951994-02-21 16:36:04 +0000211 self.read = self.fp.read
Guido van Rossum749057b1994-02-22 19:03:38 +0000212 self.readline = self.fp.readline
213 self.readlines = self.fp.readlines
Guido van Rossum23acc951994-02-21 16:36:04 +0000214 self.fileno = self.fp.fileno
215 def __del__(self):
216 self.close()
217 def close(self):
Guido van Rossum23acc951994-02-21 16:36:04 +0000218 self.fp = None
Guido van Rossum749057b1994-02-22 19:03:38 +0000219
220# Class to add a close hook to an open file
221class addclosehook(addbase):
222 def __init__(self, fp, closehook, *hookargs):
223 addbase.__init__(self, fp)
224 self.closehook = closehook
225 self.hookargs = hookargs
226 def close(self):
227 if self.closehook:
228 apply(self.closehook, self.hookargs)
229 self.closehook = None
230 self.fp = None
231
232# class to add an info() method to an open file
233class addinfo(addbase):
234 def __init__(self, fp, headers):
235 addbase.__init__(self, fp)
236 self.headers = headers
237 def info(self):
238 return self.headers
Guido van Rossum23acc951994-02-21 16:36:04 +0000239
240
Guido van Rossum749057b1994-02-22 19:03:38 +0000241# Utilities to parse URLs:
Guido van Rossum23acc951994-02-21 16:36:04 +0000242# splittype('type:opaquestring') --> 'type', 'opaquestring'
243# splithost('//host[:port]/path') --> 'host[:port]', '/path'
244# splitport('host:port') --> 'host', 'port'
245# splitquery('/path?query') --> '/path', 'query'
246# splittag('/path#tag') --> '/path', 'tag'
247# splitgophertype('/Xselector') --> 'X', 'selector'
248
Guido van Rossum749057b1994-02-22 19:03:38 +0000249_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000250def splittype(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000251 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000252 return None, url
253
Guido van Rossum749057b1994-02-22 19:03:38 +0000254_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000255def splithost(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000256 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000257 return None, url
258
Guido van Rossum749057b1994-02-22 19:03:38 +0000259_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000260def splitport(host):
Guido van Rossum749057b1994-02-22 19:03:38 +0000261 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000262 return host, None
263
Guido van Rossum749057b1994-02-22 19:03:38 +0000264_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000265def splitquery(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000266 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000267 return url, None
268
Guido van Rossum749057b1994-02-22 19:03:38 +0000269_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
Guido van Rossum23acc951994-02-21 16:36:04 +0000270def splittag(url):
Guido van Rossum749057b1994-02-22 19:03:38 +0000271 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
Guido van Rossum23acc951994-02-21 16:36:04 +0000272 return url, None
273
274def splitgophertype(selector):
275 if selector[:1] == '/' and selector[1:2]:
276 return selector[1], selector[2:]
277 return None, selector
278
279
280# Test program
281def test():
282 import sys
Guido van Rossum749057b1994-02-22 19:03:38 +0000283 import regsub
Guido van Rossum23acc951994-02-21 16:36:04 +0000284 args = sys.argv[1:]
285 if not args:
286 args = [
287 '/etc/passwd',
288 'file:/etc/passwd',
289 'file://localhost/etc/passwd',
290 'ftp://ftp.cwi.nl/etc/passwd',
291 'gopher://gopher.cwi.nl/11/',
292 'http://www.cwi.nl/index.html',
293 ]
294 for arg in args:
295 print '-'*10, arg, '-'*10
296 print regsub.gsub('\r', '', urlopen(arg).read())
297 print '-'*40
298
299# Run test program when run as a script
300if __name__ == '__main__':
301 test()