blob: 63e41829e4dedfbeb6fed3118a6ee180167b323c [file] [log] [blame]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +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#
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 Rossumbbb0a051995-08-04 04:29:05 +000013# The info() method returns an mimetools.Message object which can be
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000014# used to query various info about the object, if available.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000015# (mimetools.Message objects are queried with the getheader() method.)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000016
Guido van Rossum7c395db1994-07-04 22:14:49 +000017import string
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000018import socket
19import regex
Jack Jansendc3e3f61995-12-15 13:22:13 +000020import os
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000021
22
Guido van Rossum442e7201996-03-20 15:33:11 +000023__version__ = '1.3'
Guido van Rossum6cb15a01995-06-22 19:00:13 +000024
Jack Jansendc3e3f61995-12-15 13:22:13 +000025# Helper for non-unix systems
26if os.name == 'mac':
Guido van Rossum71ac9451996-03-21 16:31:41 +000027 from macurl2path import url2pathname, pathname2url
Guido van Rossum2281d351996-06-26 19:47:37 +000028elif os.name == 'nt':
29 from nturl2path import url2pathname, pathname2url
Jack Jansendc3e3f61995-12-15 13:22:13 +000030else:
Jack Jansene8ea21b1995-12-21 15:43:53 +000031 def url2pathname(pathname):
Jack Jansendc3e3f61995-12-15 13:22:13 +000032 return pathname
Jack Jansene8ea21b1995-12-21 15:43:53 +000033 def pathname2url(pathname):
34 return pathname
Guido van Rossum6cb15a01995-06-22 19:00:13 +000035
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000036# This really consists of two pieces:
37# (1) a class which handles opening of all sorts of URLs
38# (plus assorted utilities etc.)
39# (2) a set of functions for parsing URLs
40# XXX Should these be separated out into different modules?
41
42
43# Shortcut for basic usage
44_urlopener = None
45def urlopen(url):
46 global _urlopener
47 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000048 _urlopener = FancyURLopener()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000049 return _urlopener.open(url)
Guido van Rossuma7e4b281996-06-11 00:16:27 +000050def urlretrieve(url, filename=None):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000051 global _urlopener
52 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000053 _urlopener = FancyURLopener()
Guido van Rossuma7e4b281996-06-11 00:16:27 +000054 if filename:
55 return _urlopener.retrieve(url, filename)
56 else:
57 return _urlopener.retrieve(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000058def urlcleanup():
59 if _urlopener:
60 _urlopener.cleanup()
61
62
63# Class to open URLs.
64# This is a class rather than just a subroutine because we may need
65# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000066# Note -- this is a base class for those who don't want the
67# automatic handling of errors type 302 (relocated) and 401
68# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000069ftpcache = {}
70class URLopener:
71
72 # Constructor
Guido van Rossum442e7201996-03-20 15:33:11 +000073 def __init__(self, proxies=None):
74 if proxies is None:
75 proxies = getproxies()
76 self.proxies = proxies
Guido van Rossum6cb15a01995-06-22 19:00:13 +000077 server_version = "Python-urllib/%s" % __version__
78 self.addheaders = [('User-agent', server_version)]
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000079 self.tempcache = None
80 # Undocumented feature: if you assign {} to tempcache,
81 # it is used to cache files retrieved with
82 # self.retrieve(). This is not enabled by default
83 # since it does not work for changing documents (and I
84 # haven't got the logic to check expiration headers
85 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000086 self.ftpcache = ftpcache
87 # Undocumented feature: you can use a different
88 # ftp cache by assigning to the .ftpcache member;
89 # in case you want logically independent URL openers
90
91 def __del__(self):
92 self.close()
93
94 def close(self):
95 self.cleanup()
96
97 def cleanup(self):
98 import os
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000099 if self.tempcache:
100 for url in self.tempcache.keys():
101 try:
102 os.unlink(self.tempcache[url][0])
103 except os.error:
104 pass
105 del self.tempcache[url]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000106
107 # Add a header to be used by the HTTP interface only
108 # e.g. u.addheader('Accept', 'sound/basic')
109 def addheader(self, *args):
110 self.addheaders.append(args)
111
112 # External interface
113 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumca445401995-08-29 19:19:12 +0000114 def open(self, fullurl):
115 fullurl = unwrap(fullurl)
116 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000117 if not type: type = 'file'
Guido van Rossum442e7201996-03-20 15:33:11 +0000118 if self.proxies.has_key(type):
119 proxy = self.proxies[type]
120 type, proxy = splittype(proxy)
121 host, selector = splithost(proxy)
122 url = (host, fullurl) # Signal special case to open_*()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000123 name = 'open_' + type
124 if '-' in name:
125 import regsub
126 name = regsub.gsub('-', '_', name)
127 if not hasattr(self, name):
Guido van Rossumca445401995-08-29 19:19:12 +0000128 return self.open_unknown(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000129 try:
130 return getattr(self, name)(url)
131 except socket.error, msg:
132 raise IOError, ('socket error', msg)
133
Guido van Rossumca445401995-08-29 19:19:12 +0000134 # Overridable interface to open unknown URL type
135 def open_unknown(self, fullurl):
136 type, url = splittype(fullurl)
137 raise IOError, ('url error', 'unknown url type', type)
138
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000139 # External interface
140 # retrieve(url) returns (filename, None) for a local object
141 # or (tempfilename, headers) for a remote object
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000142 def retrieve(self, url, filename=None):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000143 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000144 return self.tempcache[url]
145 url1 = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000146 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000147 self.tempcache[url] = self.tempcache[url1]
148 return self.tempcache[url1]
149 type, url1 = splittype(url1)
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000150 if not filename and (not type or type == 'file'):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000151 try:
152 fp = self.open_local_file(url1)
153 del fp
Jack Jansene8ea21b1995-12-21 15:43:53 +0000154 return url2pathname(splithost(url1)[1]), None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000155 except IOError, msg:
156 pass
157 fp = self.open(url)
158 headers = fp.info()
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000159 if not filename:
160 import tempfile
161 filename = tempfile.mktemp()
162 result = filename, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000163 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000164 self.tempcache[url] = result
Guido van Rossuma7e4b281996-06-11 00:16:27 +0000165 tfp = open(filename, 'w')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000166 bs = 1024*8
167 block = fp.read(bs)
168 while block:
169 tfp.write(block)
170 block = fp.read(bs)
171 del fp
172 del tfp
173 return result
174
175 # Each method named open_<type> knows how to open that type of URL
176
177 # Use HTTP protocol
178 def open_http(self, url):
179 import httplib
Guido van Rossum442e7201996-03-20 15:33:11 +0000180 if type(url) is type(""):
181 host, selector = splithost(url)
182 else:
183 host, selector = url
184 print "proxy via http:", host, selector
Guido van Rossum590b2891994-04-18 09:39:56 +0000185 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000186 i = string.find(host, '@')
187 if i >= 0:
188 user_passwd, host = host[:i], host[i+1:]
189 else:
190 user_passwd = None
191 if user_passwd:
192 import base64
193 auth = string.strip(base64.encodestring(user_passwd))
194 else:
195 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000196 h = httplib.HTTP(host)
197 h.putrequest('GET', selector)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000198 if auth: h.putheader('Authorization: Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000199 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000200 h.endheaders()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000201 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000202 fp = h.getfile()
203 if errcode == 200:
204 return addinfo(fp, headers)
205 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000206 return self.http_error(url,
207 fp, errcode, errmsg, headers)
208
209 # Handle http errors.
210 # Derived class can override this, or provide specific handlers
211 # named http_error_DDD where DDD is the 3-digit error code
212 def http_error(self, url, fp, errcode, errmsg, headers):
213 # First check if there's a specific handler for this error
214 name = 'http_error_%d' % errcode
215 if hasattr(self, name):
216 method = getattr(self, name)
217 result = method(url, fp, errcode, errmsg, headers)
218 if result: return result
219 return self.http_error_default(
220 url, fp, errcode, errmsg, headers)
221
222 # Default http error handler: close the connection and raises IOError
223 def http_error_default(self, url, fp, errcode, errmsg, headers):
224 void = fp.read()
225 fp.close()
226 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000227
228 # Use Gopher protocol
229 def open_gopher(self, url):
230 import gopherlib
231 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000232 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000233 type, selector = splitgophertype(selector)
234 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000235 selector = unquote(selector)
236 if query:
237 query = unquote(query)
238 fp = gopherlib.send_query(selector, query, host)
239 else:
240 fp = gopherlib.send_selector(selector, host)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000241 return addinfo(fp, noheaders())
242
243 # Use local file or FTP depending on form of URL
244 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000245 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000246 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000247 else:
248 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000249
250 # Use local file
251 def open_local_file(self, url):
252 host, file = splithost(url)
Jack Jansene8ea21b1995-12-21 15:43:53 +0000253 if not host: return addinfo(open(url2pathname(file), 'r'), noheaders())
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000254 host, port = splitport(host)
255 if not port and socket.gethostbyname(host) in (
256 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000257 file = unquote(file)
Jack Jansene8ea21b1995-12-21 15:43:53 +0000258 return addinfo(open(url2pathname(file), 'r'), noheaders())
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000259 raise IOError, ('local file error', 'not on local host')
260
261 # Use FTP protocol
262 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000263 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000264 if not host: raise IOError, ('ftp error', 'no host given')
265 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000266 user, host = splituser(host)
267 if user: user, passwd = splitpasswd(user)
268 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000269 host = socket.gethostbyname(host)
270 if not port:
271 import ftplib
272 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000273 path, attrs = splitattr(path)
274 dirs = string.splitfields(path, '/')
275 dirs, file = dirs[:-1], dirs[-1]
276 if dirs and not dirs[0]: dirs = dirs[1:]
277 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000278 try:
279 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000280 self.ftpcache[key] = \
281 ftpwrapper(user, passwd,
282 host, port, dirs)
283 if not file: type = 'D'
284 else: type = 'I'
285 for attr in attrs:
286 attr, value = splitvalue(attr)
287 if string.lower(attr) == 'type' and \
288 value in ('a', 'A', 'i', 'I', 'd', 'D'):
289 type = string.upper(value)
290 return addinfo(self.ftpcache[key].retrfile(file, type),
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000291 noheaders())
292 except ftperrors(), msg:
293 raise IOError, ('ftp error', msg)
294
295
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000296# Derived class with handlers for errors we can handle (perhaps)
297class FancyURLopener(URLopener):
298
299 def __init__(self, *args):
300 apply(URLopener.__init__, (self,) + args)
301 self.auth_cache = {}
302
303 # Default error handling -- don't raise an exception
304 def http_error_default(self, url, fp, errcode, errmsg, headers):
305 return addinfo(fp, headers)
306
307 # Error 302 -- relocated
308 def http_error_302(self, url, fp, errcode, errmsg, headers):
309 # XXX The server can force infinite recursion here!
310 if headers.has_key('location'):
311 newurl = headers['location']
312 elif headers.has_key('uri'):
313 newurl = headers['uri']
314 else:
315 return
316 void = fp.read()
317 fp.close()
318 return self.open(newurl)
319
320 # Error 401 -- authentication required
321 # See this URL for a description of the basic authentication scheme:
322 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
323 def http_error_401(self, url, fp, errcode, errmsg, headers):
324 if headers.has_key('www-authenticate'):
325 stuff = headers['www-authenticate']
326 p = regex.compile(
327 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
328 if p.match(stuff) >= 0:
329 scheme, realm = p.group(1, 2)
330 if string.lower(scheme) == 'basic':
331 return self.retry_http_basic_auth(
332 url, realm)
333
334 def retry_http_basic_auth(self, url, realm):
335 host, selector = splithost(url)
336 i = string.find(host, '@') + 1
337 host = host[i:]
338 user, passwd = self.get_user_passwd(host, realm, i)
339 if not (user or passwd): return None
340 host = user + ':' + passwd + '@' + host
341 newurl = '//' + host + selector
342 return self.open_http(newurl)
343
344 def get_user_passwd(self, host, realm, clear_cache = 0):
345 key = realm + '@' + string.lower(host)
346 if self.auth_cache.has_key(key):
347 if clear_cache:
348 del self.auth_cache[key]
349 else:
350 return self.auth_cache[key]
351 user, passwd = self.prompt_user_passwd(host, realm)
352 if user or passwd: self.auth_cache[key] = (user, passwd)
353 return user, passwd
354
355 def prompt_user_passwd(self, host, realm):
356 # Override this in a GUI environment!
357 try:
358 user = raw_input("Enter username for %s at %s: " %
359 (realm, host))
360 self.echo_off()
361 try:
362 passwd = raw_input(
363 "Enter password for %s in %s at %s: " %
364 (user, realm, host))
365 finally:
366 self.echo_on()
367 return user, passwd
368 except KeyboardInterrupt:
369 return None, None
370
371 def echo_off(self):
372 import os
373 os.system("stty -echo")
374
375 def echo_on(self):
376 import os
377 print
378 os.system("stty echo")
379
380
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000381# Utility functions
382
383# Return the IP address of the magic hostname 'localhost'
384_localhost = None
385def localhost():
386 global _localhost
387 if not _localhost:
388 _localhost = socket.gethostbyname('localhost')
389 return _localhost
390
391# Return the IP address of the current host
392_thishost = None
393def thishost():
394 global _thishost
395 if not _thishost:
396 _thishost = socket.gethostbyname(socket.gethostname())
397 return _thishost
398
399# Return the set of errors raised by the FTP class
400_ftperrors = None
401def ftperrors():
402 global _ftperrors
403 if not _ftperrors:
404 import ftplib
405 _ftperrors = (ftplib.error_reply,
406 ftplib.error_temp,
407 ftplib.error_perm,
408 ftplib.error_proto)
409 return _ftperrors
410
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000411# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000412_noheaders = None
413def noheaders():
414 global _noheaders
415 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000416 import mimetools
417 import StringIO
418 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000419 _noheaders.fp.close() # Recycle file descriptor
420 return _noheaders
421
422
423# Utility classes
424
425# Class used by open_ftp() for cache of open FTP connections
426class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000427 def __init__(self, user, passwd, host, port, dirs):
428 self.user = unquote(user or '')
429 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000430 self.host = host
431 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000432 self.dirs = []
433 for dir in dirs:
434 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000435 self.init()
436 def init(self):
437 import ftplib
438 self.ftp = ftplib.FTP()
439 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000440 self.ftp.login(self.user, self.passwd)
441 for dir in self.dirs:
442 self.ftp.cwd(dir)
443 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000444 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000445 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
446 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000447 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000448 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000449 except ftplib.all_errors:
450 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000451 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000452 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000453 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000454 try:
455 cmd = 'RETR ' + file
456 conn = self.ftp.transfercmd(cmd)
457 except ftplib.error_perm, reason:
458 if reason[:3] != '550':
459 raise IOError, ('ftp error', reason)
460 if not conn:
461 # Try a directory listing
462 if file: cmd = 'LIST ' + file
463 else: cmd = 'LIST'
464 conn = self.ftp.transfercmd(cmd)
Jack Jansen0d12ead1996-02-14 16:05:20 +0000465 return addclosehook(conn.makefile('rb'), self.ftp.voidresp)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000466
467# Base class for addinfo and addclosehook
468class addbase:
469 def __init__(self, fp):
470 self.fp = fp
471 self.read = self.fp.read
472 self.readline = self.fp.readline
473 self.readlines = self.fp.readlines
474 self.fileno = self.fp.fileno
475 def __repr__(self):
476 return '<%s at %s whose fp = %s>' % (
477 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000478 def close(self):
479 self.read = None
480 self.readline = None
481 self.readlines = None
482 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000483 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000484 self.fp = None
485
486# Class to add a close hook to an open file
487class addclosehook(addbase):
488 def __init__(self, fp, closehook, *hookargs):
489 addbase.__init__(self, fp)
490 self.closehook = closehook
491 self.hookargs = hookargs
492 def close(self):
493 if self.closehook:
494 apply(self.closehook, self.hookargs)
495 self.closehook = None
496 self.hookargs = None
497 addbase.close(self)
498
499# class to add an info() method to an open file
500class addinfo(addbase):
501 def __init__(self, fp, headers):
502 addbase.__init__(self, fp)
503 self.headers = headers
504 def info(self):
505 return self.headers
506
507
508# Utility to combine a URL with a base URL to form a new URL
509
510def basejoin(base, url):
511 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000512 if type:
513 # if url is complete (i.e., it contains a type), return it
514 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000515 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000516 type, basepath = splittype(base) # inherit type from base
517 if host:
518 # if url contains host, just inherit type
519 if type: return type + '://' + host + path
520 else:
521 # no type inherited, so url must have started with //
522 # just return it
523 return url
524 host, basepath = splithost(basepath) # inherit host
525 basepath, basetag = splittag(basepath) # remove extraneuous cruft
526 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000527 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000528 # non-absolute path name
529 if path[:1] in ('#', '?'):
530 # path is just a tag or query, attach to basepath
531 i = len(basepath)
532 else:
533 # else replace last component
534 i = string.rfind(basepath, '/')
535 if i < 0:
536 # basepath not absolute
537 if host:
538 # host present, make absolute
539 basepath = '/'
540 else:
541 # else keep non-absolute
542 basepath = ''
543 else:
544 # remove last file component
545 basepath = basepath[:i+1]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000546 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000547 if type and host: return type + '://' + host + path
548 elif type: return type + ':' + path
549 elif host: return '//' + host + path # don't know what this means
550 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000551
552
Guido van Rossum7c395db1994-07-04 22:14:49 +0000553# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000554# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000555# splittype('type:opaquestring') --> 'type', 'opaquestring'
556# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000557# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
558# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000559# splitport('host:port') --> 'host', 'port'
560# splitquery('/path?query') --> '/path', 'query'
561# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000562# splitattr('/path;attr1=value1;attr2=value2;...') ->
563# '/path', ['attr1=value1', 'attr2=value2', ...]
564# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000565# splitgophertype('/Xselector') --> 'X', 'selector'
566# unquote('abc%20def') -> 'abc def'
567# quote('abc def') -> 'abc%20def')
568
569def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000570 url = string.strip(url)
571 if url[:1] == '<' and url[-1:] == '>':
572 url = string.strip(url[1:-1])
573 if url[:4] == 'URL:': url = string.strip(url[4:])
574 return url
575
576_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
577def splittype(url):
578 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
579 return None, url
580
581_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
582def splithost(url):
583 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
584 return None, url
585
Guido van Rossum7c395db1994-07-04 22:14:49 +0000586_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
587def splituser(host):
588 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
589 return None, host
590
591_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
592def splitpasswd(user):
593 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
594 return user, None
595
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000596_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
597def splitport(host):
598 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
599 return host, None
600
Guido van Rossum53725a21996-06-13 19:12:35 +0000601# Split host and port, returning numeric port.
602# Return given default port if no ':' found; defaults to -1.
Guido van Rossum84a00a81996-06-17 17:11:40 +0000603# Return numerical port if a valid number are found after ':'.
604# Return None if ':' but not a valid number.
605_nportprog = regex.compile('^\(.*\):\(.*\)$')
Guido van Rossum53725a21996-06-13 19:12:35 +0000606def splitnport(host, defport=-1):
607 if _nportprog.match(host) >= 0:
Guido van Rossum84a00a81996-06-17 17:11:40 +0000608 host, port = _nportprog.group(1, 2)
609 try:
610 if not port: raise string.atoi_error, "no digits"
611 nport = string.atoi(port)
612 except string.atoi_error:
613 nport = None
Guido van Rossum53725a21996-06-13 19:12:35 +0000614 return host, nport
615 return host, defport
616
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000617_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
618def splitquery(url):
619 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
620 return url, None
621
622_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
623def splittag(url):
624 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
625 return url, None
626
Guido van Rossum7c395db1994-07-04 22:14:49 +0000627def splitattr(url):
628 words = string.splitfields(url, ';')
629 return words[0], words[1:]
630
631_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
632def splitvalue(attr):
633 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
634 return attr, None
635
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000636def splitgophertype(selector):
637 if selector[:1] == '/' and selector[1:2]:
638 return selector[1], selector[2:]
639 return None, selector
640
641_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
642def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000643 i = 0
644 n = len(s)
645 res = ''
646 while 0 <= i < n:
647 j = _quoteprog.search(s, i)
648 if j < 0:
649 res = res + s[i:]
650 break
Guido van Rossum8c8a02a1996-01-26 17:41:44 +0000651 res = res + (s[i:j] + chr(string.atoi(s[j+1:j+3], 16)))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000652 i = j+3
653 return res
654
Guido van Rossum3bb54481994-08-29 10:52:58 +0000655always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000656def quote(s, safe = '/'):
657 safe = always_safe + safe
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000658 res = ''
659 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000660 if c in safe:
661 res = res + c
662 else:
663 res = res + '%%%02x' % ord(c)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000664 return res
665
Guido van Rossum442e7201996-03-20 15:33:11 +0000666
667# Proxy handling
668def getproxies():
669 """Return a dictionary of protocol scheme -> proxy server URL mappings.
670
671 Scan the environment for variables named <scheme>_proxy;
672 this seems to be the standard convention. If you need a
673 different way, you can pass a proxies dictionary to the
674 [Fancy]URLopener constructor.
675
676 """
677 proxies = {}
678 for name, value in os.environ.items():
679 if value and name[-6:] == '_proxy':
680 proxies[name[:-6]] = value
681 return proxies
682
683
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000684# Test and time quote() and unquote()
685def test1():
686 import time
687 s = ''
688 for i in range(256): s = s + chr(i)
689 s = s*4
690 t0 = time.time()
691 qs = quote(s)
692 uqs = unquote(qs)
693 t1 = time.time()
694 if uqs != s:
695 print 'Wrong!'
696 print `s`
697 print `qs`
698 print `uqs`
699 print round(t1 - t0, 3), 'sec'
700
701
702# Test program
703def test():
704 import sys
705 import regsub
706 args = sys.argv[1:]
707 if not args:
708 args = [
709 '/etc/passwd',
710 'file:/etc/passwd',
711 'file://localhost/etc/passwd',
712 'ftp://ftp.cwi.nl/etc/passwd',
713 'gopher://gopher.cwi.nl/11/',
714 'http://www.cwi.nl/index.html',
715 ]
716 try:
717 for url in args:
718 print '-'*10, url, '-'*10
719 fn, h = urlretrieve(url)
720 print fn, h
721 if h:
722 print '======'
723 for k in h.keys(): print k + ':', h[k]
724 print '======'
725 fp = open(fn, 'r')
726 data = fp.read()
727 del fp
728 print regsub.gsub('\r', '', data)
729 fn, h = None, None
730 print '-'*40
731 finally:
732 urlcleanup()
733
734# Run test program when run as a script
735if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000736## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000737 test()