| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 1 | # 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 Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 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 Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 13 | # 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 | |
| 17 | import socket |
| 18 | import regex |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 19 | |
| 20 | |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 21 | # 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 Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 30 | def urlopen(url): |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 31 | global _urlopener |
| 32 | if not _urlopener: |
| 33 | _urlopener = URLopener() |
| 34 | return _urlopener.open(url) |
| Guido van Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 35 | def urlretrieve(url): |
| 36 | global _urlopener |
| 37 | if not _urlopener: |
| 38 | _urlopener = URLopener() |
| 39 | return _urlopener.retrieve(url) |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 40 | |
| 41 | |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 42 | # 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 Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 45 | ftpcache = {} |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 46 | class URLopener: |
| 47 | |
| 48 | # Constructor |
| 49 | def __init__(self): |
| 50 | self.addheaders = [] |
| 51 | self.ftpcache = ftpcache |
| Guido van Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 52 | self.tempfiles = [] |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 53 | # 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 Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 57 | 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 Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 71 | # 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 Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 79 | type, url = splittype(unwrap(url)) |
| 80 | if not type: type = 'file' |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 81 | 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 Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 93 | # 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 Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 119 | # 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 Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 144 | 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 Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 151 | 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 Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 156 | return addinfo(open(file, 'r'), noheaders()) |
| 157 | raise IOError, ('local file error', 'not on local host') |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 158 | |
| 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 |
| 181 | def 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 |
| 189 | def 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 |
| 197 | def 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 |
| 209 | def 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 Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 216 | |
| 217 | |
| 218 | # Utility classes |
| 219 | |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 220 | # Class used by open_ftp() for cache of open FTP connections |
| 221 | class ftpwrapper: |
| 222 | def __init__(self, host, port): |
| 223 | self.host = host |
| 224 | self.port = port |
| 225 | self.init() |
| 226 | def init(self): |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 227 | import ftplib |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 228 | self.ftp = ftplib.FTP() |
| 229 | self.ftp.connect(self.host, self.port) |
| 230 | self.ftp.login() |
| 231 | def retrfile(self, file): |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 232 | import ftplib |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 233 | 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 Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 248 | if file: cmd = 'LIST ' + file |
| 249 | else: cmd = 'LIST' |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 250 | conn = self.ftp.transfercmd(cmd) |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 251 | return addclosehook(conn.makefile('r'), self.ftp.voidresp) |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 252 | |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 253 | # Base class for addinfo and addclosehook |
| 254 | class addbase: |
| 255 | def __init__(self, fp): |
| 256 | self.fp = fp |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 257 | self.read = self.fp.read |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 258 | self.readline = self.fp.readline |
| 259 | self.readlines = self.fp.readlines |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 260 | self.fileno = self.fp.fileno |
| 261 | def __del__(self): |
| 262 | self.close() |
| 263 | def close(self): |
| Guido van Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 264 | self.read = None |
| 265 | self.readline = None |
| 266 | self.readlines = None |
| 267 | self.fileno = None |
| 268 | self.fp.close() |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 269 | self.fp = None |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 270 | |
| 271 | # Class to add a close hook to an open file |
| 272 | class 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 Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 281 | self.hookargs = None |
| 282 | addbase.close(self) |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 283 | |
| 284 | # class to add an info() method to an open file |
| 285 | class 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 Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 291 | |
| 292 | |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 293 | # Utilities to parse URLs: |
| Guido van Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 294 | # unwrap('<URL:type//host/path>') --> 'type//host/path' |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 295 | # 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 Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 302 | def 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 Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 310 | _typeprog = regex.compile('^\([^/:]+\):\(.*\)$') |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 311 | def splittype(url): |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 312 | if _typeprog.match(url) >= 0: return _typeprog.group(1, 2) |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 313 | return None, url |
| 314 | |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 315 | _hostprog = regex.compile('^//\([^/]+\)\(.*\)$') |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 316 | def splithost(url): |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 317 | if _hostprog.match(url) >= 0: return _hostprog.group(1, 2) |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 318 | return None, url |
| 319 | |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 320 | _portprog = regex.compile('^\(.*\):\([0-9]+\)$') |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 321 | def splitport(host): |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 322 | if _portprog.match(host) >= 0: return _portprog.group(1, 2) |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 323 | return host, None |
| 324 | |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 325 | _queryprog = regex.compile('^\(.*\)\?\([^?]*\)$') |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 326 | def splitquery(url): |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 327 | if _queryprog.match(url) >= 0: return _queryprog.group(1, 2) |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 328 | return url, None |
| 329 | |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 330 | _tagprog = regex.compile('^\(.*\)#\([^#]*\)$') |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 331 | def splittag(url): |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 332 | if _tagprog.match(url) >= 0: return _tagprog.group(1, 2) |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 333 | return url, None |
| 334 | |
| 335 | def 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 |
| 342 | def test(): |
| 343 | import sys |
| Guido van Rossum | 749057b | 1994-02-22 19:03:38 +0000 | [diff] [blame] | 344 | import regsub |
| Guido van Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 345 | 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 Rossum | d5b9ea1 | 1994-02-24 13:50:39 +0000 | [diff] [blame^] | 355 | 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 Rossum | 23acc95 | 1994-02-21 16:36:04 +0000 | [diff] [blame] | 370 | |
| 371 | # Run test program when run as a script |
| 372 | if __name__ == '__main__': |
| 373 | test() |