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 | # |
| 9 | # The object returned by urlopen() will differ per protocol. |
| 10 | # All you know is that is has methods read(), fileno(), close() and info(). |
| 11 | # The read(), fileno() and close() methods work like those of open files. |
| 12 | # The info() method returns an rfc822.Message object which can be |
| 13 | # used to query various info about the object, if available. |
| 14 | # (rfc822.Message objects are queried with the getheader() method.) |
| 15 | |
| 16 | import socket |
| 17 | import regex |
| 18 | import regsub |
| 19 | import string |
| 20 | import rfc822 |
| 21 | import ftplib |
| 22 | |
| 23 | |
| 24 | # External interface -- use urlopen(file) as if it were open(file, 'r') |
| 25 | def urlopen(url): |
| 26 | url = string.strip(url) |
| 27 | if url[:1] == '<' and url[-1:] == '>': url = string.strip(url[1:-1]) |
| 28 | if url[:4] == 'URL:': url = string.strip(url[4:]) |
| 29 | type, url = splittype(url) |
| 30 | if not type: type = 'file' |
| 31 | type = regsub.gsub('-', '_', type) |
| 32 | try: |
| 33 | func = eval('open_' + type) |
| 34 | except NameError: |
| 35 | raise IOError, ('url error', 'unknown url type', type) |
| 36 | try: |
| 37 | return func(url) |
| 38 | except socket.error, msg: |
| 39 | raise IOError, ('socket error', msg) |
| 40 | |
| 41 | |
| 42 | # Each routine of the form open_<type> knows how to open that type of URL |
| 43 | |
| 44 | # Use HTTP protocol |
| 45 | def open_http(url): |
| 46 | import httplib |
| 47 | host, selector = splithost(url) |
| 48 | h = httplib.HTTP(host) |
| 49 | h.putrequest('GET', selector) |
| 50 | errcode, errmsg, headers = h.getreply() |
| 51 | if errcode == 200: return makefile(h.getfile(), headers) |
| 52 | else: raise IOError, ('http error', errcode, errmsg, headers) |
| 53 | |
| 54 | # Empty rfc822.Message object |
| 55 | noheaders = rfc822.Message(open('/dev/null', 'r')) |
| 56 | noheaders.fp.close() # Recycle file descriptor |
| 57 | |
| 58 | # Use Gopher protocol |
| 59 | def open_gopher(url): |
| 60 | import gopherlib |
| 61 | host, selector = splithost(url) |
| 62 | type, selector = splitgophertype(selector) |
| 63 | selector, query = splitquery(selector) |
| 64 | if query: fp = gopherlib.send_query(selector, query, host) |
| 65 | else: fp = gopherlib.send_selector(selector, host) |
| 66 | return makefile(fp, noheaders) |
| 67 | |
| 68 | # Use local file or FTP depending on form of URL |
| 69 | localhost = socket.gethostbyname('localhost') |
| 70 | thishost = socket.gethostbyname(socket.gethostname()) |
| 71 | def open_file(url): |
| 72 | host, file = splithost(url) |
| 73 | if not host: return makefile(open(file, 'r'), noheaders) |
| 74 | host, port = splitport(host) |
| 75 | if not port and socket.gethostbyname(host) in (localhost, thishost): |
| 76 | try: fp = open(file, 'r') |
| 77 | except IOError: fp = None |
| 78 | if fp: return makefile(fp, noheaders) |
| 79 | return open_ftp(url) |
| 80 | |
| 81 | # Use FTP protocol |
| 82 | ftpcache = {} |
| 83 | ftperrors = (ftplib.error_reply, |
| 84 | ftplib.error_temp, |
| 85 | ftplib.error_perm, |
| 86 | ftplib.error_proto) |
| 87 | def open_ftp(url): |
| 88 | host, file = splithost(url) |
| 89 | host, port = splitport(host) |
| 90 | host = socket.gethostbyname(host) |
| 91 | if not port: port = ftplib.FTP_PORT |
| 92 | key = (host, port) |
| 93 | try: |
| 94 | if not ftpcache.has_key(key): |
| 95 | ftpcache[key] = ftpwrapper(host, port) |
| 96 | return makefile(ftpcache[key].retrfile(file), noheaders) |
| 97 | except ftperrors, msg: |
| 98 | raise IOError, ('ftp error', msg) |
| 99 | |
| 100 | |
| 101 | # Utility classes |
| 102 | |
| 103 | # Class used to add an info() method to a file object |
| 104 | class makefile: |
| 105 | def __init__(self, fp, headers): |
| 106 | self.fp = fp |
| 107 | self.headers = headers |
| 108 | self.read = self.fp.read |
| 109 | self.fileno = self.fp.fileno |
| 110 | self.close = self.fp.close |
| 111 | def info(self): |
| 112 | return self.headers |
| 113 | |
| 114 | # Class used by open_ftp() for cache of open FTP connections |
| 115 | class ftpwrapper: |
| 116 | def __init__(self, host, port): |
| 117 | self.host = host |
| 118 | self.port = port |
| 119 | self.init() |
| 120 | def init(self): |
| 121 | self.ftp = ftplib.FTP() |
| 122 | self.ftp.connect(self.host, self.port) |
| 123 | self.ftp.login() |
| 124 | def retrfile(self, file): |
| 125 | try: |
| 126 | self.ftp.voidcmd('TYPE I') |
| 127 | except ftplib.all_errors: |
| 128 | self.init() |
| 129 | self.ftp.voidcmd('TYPE I') |
| 130 | conn = None |
| 131 | if file: |
| 132 | try: |
| 133 | cmd = 'RETR ' + file |
| 134 | conn = self.ftp.transfercmd(cmd) |
| 135 | except ftplib.error_perm, reason: |
| 136 | if reason[:3] != '550': |
| 137 | raise IOError, ('ftp error', reason) |
| 138 | if not conn: |
| 139 | # Try a directory listing |
| 140 | if file: cmd = 'NLST ' + file |
| 141 | else: cmd = 'NLST' |
| 142 | conn = self.ftp.transfercmd(cmd) |
| 143 | return fakefile(self.ftp, conn) |
| 144 | |
| 145 | # Class used by ftpwrapper to handle response when transfer is complete |
| 146 | class fakefile: |
| 147 | def __init__(self, ftp, conn): |
| 148 | self.ftp = ftp |
| 149 | self.conn = conn |
| 150 | self.fp = self.conn.makefile('r') |
| 151 | self.read = self.fp.read |
| 152 | self.fileno = self.fp.fileno |
| 153 | def __del__(self): |
| 154 | self.close() |
| 155 | def close(self): |
| 156 | self.conn = None |
| 157 | self.fp = None |
| 158 | self.read = None |
| 159 | if self.ftp: self.ftp.voidresp() |
| 160 | self.ftp = None |
| 161 | |
| 162 | |
| 163 | # Utilities to split url parts into components: |
| 164 | # splittype('type:opaquestring') --> 'type', 'opaquestring' |
| 165 | # splithost('//host[:port]/path') --> 'host[:port]', '/path' |
| 166 | # splitport('host:port') --> 'host', 'port' |
| 167 | # splitquery('/path?query') --> '/path', 'query' |
| 168 | # splittag('/path#tag') --> '/path', 'tag' |
| 169 | # splitgophertype('/Xselector') --> 'X', 'selector' |
| 170 | |
| 171 | typeprog = regex.compile('^\([^/:]+\):\(.*\)$') |
| 172 | def splittype(url): |
| 173 | if typeprog.match(url) >= 0: return typeprog.group(1, 2) |
| 174 | return None, url |
| 175 | |
| 176 | hostprog = regex.compile('^//\([^/]+\)\(.*\)$') |
| 177 | def splithost(url): |
| 178 | if hostprog.match(url) >= 0: return hostprog.group(1, 2) |
| 179 | return None, url |
| 180 | |
| 181 | portprog = regex.compile('^\(.*\):\([0-9]+\)$') |
| 182 | def splitport(host): |
| 183 | if portprog.match(host) >= 0: return portprog.group(1, 2) |
| 184 | return host, None |
| 185 | |
| 186 | queryprog = regex.compile('^\(.*\)\?\([^?]*\)$') |
| 187 | def splitquery(url): |
| 188 | if queryprog.match(url) >= 0: return queryprog.group(1, 2) |
| 189 | return url, None |
| 190 | |
| 191 | tagprog = regex.compile('^\(.*\)#\([^#]*\)$') |
| 192 | def splittag(url): |
| 193 | if tagprog.match(url) >= 0: return tagprog.group(1, 2) |
| 194 | return url, None |
| 195 | |
| 196 | def splitgophertype(selector): |
| 197 | if selector[:1] == '/' and selector[1:2]: |
| 198 | return selector[1], selector[2:] |
| 199 | return None, selector |
| 200 | |
| 201 | |
| 202 | # Test program |
| 203 | def test(): |
| 204 | import sys |
| 205 | args = sys.argv[1:] |
| 206 | if not args: |
| 207 | args = [ |
| 208 | '/etc/passwd', |
| 209 | 'file:/etc/passwd', |
| 210 | 'file://localhost/etc/passwd', |
| 211 | 'ftp://ftp.cwi.nl/etc/passwd', |
| 212 | 'gopher://gopher.cwi.nl/11/', |
| 213 | 'http://www.cwi.nl/index.html', |
| 214 | ] |
| 215 | for arg in args: |
| 216 | print '-'*10, arg, '-'*10 |
| 217 | print regsub.gsub('\r', '', urlopen(arg).read()) |
| 218 | print '-'*40 |
| 219 | |
| 220 | # Run test program when run as a script |
| 221 | if __name__ == '__main__': |
| 222 | test() |