blob: b06f6bfc5d52acec4d06a77d3efbd14ae44cda96 [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 Rossumca445401995-08-29 19:19:12 +000023__version__ = '1.2'
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':
27 def _fixpath(pathname):
28 components = string.split(pathname, '/')
29 if not components[0]:
30 # Absolute unix path, don't start with colon
31 return string.join(components[1:], ':')
32 else:
33 # relative unix path, start with colon
34 return ':' + string.join(components, ':')
35else:
36 def _fixpath(pathname):
37 return pathname
38
Guido van Rossum6cb15a01995-06-22 19:00:13 +000039
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000040# This really consists of two pieces:
41# (1) a class which handles opening of all sorts of URLs
42# (plus assorted utilities etc.)
43# (2) a set of functions for parsing URLs
44# XXX Should these be separated out into different modules?
45
46
47# Shortcut for basic usage
48_urlopener = None
49def urlopen(url):
50 global _urlopener
51 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000052 _urlopener = FancyURLopener()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000053 return _urlopener.open(url)
54def urlretrieve(url):
55 global _urlopener
56 if not _urlopener:
Guido van Rossumbbb0a051995-08-04 04:29:05 +000057 _urlopener = FancyURLopener()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000058 return _urlopener.retrieve(url)
59def urlcleanup():
60 if _urlopener:
61 _urlopener.cleanup()
62
63
64# Class to open URLs.
65# This is a class rather than just a subroutine because we may need
66# more than one set of global protocol-specific options.
Guido van Rossumbbb0a051995-08-04 04:29:05 +000067# Note -- this is a base class for those who don't want the
68# automatic handling of errors type 302 (relocated) and 401
69# (authorization needed).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000070ftpcache = {}
71class URLopener:
72
73 # Constructor
74 def __init__(self):
Guido van Rossum6cb15a01995-06-22 19:00:13 +000075 server_version = "Python-urllib/%s" % __version__
76 self.addheaders = [('User-agent', server_version)]
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000077 self.tempcache = None
78 # Undocumented feature: if you assign {} to tempcache,
79 # it is used to cache files retrieved with
80 # self.retrieve(). This is not enabled by default
81 # since it does not work for changing documents (and I
82 # haven't got the logic to check expiration headers
83 # yet).
Guido van Rossum7c6ebb51994-03-22 12:05:32 +000084 self.ftpcache = ftpcache
85 # Undocumented feature: you can use a different
86 # ftp cache by assigning to the .ftpcache member;
87 # in case you want logically independent URL openers
88
89 def __del__(self):
90 self.close()
91
92 def close(self):
93 self.cleanup()
94
95 def cleanup(self):
96 import os
Guido van Rossum7aeb4b91994-08-23 13:32:20 +000097 if self.tempcache:
98 for url in self.tempcache.keys():
99 try:
100 os.unlink(self.tempcache[url][0])
101 except os.error:
102 pass
103 del self.tempcache[url]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000104
105 # Add a header to be used by the HTTP interface only
106 # e.g. u.addheader('Accept', 'sound/basic')
107 def addheader(self, *args):
108 self.addheaders.append(args)
109
110 # External interface
111 # Use URLopener().open(file) instead of open(file, 'r')
Guido van Rossumca445401995-08-29 19:19:12 +0000112 def open(self, fullurl):
113 fullurl = unwrap(fullurl)
114 type, url = splittype(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000115 if not type: type = 'file'
116 name = 'open_' + type
117 if '-' in name:
118 import regsub
119 name = regsub.gsub('-', '_', name)
120 if not hasattr(self, name):
Guido van Rossumca445401995-08-29 19:19:12 +0000121 return self.open_unknown(fullurl)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000122 try:
123 return getattr(self, name)(url)
124 except socket.error, msg:
125 raise IOError, ('socket error', msg)
126
Guido van Rossumca445401995-08-29 19:19:12 +0000127 # Overridable interface to open unknown URL type
128 def open_unknown(self, fullurl):
129 type, url = splittype(fullurl)
130 raise IOError, ('url error', 'unknown url type', type)
131
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000132 # External interface
133 # retrieve(url) returns (filename, None) for a local object
134 # or (tempfilename, headers) for a remote object
135 def retrieve(self, url):
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000136 if self.tempcache and self.tempcache.has_key(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000137 return self.tempcache[url]
138 url1 = unwrap(url)
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000139 if self.tempcache and self.tempcache.has_key(url1):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000140 self.tempcache[url] = self.tempcache[url1]
141 return self.tempcache[url1]
142 type, url1 = splittype(url1)
143 if not type or type == 'file':
144 try:
145 fp = self.open_local_file(url1)
146 del fp
147 return splithost(url1)[1], None
148 except IOError, msg:
149 pass
150 fp = self.open(url)
151 headers = fp.info()
152 import tempfile
153 tfn = tempfile.mktemp()
Guido van Rossumfa59e831994-09-21 11:36:19 +0000154 result = tfn, headers
Guido van Rossum7aeb4b91994-08-23 13:32:20 +0000155 if self.tempcache is not None:
Guido van Rossumfa59e831994-09-21 11:36:19 +0000156 self.tempcache[url] = result
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000157 tfp = open(tfn, 'w')
158 bs = 1024*8
159 block = fp.read(bs)
160 while block:
161 tfp.write(block)
162 block = fp.read(bs)
163 del fp
164 del tfp
165 return result
166
167 # Each method named open_<type> knows how to open that type of URL
168
169 # Use HTTP protocol
170 def open_http(self, url):
171 import httplib
172 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000173 if not host: raise IOError, ('http error', 'no host given')
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000174 i = string.find(host, '@')
175 if i >= 0:
176 user_passwd, host = host[:i], host[i+1:]
177 else:
178 user_passwd = None
179 if user_passwd:
180 import base64
181 auth = string.strip(base64.encodestring(user_passwd))
182 else:
183 auth = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000184 h = httplib.HTTP(host)
185 h.putrequest('GET', selector)
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000186 if auth: h.putheader('Authorization: Basic %s' % auth)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000187 for args in self.addheaders: apply(h.putheader, args)
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000188 h.endheaders()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000189 errcode, errmsg, headers = h.getreply()
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000190 fp = h.getfile()
191 if errcode == 200:
192 return addinfo(fp, headers)
193 else:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000194 return self.http_error(url,
195 fp, errcode, errmsg, headers)
196
197 # Handle http errors.
198 # Derived class can override this, or provide specific handlers
199 # named http_error_DDD where DDD is the 3-digit error code
200 def http_error(self, url, fp, errcode, errmsg, headers):
201 # First check if there's a specific handler for this error
202 name = 'http_error_%d' % errcode
203 if hasattr(self, name):
204 method = getattr(self, name)
205 result = method(url, fp, errcode, errmsg, headers)
206 if result: return result
207 return self.http_error_default(
208 url, fp, errcode, errmsg, headers)
209
210 # Default http error handler: close the connection and raises IOError
211 def http_error_default(self, url, fp, errcode, errmsg, headers):
212 void = fp.read()
213 fp.close()
214 raise IOError, ('http error', errcode, errmsg, headers)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000215
216 # Use Gopher protocol
217 def open_gopher(self, url):
218 import gopherlib
219 host, selector = splithost(url)
Guido van Rossum590b2891994-04-18 09:39:56 +0000220 if not host: raise IOError, ('gopher error', 'no host given')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000221 type, selector = splitgophertype(selector)
222 selector, query = splitquery(selector)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000223 selector = unquote(selector)
224 if query:
225 query = unquote(query)
226 fp = gopherlib.send_query(selector, query, host)
227 else:
228 fp = gopherlib.send_selector(selector, host)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000229 return addinfo(fp, noheaders())
230
231 # Use local file or FTP depending on form of URL
232 def open_file(self, url):
Guido van Rossumca445401995-08-29 19:19:12 +0000233 if url[:2] == '//':
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000234 return self.open_ftp(url)
Guido van Rossumca445401995-08-29 19:19:12 +0000235 else:
236 return self.open_local_file(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000237
238 # Use local file
239 def open_local_file(self, url):
240 host, file = splithost(url)
Jack Jansendc3e3f61995-12-15 13:22:13 +0000241 if not host: return addinfo(open(_fixpath(file), 'r'), noheaders())
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000242 host, port = splitport(host)
243 if not port and socket.gethostbyname(host) in (
244 localhost(), thishost()):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000245 file = unquote(file)
Jack Jansendc3e3f61995-12-15 13:22:13 +0000246 return addinfo(open(_fixpath(file), 'r'), noheaders())
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000247 raise IOError, ('local file error', 'not on local host')
248
249 # Use FTP protocol
250 def open_ftp(self, url):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000251 host, path = splithost(url)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000252 if not host: raise IOError, ('ftp error', 'no host given')
253 host, port = splitport(host)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000254 user, host = splituser(host)
255 if user: user, passwd = splitpasswd(user)
256 else: passwd = None
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000257 host = socket.gethostbyname(host)
258 if not port:
259 import ftplib
260 port = ftplib.FTP_PORT
Guido van Rossum7c395db1994-07-04 22:14:49 +0000261 path, attrs = splitattr(path)
262 dirs = string.splitfields(path, '/')
263 dirs, file = dirs[:-1], dirs[-1]
264 if dirs and not dirs[0]: dirs = dirs[1:]
265 key = (user, host, port, string.joinfields(dirs, '/'))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000266 try:
267 if not self.ftpcache.has_key(key):
Guido van Rossum7c395db1994-07-04 22:14:49 +0000268 self.ftpcache[key] = \
269 ftpwrapper(user, passwd,
270 host, port, dirs)
271 if not file: type = 'D'
272 else: type = 'I'
273 for attr in attrs:
274 attr, value = splitvalue(attr)
275 if string.lower(attr) == 'type' and \
276 value in ('a', 'A', 'i', 'I', 'd', 'D'):
277 type = string.upper(value)
278 return addinfo(self.ftpcache[key].retrfile(file, type),
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000279 noheaders())
280 except ftperrors(), msg:
281 raise IOError, ('ftp error', msg)
282
283
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000284# Derived class with handlers for errors we can handle (perhaps)
285class FancyURLopener(URLopener):
286
287 def __init__(self, *args):
288 apply(URLopener.__init__, (self,) + args)
289 self.auth_cache = {}
290
291 # Default error handling -- don't raise an exception
292 def http_error_default(self, url, fp, errcode, errmsg, headers):
293 return addinfo(fp, headers)
294
295 # Error 302 -- relocated
296 def http_error_302(self, url, fp, errcode, errmsg, headers):
297 # XXX The server can force infinite recursion here!
298 if headers.has_key('location'):
299 newurl = headers['location']
300 elif headers.has_key('uri'):
301 newurl = headers['uri']
302 else:
303 return
304 void = fp.read()
305 fp.close()
306 return self.open(newurl)
307
308 # Error 401 -- authentication required
309 # See this URL for a description of the basic authentication scheme:
310 # http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt
311 def http_error_401(self, url, fp, errcode, errmsg, headers):
312 if headers.has_key('www-authenticate'):
313 stuff = headers['www-authenticate']
314 p = regex.compile(
315 '[ \t]*\([^ \t]+\)[ \t]+realm="\([^"]*\)"')
316 if p.match(stuff) >= 0:
317 scheme, realm = p.group(1, 2)
318 if string.lower(scheme) == 'basic':
319 return self.retry_http_basic_auth(
320 url, realm)
321
322 def retry_http_basic_auth(self, url, realm):
323 host, selector = splithost(url)
324 i = string.find(host, '@') + 1
325 host = host[i:]
326 user, passwd = self.get_user_passwd(host, realm, i)
327 if not (user or passwd): return None
328 host = user + ':' + passwd + '@' + host
329 newurl = '//' + host + selector
330 return self.open_http(newurl)
331
332 def get_user_passwd(self, host, realm, clear_cache = 0):
333 key = realm + '@' + string.lower(host)
334 if self.auth_cache.has_key(key):
335 if clear_cache:
336 del self.auth_cache[key]
337 else:
338 return self.auth_cache[key]
339 user, passwd = self.prompt_user_passwd(host, realm)
340 if user or passwd: self.auth_cache[key] = (user, passwd)
341 return user, passwd
342
343 def prompt_user_passwd(self, host, realm):
344 # Override this in a GUI environment!
345 try:
346 user = raw_input("Enter username for %s at %s: " %
347 (realm, host))
348 self.echo_off()
349 try:
350 passwd = raw_input(
351 "Enter password for %s in %s at %s: " %
352 (user, realm, host))
353 finally:
354 self.echo_on()
355 return user, passwd
356 except KeyboardInterrupt:
357 return None, None
358
359 def echo_off(self):
360 import os
361 os.system("stty -echo")
362
363 def echo_on(self):
364 import os
365 print
366 os.system("stty echo")
367
368
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000369# Utility functions
370
371# Return the IP address of the magic hostname 'localhost'
372_localhost = None
373def localhost():
374 global _localhost
375 if not _localhost:
376 _localhost = socket.gethostbyname('localhost')
377 return _localhost
378
379# Return the IP address of the current host
380_thishost = None
381def thishost():
382 global _thishost
383 if not _thishost:
384 _thishost = socket.gethostbyname(socket.gethostname())
385 return _thishost
386
387# Return the set of errors raised by the FTP class
388_ftperrors = None
389def ftperrors():
390 global _ftperrors
391 if not _ftperrors:
392 import ftplib
393 _ftperrors = (ftplib.error_reply,
394 ftplib.error_temp,
395 ftplib.error_perm,
396 ftplib.error_proto)
397 return _ftperrors
398
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000399# Return an empty mimetools.Message object
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000400_noheaders = None
401def noheaders():
402 global _noheaders
403 if not _noheaders:
Guido van Rossumbbb0a051995-08-04 04:29:05 +0000404 import mimetools
405 import StringIO
406 _noheaders = mimetools.Message(StringIO.StringIO(), 0)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000407 _noheaders.fp.close() # Recycle file descriptor
408 return _noheaders
409
410
411# Utility classes
412
413# Class used by open_ftp() for cache of open FTP connections
414class ftpwrapper:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000415 def __init__(self, user, passwd, host, port, dirs):
416 self.user = unquote(user or '')
417 self.passwd = unquote(passwd or '')
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000418 self.host = host
419 self.port = port
Guido van Rossum7c395db1994-07-04 22:14:49 +0000420 self.dirs = []
421 for dir in dirs:
422 self.dirs.append(unquote(dir))
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000423 self.init()
424 def init(self):
425 import ftplib
426 self.ftp = ftplib.FTP()
427 self.ftp.connect(self.host, self.port)
Guido van Rossum7c395db1994-07-04 22:14:49 +0000428 self.ftp.login(self.user, self.passwd)
429 for dir in self.dirs:
430 self.ftp.cwd(dir)
431 def retrfile(self, file, type):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000432 import ftplib
Guido van Rossum7c395db1994-07-04 22:14:49 +0000433 if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
434 else: cmd = 'TYPE ' + type; isdir = 0
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000435 try:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000436 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000437 except ftplib.all_errors:
438 self.init()
Guido van Rossum7c395db1994-07-04 22:14:49 +0000439 self.ftp.voidcmd(cmd)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000440 conn = None
Guido van Rossum7c395db1994-07-04 22:14:49 +0000441 if file and not isdir:
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000442 try:
443 cmd = 'RETR ' + file
444 conn = self.ftp.transfercmd(cmd)
445 except ftplib.error_perm, reason:
446 if reason[:3] != '550':
447 raise IOError, ('ftp error', reason)
448 if not conn:
449 # Try a directory listing
450 if file: cmd = 'LIST ' + file
451 else: cmd = 'LIST'
452 conn = self.ftp.transfercmd(cmd)
453 return addclosehook(conn.makefile('r'), self.ftp.voidresp)
454
455# Base class for addinfo and addclosehook
456class addbase:
457 def __init__(self, fp):
458 self.fp = fp
459 self.read = self.fp.read
460 self.readline = self.fp.readline
461 self.readlines = self.fp.readlines
462 self.fileno = self.fp.fileno
463 def __repr__(self):
464 return '<%s at %s whose fp = %s>' % (
465 self.__class__.__name__, `id(self)`, `self.fp`)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000466 def close(self):
467 self.read = None
468 self.readline = None
469 self.readlines = None
470 self.fileno = None
Guido van Rossum6cb15a01995-06-22 19:00:13 +0000471 if self.fp: self.fp.close()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000472 self.fp = None
473
474# Class to add a close hook to an open file
475class addclosehook(addbase):
476 def __init__(self, fp, closehook, *hookargs):
477 addbase.__init__(self, fp)
478 self.closehook = closehook
479 self.hookargs = hookargs
480 def close(self):
481 if self.closehook:
482 apply(self.closehook, self.hookargs)
483 self.closehook = None
484 self.hookargs = None
485 addbase.close(self)
486
487# class to add an info() method to an open file
488class addinfo(addbase):
489 def __init__(self, fp, headers):
490 addbase.__init__(self, fp)
491 self.headers = headers
492 def info(self):
493 return self.headers
494
495
496# Utility to combine a URL with a base URL to form a new URL
497
498def basejoin(base, url):
499 type, path = splittype(url)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000500 if type:
501 # if url is complete (i.e., it contains a type), return it
502 return url
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000503 host, path = splithost(path)
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000504 type, basepath = splittype(base) # inherit type from base
505 if host:
506 # if url contains host, just inherit type
507 if type: return type + '://' + host + path
508 else:
509 # no type inherited, so url must have started with //
510 # just return it
511 return url
512 host, basepath = splithost(basepath) # inherit host
513 basepath, basetag = splittag(basepath) # remove extraneuous cruft
514 basepath, basequery = splitquery(basepath) # idem
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000515 if path[:1] != '/':
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000516 # non-absolute path name
517 if path[:1] in ('#', '?'):
518 # path is just a tag or query, attach to basepath
519 i = len(basepath)
520 else:
521 # else replace last component
522 i = string.rfind(basepath, '/')
523 if i < 0:
524 # basepath not absolute
525 if host:
526 # host present, make absolute
527 basepath = '/'
528 else:
529 # else keep non-absolute
530 basepath = ''
531 else:
532 # remove last file component
533 basepath = basepath[:i+1]
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000534 path = basepath + path
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000535 if type and host: return type + '://' + host + path
536 elif type: return type + ':' + path
537 elif host: return '//' + host + path # don't know what this means
538 else: return path
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000539
540
Guido van Rossum7c395db1994-07-04 22:14:49 +0000541# Utilities to parse URLs (most of these return None for missing parts):
Sjoerd Mullendere0371b81995-11-10 10:36:07 +0000542# unwrap('<URL:type://host/path>') --> 'type://host/path'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000543# splittype('type:opaquestring') --> 'type', 'opaquestring'
544# splithost('//host[:port]/path') --> 'host[:port]', '/path'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000545# splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
546# splitpasswd('user:passwd') -> 'user', 'passwd'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000547# splitport('host:port') --> 'host', 'port'
548# splitquery('/path?query') --> '/path', 'query'
549# splittag('/path#tag') --> '/path', 'tag'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000550# splitattr('/path;attr1=value1;attr2=value2;...') ->
551# '/path', ['attr1=value1', 'attr2=value2', ...]
552# splitvalue('attr=value') --> 'attr', 'value'
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000553# splitgophertype('/Xselector') --> 'X', 'selector'
554# unquote('abc%20def') -> 'abc def'
555# quote('abc def') -> 'abc%20def')
556
557def unwrap(url):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000558 url = string.strip(url)
559 if url[:1] == '<' and url[-1:] == '>':
560 url = string.strip(url[1:-1])
561 if url[:4] == 'URL:': url = string.strip(url[4:])
562 return url
563
564_typeprog = regex.compile('^\([^/:]+\):\(.*\)$')
565def splittype(url):
566 if _typeprog.match(url) >= 0: return _typeprog.group(1, 2)
567 return None, url
568
569_hostprog = regex.compile('^//\([^/]+\)\(.*\)$')
570def splithost(url):
571 if _hostprog.match(url) >= 0: return _hostprog.group(1, 2)
572 return None, url
573
Guido van Rossum7c395db1994-07-04 22:14:49 +0000574_userprog = regex.compile('^\([^@]*\)@\(.*\)$')
575def splituser(host):
576 if _userprog.match(host) >= 0: return _userprog.group(1, 2)
577 return None, host
578
579_passwdprog = regex.compile('^\([^:]*\):\(.*\)$')
580def splitpasswd(user):
581 if _passwdprog.match(user) >= 0: return _passwdprog.group(1, 2)
582 return user, None
583
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000584_portprog = regex.compile('^\(.*\):\([0-9]+\)$')
585def splitport(host):
586 if _portprog.match(host) >= 0: return _portprog.group(1, 2)
587 return host, None
588
589_queryprog = regex.compile('^\(.*\)\?\([^?]*\)$')
590def splitquery(url):
591 if _queryprog.match(url) >= 0: return _queryprog.group(1, 2)
592 return url, None
593
594_tagprog = regex.compile('^\(.*\)#\([^#]*\)$')
595def splittag(url):
596 if _tagprog.match(url) >= 0: return _tagprog.group(1, 2)
597 return url, None
598
Guido van Rossum7c395db1994-07-04 22:14:49 +0000599def splitattr(url):
600 words = string.splitfields(url, ';')
601 return words[0], words[1:]
602
603_valueprog = regex.compile('^\([^=]*\)=\(.*\)$')
604def splitvalue(attr):
605 if _valueprog.match(attr) >= 0: return _valueprog.group(1, 2)
606 return attr, None
607
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000608def splitgophertype(selector):
609 if selector[:1] == '/' and selector[1:2]:
610 return selector[1], selector[2:]
611 return None, selector
612
613_quoteprog = regex.compile('%[0-9a-fA-F][0-9a-fA-F]')
614def unquote(s):
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000615 i = 0
616 n = len(s)
617 res = ''
618 while 0 <= i < n:
619 j = _quoteprog.search(s, i)
620 if j < 0:
621 res = res + s[i:]
622 break
623 res = res + (s[i:j] + chr(eval('0x' + s[j+1:j+3])))
624 i = j+3
625 return res
626
Guido van Rossum3bb54481994-08-29 10:52:58 +0000627always_safe = string.letters + string.digits + '_,.-'
Guido van Rossum7c395db1994-07-04 22:14:49 +0000628def quote(s, safe = '/'):
629 safe = always_safe + safe
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000630 res = ''
631 for c in s:
Guido van Rossum7c395db1994-07-04 22:14:49 +0000632 if c in safe:
633 res = res + c
634 else:
635 res = res + '%%%02x' % ord(c)
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000636 return res
637
638# Test and time quote() and unquote()
639def test1():
640 import time
641 s = ''
642 for i in range(256): s = s + chr(i)
643 s = s*4
644 t0 = time.time()
645 qs = quote(s)
646 uqs = unquote(qs)
647 t1 = time.time()
648 if uqs != s:
649 print 'Wrong!'
650 print `s`
651 print `qs`
652 print `uqs`
653 print round(t1 - t0, 3), 'sec'
654
655
656# Test program
657def test():
658 import sys
659 import regsub
660 args = sys.argv[1:]
661 if not args:
662 args = [
663 '/etc/passwd',
664 'file:/etc/passwd',
665 'file://localhost/etc/passwd',
666 'ftp://ftp.cwi.nl/etc/passwd',
667 'gopher://gopher.cwi.nl/11/',
668 'http://www.cwi.nl/index.html',
669 ]
670 try:
671 for url in args:
672 print '-'*10, url, '-'*10
673 fn, h = urlretrieve(url)
674 print fn, h
675 if h:
676 print '======'
677 for k in h.keys(): print k + ':', h[k]
678 print '======'
679 fp = open(fn, 'r')
680 data = fp.read()
681 del fp
682 print regsub.gsub('\r', '', data)
683 fn, h = None, None
684 print '-'*40
685 finally:
686 urlcleanup()
687
688# Run test program when run as a script
689if __name__ == '__main__':
Guido van Rossum7c395db1994-07-04 22:14:49 +0000690## test1()
Guido van Rossum7c6ebb51994-03-22 12:05:32 +0000691 test()