home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / URLLIB.PY < prev    next >
Encoding:
Python Source  |  2000-10-02  |  43.8 KB  |  1,281 lines

  1. """Open an arbitrary URL.
  2.  
  3. See the following document for more info on URLs:
  4. "Names and Addresses, URIs, URLs, URNs, URCs", at
  5. http://www.w3.org/pub/WWW/Addressing/Overview.html
  6.  
  7. See also the HTTP spec (from which the error codes are derived):
  8. "HTTP - Hypertext Transfer Protocol", at
  9. http://www.w3.org/pub/WWW/Protocols/
  10.  
  11. Related standards and specs:
  12. - RFC1808: the "relative URL" spec. (authoritative status)
  13. - RFC1738 - the "URL standard". (authoritative status)
  14. - RFC1630 - the "URI spec". (informational status)
  15.  
  16. The object returned by URLopener().open(file) will differ per
  17. protocol.  All you know is that is has methods read(), readline(),
  18. readlines(), fileno(), close() and info().  The read*(), fileno()
  19. and close() methods work like those of open files.
  20. The info() method returns a mimetools.Message object which can be
  21. used to query various info about the object, if available.
  22. (mimetools.Message objects are queried with the getheader() method.)
  23. """
  24.  
  25. import string
  26. import socket
  27. import os
  28. import sys
  29.  
  30.  
  31. __version__ = '1.13'    # XXX This version is not always updated :-(
  32.  
  33. MAXFTPCACHE = 10        # Trim the ftp cache beyond this size
  34.  
  35. # Helper for non-unix systems
  36. if os.name == 'mac':
  37.     from macurl2path import url2pathname, pathname2url
  38. elif os.name == 'nt':
  39.     from nturl2path import url2pathname, pathname2url
  40. else:
  41.     def url2pathname(pathname):
  42.         return unquote(pathname)
  43.     def pathname2url(pathname):
  44.         return quote(pathname)
  45.  
  46. # This really consists of two pieces:
  47. # (1) a class which handles opening of all sorts of URLs
  48. #     (plus assorted utilities etc.)
  49. # (2) a set of functions for parsing URLs
  50. # XXX Should these be separated out into different modules?
  51.  
  52.  
  53. # Shortcut for basic usage
  54. _urlopener = None
  55. def urlopen(url, data=None):
  56.     """urlopen(url [, data]) -> open file-like object"""
  57.     global _urlopener
  58.     if not _urlopener:
  59.         _urlopener = FancyURLopener()
  60.     if data is None:
  61.         return _urlopener.open(url)
  62.     else:
  63.         return _urlopener.open(url, data)
  64. def urlretrieve(url, filename=None, reporthook=None, data=None):
  65.     global _urlopener
  66.     if not _urlopener:
  67.         _urlopener = FancyURLopener()
  68.     return _urlopener.retrieve(url, filename, reporthook, data)
  69. def urlcleanup():
  70.     if _urlopener:
  71.         _urlopener.cleanup()
  72.  
  73.  
  74. ftpcache = {}
  75. class URLopener:
  76.     """Class to open URLs.
  77.     This is a class rather than just a subroutine because we may need
  78.     more than one set of global protocol-specific options.
  79.     Note -- this is a base class for those who don't want the
  80.     automatic handling of errors type 302 (relocated) and 401
  81.     (authorization needed)."""
  82.  
  83.     __tempfiles = None
  84.  
  85.     version = "Python-urllib/%s" % __version__
  86.  
  87.     # Constructor
  88.     def __init__(self, proxies=None, **x509):
  89.         if proxies is None:
  90.             proxies = getproxies()
  91.         assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
  92.         self.proxies = proxies
  93.         self.key_file = x509.get('key_file')
  94.         self.cert_file = x509.get('cert_file')
  95.         self.addheaders = [('User-agent', self.version)]
  96.         self.__tempfiles = []
  97.         self.__unlink = os.unlink # See cleanup()
  98.         self.tempcache = None
  99.         # Undocumented feature: if you assign {} to tempcache,
  100.         # it is used to cache files retrieved with
  101.         # self.retrieve().  This is not enabled by default
  102.         # since it does not work for changing documents (and I
  103.         # haven't got the logic to check expiration headers
  104.         # yet).
  105.         self.ftpcache = ftpcache
  106.         # Undocumented feature: you can use a different
  107.         # ftp cache by assigning to the .ftpcache member;
  108.         # in case you want logically independent URL openers
  109.         # XXX This is not threadsafe.  Bah.
  110.  
  111.     def __del__(self):
  112.         self.close()
  113.  
  114.     def close(self):
  115.         self.cleanup()
  116.  
  117.     def cleanup(self):
  118.         # This code sometimes runs when the rest of this module
  119.         # has already been deleted, so it can't use any globals
  120.         # or import anything.
  121.         if self.__tempfiles:
  122.             for file in self.__tempfiles:
  123.                 try:
  124.                     self.__unlink(file)
  125.                 except:
  126.                     pass
  127.             del self.__tempfiles[:]
  128.         if self.tempcache:
  129.             self.tempcache.clear()
  130.  
  131.     def addheader(self, *args):
  132.         """Add a header to be used by the HTTP interface only
  133.         e.g. u.addheader('Accept', 'sound/basic')"""
  134.         self.addheaders.append(args)
  135.  
  136.     # External interface
  137.     def open(self, fullurl, data=None):
  138.         """Use URLopener().open(file) instead of open(file, 'r')."""
  139.         fullurl = unwrap(fullurl)
  140.         if self.tempcache and self.tempcache.has_key(fullurl):
  141.             filename, headers = self.tempcache[fullurl]
  142.             fp = open(filename, 'rb')
  143.             return addinfourl(fp, headers, fullurl)
  144.         type, url = splittype(fullurl)
  145.         if not type:
  146.             type = 'file'
  147.         if self.proxies.has_key(type):
  148.             proxy = self.proxies[type]
  149.             type, proxyhost = splittype(proxy)
  150.             host, selector = splithost(proxyhost)
  151.             url = (host, fullurl) # Signal special case to open_*()
  152.         else:
  153.             proxy = None
  154.         name = 'open_' + type
  155.         self.type = type
  156.         if '-' in name:
  157.             # replace - with _
  158.             name = string.join(string.split(name, '-'), '_')
  159.         if not hasattr(self, name):
  160.             if proxy:
  161.                 return self.open_unknown_proxy(proxy, fullurl, data)
  162.             else:
  163.                 return self.open_unknown(fullurl, data)
  164.         try:
  165.             if data is None:
  166.                 return getattr(self, name)(url)
  167.             else:
  168.                 return getattr(self, name)(url, data)
  169.         except socket.error, msg:
  170.             raise IOError, ('socket error', msg), sys.exc_info()[2]
  171.  
  172.     def open_unknown(self, fullurl, data=None):
  173.         """Overridable interface to open unknown URL type."""
  174.         type, url = splittype(fullurl)
  175.         raise IOError, ('url error', 'unknown url type', type)
  176.  
  177.     def open_unknown_proxy(self, proxy, fullurl, data=None):
  178.         """Overridable interface to open unknown URL type."""
  179.         type, url = splittype(fullurl)
  180.         raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
  181.  
  182.     # External interface
  183.     def retrieve(self, url, filename=None, reporthook=None, data=None):
  184.         """retrieve(url) returns (filename, None) for a local object
  185.         or (tempfilename, headers) for a remote object."""
  186.         url = unwrap(url)
  187.         if self.tempcache and self.tempcache.has_key(url):
  188.             return self.tempcache[url]
  189.         type, url1 = splittype(url)
  190.         if not filename and (not type or type == 'file'):
  191.             try:
  192.                 fp = self.open_local_file(url1)
  193.                 hdrs = fp.info()
  194.                 del fp
  195.                 return url2pathname(splithost(url1)[1]), hdrs
  196.             except IOError, msg:
  197.                 pass
  198.         fp = self.open(url, data)
  199.         headers = fp.info()
  200.         if not filename:
  201.             import tempfile
  202.             garbage, path = splittype(url)
  203.             garbage, path = splithost(path or "")
  204.             path, garbage = splitquery(path or "")
  205.             path, garbage = splitattr(path or "")
  206.             suffix = os.path.splitext(path)[1]
  207.             filename = tempfile.mktemp(suffix)
  208.             self.__tempfiles.append(filename)
  209.         result = filename, headers
  210.         if self.tempcache is not None:
  211.             self.tempcache[url] = result
  212.         tfp = open(filename, 'wb')
  213.         bs = 1024*8
  214.         size = -1
  215.         blocknum = 1
  216.         if reporthook:
  217.             if headers.has_key("content-length"):
  218.                 size = int(headers["Content-Length"])
  219.             reporthook(0, bs, size)
  220.         block = fp.read(bs)
  221.         if reporthook:
  222.             reporthook(1, bs, size)
  223.         while block:
  224.             tfp.write(block)
  225.             block = fp.read(bs)
  226.             blocknum = blocknum + 1
  227.             if reporthook:
  228.                 reporthook(blocknum, bs, size)
  229.         fp.close()
  230.         tfp.close()
  231.         del fp
  232.         del tfp
  233.         return result
  234.  
  235.     # Each method named open_<type> knows how to open that type of URL
  236.  
  237.     def open_http(self, url, data=None):
  238.         """Use HTTP protocol."""
  239.         import httplib
  240.         user_passwd = None
  241.         if type(url) is type(""):
  242.             host, selector = splithost(url)
  243.             if host:
  244.                 user_passwd, host = splituser(host)
  245.                 host = unquote(host)
  246.             realhost = host
  247.         else:
  248.             host, selector = url
  249.             urltype, rest = splittype(selector)
  250.             url = rest
  251.             user_passwd = None
  252.             if string.lower(urltype) != 'http':
  253.                 realhost = None
  254.             else:
  255.                 realhost, rest = splithost(rest)
  256.                 if realhost:
  257.                     user_passwd, realhost = splituser(realhost)
  258.                 if user_passwd:
  259.                     selector = "%s://%s%s" % (urltype, realhost, rest)
  260.             #print "proxy via http:", host, selector
  261.         if not host: raise IOError, ('http error', 'no host given')
  262.         if user_passwd:
  263.             import base64
  264.             auth = string.strip(base64.encodestring(user_passwd))
  265.         else:
  266.             auth = None
  267.         h = httplib.HTTP(host)
  268.         if data is not None:
  269.             h.putrequest('POST', selector)
  270.             h.putheader('Content-type', 'application/x-www-form-urlencoded')
  271.             h.putheader('Content-length', '%d' % len(data))
  272.         else:
  273.             h.putrequest('GET', selector)
  274.         if auth: h.putheader('Authorization', 'Basic %s' % auth)
  275.         if realhost: h.putheader('Host', realhost)
  276.         for args in self.addheaders: apply(h.putheader, args)
  277.         h.endheaders()
  278.         if data is not None:
  279.             h.send(data + '\r\n')
  280.         errcode, errmsg, headers = h.getreply()
  281.         fp = h.getfile()
  282.         if errcode == 200:
  283.             return addinfourl(fp, headers, "http:" + url)
  284.         else:
  285.             if data is None:
  286.                 return self.http_error(url, fp, errcode, errmsg, headers)
  287.             else:
  288.                 return self.http_error(url, fp, errcode, errmsg, headers, data)
  289.  
  290.     def http_error(self, url, fp, errcode, errmsg, headers, data=None):
  291.         """Handle http errors.
  292.         Derived class can override this, or provide specific handlers
  293.         named http_error_DDD where DDD is the 3-digit error code."""
  294.         # First check if there's a specific handler for this error
  295.         name = 'http_error_%d' % errcode
  296.         if hasattr(self, name):
  297.             method = getattr(self, name)
  298.             if data is None:
  299.                 result = method(url, fp, errcode, errmsg, headers)
  300.             else:
  301.                 result = method(url, fp, errcode, errmsg, headers, data)
  302.             if result: return result
  303.         return self.http_error_default(url, fp, errcode, errmsg, headers)
  304.  
  305.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  306.         """Default error handler: close the connection and raise IOError."""
  307.         void = fp.read()
  308.         fp.close()
  309.         raise IOError, ('http error', errcode, errmsg, headers)
  310.  
  311.     if hasattr(socket, "ssl"):
  312.         def open_https(self, url, data=None):
  313.             """Use HTTPS protocol."""
  314.             import httplib
  315.             user_passwd = None
  316.             if type(url) is type(""):
  317.                 host, selector = splithost(url)
  318.                 if host:
  319.                     user_passwd, host = splituser(host)
  320.                     host = unquote(host)
  321.                 realhost = host
  322.             else:
  323.                 host, selector = url
  324.                 urltype, rest = splittype(selector)
  325.                 url = rest
  326.                 user_passwd = None
  327.                 if string.lower(urltype) != 'https':
  328.                     realhost = None
  329.                 else:
  330.                     realhost, rest = splithost(rest)
  331.                     if realhost:
  332.                         user_passwd, realhost = splituser(realhost)
  333.                     if user_passwd:
  334.                         selector = "%s://%s%s" % (urltype, realhost, rest)
  335.                 #print "proxy via https:", host, selector
  336.             if not host: raise IOError, ('https error', 'no host given')
  337.             if user_passwd:
  338.                 import base64
  339.                 auth = string.strip(base64.encodestring(user_passwd))
  340.             else:
  341.                 auth = None
  342.             h = httplib.HTTPS(host, 0,
  343.                               key_file=self.key_file,
  344.                               cert_file=self.cert_file)
  345.             if data is not None:
  346.                 h.putrequest('POST', selector)
  347.                 h.putheader('Content-type',
  348.                             'application/x-www-form-urlencoded')
  349.                 h.putheader('Content-length', '%d' % len(data))
  350.             else:
  351.                 h.putrequest('GET', selector)
  352.             if auth: h.putheader('Authorization: Basic %s' % auth)
  353.             if realhost: h.putheader('Host', realhost)
  354.             for args in self.addheaders: apply(h.putheader, args)
  355.             h.endheaders()
  356.             if data is not None:
  357.                 h.send(data + '\r\n')
  358.             errcode, errmsg, headers = h.getreply()
  359.             fp = h.getfile()
  360.             if errcode == 200:
  361.                 return addinfourl(fp, headers, url)
  362.             else:
  363.                 if data is None:
  364.                     return self.http_error(url, fp, errcode, errmsg, headers)
  365.                 else:
  366.                     return self.http_error(url, fp, errcode, errmsg, headers, data)
  367.  
  368.     def open_gopher(self, url):
  369.         """Use Gopher protocol."""
  370.         import gopherlib
  371.         host, selector = splithost(url)
  372.         if not host: raise IOError, ('gopher error', 'no host given')
  373.         host = unquote(host)
  374.         type, selector = splitgophertype(selector)
  375.         selector, query = splitquery(selector)
  376.         selector = unquote(selector)
  377.         if query:
  378.             query = unquote(query)
  379.             fp = gopherlib.send_query(selector, query, host)
  380.         else:
  381.             fp = gopherlib.send_selector(selector, host)
  382.         return addinfourl(fp, noheaders(), "gopher:" + url)
  383.  
  384.     def open_file(self, url):
  385.         """Use local file or FTP depending on form of URL."""
  386.         if url[:2] == '//' and url[2:3] != '/':
  387.             return self.open_ftp(url)
  388.         else:
  389.             return self.open_local_file(url)
  390.  
  391.     def open_local_file(self, url):
  392.         """Use local file."""
  393.         import mimetypes, mimetools, StringIO
  394.         mtype = mimetypes.guess_type(url)[0]
  395.         headers = mimetools.Message(StringIO.StringIO(
  396.             'Content-Type: %s\n' % (mtype or 'text/plain')))
  397.         host, file = splithost(url)
  398.         if not host:
  399.             urlfile = file
  400.             if file[:1] == '/':
  401.                 urlfile = 'file://' + file
  402.             return addinfourl(open(url2pathname(file), 'rb'),
  403.                               headers, urlfile)
  404.         host, port = splitport(host)
  405.         if not port \
  406.            and socket.gethostbyname(host) in (localhost(), thishost()):
  407.             urlfile = file
  408.             if file[:1] == '/':
  409.                 urlfile = 'file://' + file
  410.             return addinfourl(open(url2pathname(file), 'rb'),
  411.                               headers, urlfile)
  412.         raise IOError, ('local file error', 'not on local host')
  413.  
  414.     def open_ftp(self, url):
  415.         """Use FTP protocol."""
  416.         host, path = splithost(url)
  417.         if not host: raise IOError, ('ftp error', 'no host given')
  418.         host, port = splitport(host)
  419.         user, host = splituser(host)
  420.         if user: user, passwd = splitpasswd(user)
  421.         else: passwd = None
  422.         host = unquote(host)
  423.         user = unquote(user or '')
  424.         passwd = unquote(passwd or '')
  425.         host = socket.gethostbyname(host)
  426.         if not port:
  427.             import ftplib
  428.             port = ftplib.FTP_PORT
  429.         else:
  430.             port = int(port)
  431.         path, attrs = splitattr(path)
  432.         path = unquote(path)
  433.         dirs = string.splitfields(path, '/')
  434.         dirs, file = dirs[:-1], dirs[-1]
  435.         if dirs and not dirs[0]: dirs = dirs[1:]
  436.         if dirs and not dirs[0]: dirs[0] = '/'
  437.         key = user, host, port, string.join(dirs, '/')
  438.         # XXX thread unsafe!
  439.         if len(self.ftpcache) > MAXFTPCACHE:
  440.             # Prune the cache, rather arbitrarily
  441.             for k in self.ftpcache.keys():
  442.                 if k != key:
  443.                     v = self.ftpcache[k]
  444.                     del self.ftpcache[k]
  445.                     v.close()
  446.         try:
  447.             if not self.ftpcache.has_key(key):
  448.                 self.ftpcache[key] = \
  449.                     ftpwrapper(user, passwd, host, port, dirs)
  450.             if not file: type = 'D'
  451.             else: type = 'I'
  452.             for attr in attrs:
  453.                 attr, value = splitvalue(attr)
  454.                 if string.lower(attr) == 'type' and \
  455.                    value in ('a', 'A', 'i', 'I', 'd', 'D'):
  456.                     type = string.upper(value)
  457.             (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  458.             if retrlen is not None and retrlen >= 0:
  459.                 import mimetools, StringIO
  460.                 headers = mimetools.Message(StringIO.StringIO(
  461.                     'Content-Length: %d\n' % retrlen))
  462.             else:
  463.                 headers = noheaders()
  464.             return addinfourl(fp, headers, "ftp:" + url)
  465.         except ftperrors(), msg:
  466.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  467.  
  468.     def open_data(self, url, data=None):
  469.         """Use "data" URL."""
  470.         # ignore POSTed data
  471.         #
  472.         # syntax of data URLs:
  473.         # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
  474.         # mediatype := [ type "/" subtype ] *( ";" parameter )
  475.         # data      := *urlchar
  476.         # parameter := attribute "=" value
  477.         import StringIO, mimetools, time
  478.         try:
  479.             [type, data] = string.split(url, ',', 1)
  480.         except ValueError:
  481.             raise IOError, ('data error', 'bad data URL')
  482.         if not type:
  483.             type = 'text/plain;charset=US-ASCII'
  484.         semi = string.rfind(type, ';')
  485.         if semi >= 0 and '=' not in type[semi:]:
  486.             encoding = type[semi+1:]
  487.             type = type[:semi]
  488.         else:
  489.             encoding = ''
  490.         msg = []
  491.         msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
  492.                                             time.gmtime(time.time())))
  493.         msg.append('Content-type: %s' % type)
  494.         if encoding == 'base64':
  495.             import base64
  496.             data = base64.decodestring(data)
  497.         else:
  498.             data = unquote(data)
  499.         msg.append('Content-length: %d' % len(data))
  500.         msg.append('')
  501.         msg.append(data)
  502.         msg = string.join(msg, '\n')
  503.         f = StringIO.StringIO(msg)
  504.         headers = mimetools.Message(f, 0)
  505.         f.fileno = None     # needed for addinfourl
  506.         return addinfourl(f, headers, url)
  507.  
  508.  
  509. class FancyURLopener(URLopener):
  510.     """Derived class with handlers for errors we can handle (perhaps)."""
  511.  
  512.     def __init__(self, *args):
  513.         apply(URLopener.__init__, (self,) + args)
  514.         self.auth_cache = {}
  515.  
  516.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  517.         """Default error handling -- don't raise an exception."""
  518.         return addinfourl(fp, headers, "http:" + url)
  519.  
  520.     def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
  521.         """Error 302 -- relocated (temporarily)."""
  522.         # XXX The server can force infinite recursion here!
  523.         if headers.has_key('location'):
  524.             newurl = headers['location']
  525.         elif headers.has_key('uri'):
  526.             newurl = headers['uri']
  527.         else:
  528.             return
  529.         void = fp.read()
  530.         fp.close()
  531.         # In case the server sent a relative URL, join with original:
  532.         newurl = basejoin("http:" + url, newurl)
  533.         if data is None:
  534.             return self.open(newurl)
  535.         else:
  536.             return self.open(newurl, data)
  537.  
  538.     def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
  539.         """Error 301 -- also relocated (permanently)."""
  540.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  541.  
  542.     def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
  543.         """Error 401 -- authentication required.
  544.         See this URL for a description of the basic authentication scheme:
  545.         http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt"""
  546.         if headers.has_key('www-authenticate'):
  547.             stuff = headers['www-authenticate']
  548.             import re
  549.             match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  550.             if match:
  551.                 scheme, realm = match.groups()
  552.                 if string.lower(scheme) == 'basic':
  553.                    name = 'retry_' + self.type + '_basic_auth'
  554.                    if data is None:
  555.                        return getattr(self,name)(url, realm)
  556.                    else:
  557.                        return getattr(self,name)(url, realm, data)
  558.  
  559.     def retry_http_basic_auth(self, url, realm, data=None):
  560.         host, selector = splithost(url)
  561.         i = string.find(host, '@') + 1
  562.         host = host[i:]
  563.         user, passwd = self.get_user_passwd(host, realm, i)
  564.         if not (user or passwd): return None
  565.         host = user + ':' + passwd + '@' + host
  566.         newurl = 'http://' + host + selector
  567.         if data is None:
  568.             return self.open(newurl)
  569.         else:
  570.             return self.open(newurl, data)
  571.  
  572.     def retry_https_basic_auth(self, url, realm, data=None):
  573.             host, selector = splithost(url)
  574.             i = string.find(host, '@') + 1
  575.             host = host[i:]
  576.             user, passwd = self.get_user_passwd(host, realm, i)
  577.             if not (user or passwd): return None
  578.             host = user + ':' + passwd + '@' + host
  579.             newurl = '//' + host + selector
  580.             return self.open_https(newurl)
  581.  
  582.     def get_user_passwd(self, host, realm, clear_cache = 0):
  583.         key = realm + '@' + string.lower(host)
  584.         if self.auth_cache.has_key(key):
  585.             if clear_cache:
  586.                 del self.auth_cache[key]
  587.             else:
  588.                 return self.auth_cache[key]
  589.         user, passwd = self.prompt_user_passwd(host, realm)
  590.         if user or passwd: self.auth_cache[key] = (user, passwd)
  591.         return user, passwd
  592.  
  593.     def prompt_user_passwd(self, host, realm):
  594.         """Override this in a GUI environment!"""
  595.         import getpass
  596.         try:
  597.             user = raw_input("Enter username for %s at %s: " % (realm,
  598.                                                                 host))
  599.             passwd = getpass.getpass("Enter password for %s in %s at %s: " %
  600.                 (user, realm, host))
  601.             return user, passwd
  602.         except KeyboardInterrupt:
  603.             print
  604.             return None, None
  605.  
  606.  
  607. # Utility functions
  608.  
  609. _localhost = None
  610. def localhost():
  611.     """Return the IP address of the magic hostname 'localhost'."""
  612.     global _localhost
  613.     if not _localhost:
  614.         _localhost = socket.gethostbyname('localhost')
  615.     return _localhost
  616.  
  617. _thishost = None
  618. def thishost():
  619.     """Return the IP address of the current host."""
  620.     global _thishost
  621.     if not _thishost:
  622.         _thishost = socket.gethostbyname(socket.gethostname())
  623.     return _thishost
  624.  
  625. _ftperrors = None
  626. def ftperrors():
  627.     """Return the set of errors raised by the FTP class."""
  628.     global _ftperrors
  629.     if not _ftperrors:
  630.         import ftplib
  631.         _ftperrors = ftplib.all_errors
  632.     return _ftperrors
  633.  
  634. _noheaders = None
  635. def noheaders():
  636.     """Return an empty mimetools.Message object."""
  637.     global _noheaders
  638.     if not _noheaders:
  639.         import mimetools
  640.         import StringIO
  641.         _noheaders = mimetools.Message(StringIO.StringIO(), 0)
  642.         _noheaders.fp.close()   # Recycle file descriptor
  643.     return _noheaders
  644.  
  645.  
  646. # Utility classes
  647.  
  648. class ftpwrapper:
  649.     """Class used by open_ftp() for cache of open FTP connections."""
  650.  
  651.     def __init__(self, user, passwd, host, port, dirs):
  652.         self.user = user
  653.         self.passwd = passwd
  654.         self.host = host
  655.         self.port = port
  656.         self.dirs = dirs
  657.         self.init()
  658.  
  659.     def init(self):
  660.         import ftplib
  661.         self.busy = 0
  662.         self.ftp = ftplib.FTP()
  663.         self.ftp.connect(self.host, self.port)
  664.         self.ftp.login(self.user, self.passwd)
  665.         for dir in self.dirs:
  666.             self.ftp.cwd(dir)
  667.  
  668.     def retrfile(self, file, type):
  669.         import ftplib
  670.         self.endtransfer()
  671.         if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
  672.         else: cmd = 'TYPE ' + type; isdir = 0
  673.         try:
  674.             self.ftp.voidcmd(cmd)
  675.         except ftplib.all_errors:
  676.             self.init()
  677.             self.ftp.voidcmd(cmd)
  678.         conn = None
  679.         if file and not isdir:
  680.             # Use nlst to see if the file exists at all
  681.             try:
  682.                 self.ftp.nlst(file)
  683.             except ftplib.error_perm, reason:
  684.                 raise IOError, ('ftp error', reason), sys.exc_info()[2]
  685.             # Restore the transfer mode!
  686.             self.ftp.voidcmd(cmd)
  687.             # Try to retrieve as a file
  688.             try:
  689.                 cmd = 'RETR ' + file
  690.                 conn = self.ftp.ntransfercmd(cmd)
  691.             except ftplib.error_perm, reason:
  692.                 if reason[:3] != '550':
  693.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  694.         if not conn:
  695.             # Set transfer mode to ASCII!
  696.             self.ftp.voidcmd('TYPE A')
  697.             # Try a directory listing
  698.             if file: cmd = 'LIST ' + file
  699.             else: cmd = 'LIST'
  700.             conn = self.ftp.ntransfercmd(cmd)
  701.         self.busy = 1
  702.         # Pass back both a suitably decorated object and a retrieval length
  703.         return (addclosehook(conn[0].makefile('rb'),
  704.                              self.endtransfer), conn[1])
  705.     def endtransfer(self):
  706.         if not self.busy:
  707.             return
  708.         self.busy = 0
  709.         try:
  710.             self.ftp.voidresp()
  711.         except ftperrors():
  712.             pass
  713.  
  714.     def close(self):
  715.         self.endtransfer()
  716.         try:
  717.             self.ftp.close()
  718.         except ftperrors():
  719.             pass
  720.  
  721. class addbase:
  722.     """Base class for addinfo and addclosehook."""
  723.  
  724.     def __init__(self, fp):
  725.         self.fp = fp
  726.         self.read = self.fp.read
  727.         self.readline = self.fp.readline
  728.         if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
  729.         if hasattr(self.fp, "fileno"): self.fileno = self.fp.fileno
  730.  
  731.     def __repr__(self):
  732.         return '<%s at %s whose fp = %s>' % (self.__class__.__name__,
  733.                                              `id(self)`, `self.fp`)
  734.  
  735.     def close(self):
  736.         self.read = None
  737.         self.readline = None
  738.         self.readlines = None
  739.         self.fileno = None
  740.         if self.fp: self.fp.close()
  741.         self.fp = None
  742.  
  743. class addclosehook(addbase):
  744.     """Class to add a close hook to an open file."""
  745.  
  746.     def __init__(self, fp, closehook, *hookargs):
  747.         addbase.__init__(self, fp)
  748.         self.closehook = closehook
  749.         self.hookargs = hookargs
  750.  
  751.     def close(self):
  752.         addbase.close(self)
  753.         if self.closehook:
  754.             apply(self.closehook, self.hookargs)
  755.             self.closehook = None
  756.             self.hookargs = None
  757.  
  758. class addinfo(addbase):
  759.     """class to add an info() method to an open file."""
  760.  
  761.     def __init__(self, fp, headers):
  762.         addbase.__init__(self, fp)
  763.         self.headers = headers
  764.  
  765.     def info(self):
  766.         return self.headers
  767.  
  768. class addinfourl(addbase):
  769.     """class to add info() and geturl() methods to an open file."""
  770.  
  771.     def __init__(self, fp, headers, url):
  772.         addbase.__init__(self, fp)
  773.         self.headers = headers
  774.         self.url = url
  775.  
  776.     def info(self):
  777.         return self.headers
  778.  
  779.     def geturl(self):
  780.         return self.url
  781.  
  782.  
  783. def basejoin(base, url):
  784.     """Utility to combine a URL with a base URL to form a new URL."""
  785.     type, path = splittype(url)
  786.     if type:
  787.         # if url is complete (i.e., it contains a type), return it
  788.         return url
  789.     host, path = splithost(path)
  790.     type, basepath = splittype(base) # inherit type from base
  791.     if host:
  792.         # if url contains host, just inherit type
  793.         if type: return type + '://' + host + path
  794.         else:
  795.             # no type inherited, so url must have started with //
  796.             # just return it
  797.             return url
  798.     host, basepath = splithost(basepath) # inherit host
  799.     basepath, basetag = splittag(basepath) # remove extraneous cruft
  800.     basepath, basequery = splitquery(basepath) # idem
  801.     if path[:1] != '/':
  802.         # non-absolute path name
  803.         if path[:1] in ('#', '?'):
  804.             # path is just a tag or query, attach to basepath
  805.             i = len(basepath)
  806.         else:
  807.             # else replace last component
  808.             i = string.rfind(basepath, '/')
  809.         if i < 0:
  810.             # basepath not absolute
  811.             if host:
  812.                 # host present, make absolute
  813.                 basepath = '/'
  814.             else:
  815.                 # else keep non-absolute
  816.                 basepath = ''
  817.         else:
  818.             # remove last file component
  819.             basepath = basepath[:i+1]
  820.         # Interpret ../ (important because of symlinks)
  821.         while basepath and path[:3] == '../':
  822.             path = path[3:]
  823.             i = string.rfind(basepath[:-1], '/')
  824.             if i > 0:
  825.                 basepath = basepath[:i+1]
  826.             elif i == 0:
  827.                 basepath = '/'
  828.                 break
  829.             else:
  830.                 basepath = ''
  831.  
  832.         path = basepath + path
  833.     if type and host: return type + '://' + host + path
  834.     elif type: return type + ':' + path
  835.     elif host: return '//' + host + path # don't know what this means
  836.     else: return path
  837.  
  838.  
  839. # Utilities to parse URLs (most of these return None for missing parts):
  840. # unwrap('<URL:type://host/path>') --> 'type://host/path'
  841. # splittype('type:opaquestring') --> 'type', 'opaquestring'
  842. # splithost('//host[:port]/path') --> 'host[:port]', '/path'
  843. # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
  844. # splitpasswd('user:passwd') -> 'user', 'passwd'
  845. # splitport('host:port') --> 'host', 'port'
  846. # splitquery('/path?query') --> '/path', 'query'
  847. # splittag('/path#tag') --> '/path', 'tag'
  848. # splitattr('/path;attr1=value1;attr2=value2;...') ->
  849. #   '/path', ['attr1=value1', 'attr2=value2', ...]
  850. # splitvalue('attr=value') --> 'attr', 'value'
  851. # splitgophertype('/Xselector') --> 'X', 'selector'
  852. # unquote('abc%20def') -> 'abc def'
  853. # quote('abc def') -> 'abc%20def')
  854.  
  855. def unwrap(url):
  856.     """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
  857.     url = string.strip(url)
  858.     if url[:1] == '<' and url[-1:] == '>':
  859.         url = string.strip(url[1:-1])
  860.     if url[:4] == 'URL:': url = string.strip(url[4:])
  861.     return url
  862.  
  863. _typeprog = None
  864. def splittype(url):
  865.     """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  866.     global _typeprog
  867.     if _typeprog is None:
  868.         import re
  869.         _typeprog = re.compile('^([^/:]+):')
  870.  
  871.     match = _typeprog.match(url)
  872.     if match:
  873.         scheme = match.group(1)
  874.         return scheme.lower(), url[len(scheme) + 1:]
  875.     return None, url
  876.  
  877. _hostprog = None
  878. def splithost(url):
  879.     """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  880.     global _hostprog
  881.     if _hostprog is None:
  882.         import re
  883.         _hostprog = re.compile('^//([^/]*)(.*)$')
  884.  
  885.     match = _hostprog.match(url)
  886.     if match: return match.group(1, 2)
  887.     return None, url
  888.  
  889. _userprog = None
  890. def splituser(host):
  891.     """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  892.     global _userprog
  893.     if _userprog is None:
  894.         import re
  895.         _userprog = re.compile('^([^@]*)@(.*)$')
  896.  
  897.     match = _userprog.match(host)
  898.     if match: return map(unquote, match.group(1, 2))
  899.     return None, host
  900.  
  901. _passwdprog = None
  902. def splitpasswd(user):
  903.     """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  904.     global _passwdprog
  905.     if _passwdprog is None:
  906.         import re
  907.         _passwdprog = re.compile('^([^:]*):(.*)$')
  908.  
  909.     match = _passwdprog.match(user)
  910.     if match: return match.group(1, 2)
  911.     return user, None
  912.  
  913. # splittag('/path#tag') --> '/path', 'tag'
  914. _portprog = None
  915. def splitport(host):
  916.     """splitport('host:port') --> 'host', 'port'."""
  917.     global _portprog
  918.     if _portprog is None:
  919.         import re
  920.         _portprog = re.compile('^(.*):([0-9]+)$')
  921.  
  922.     match = _portprog.match(host)
  923.     if match: return match.group(1, 2)
  924.     return host, None
  925.  
  926. _nportprog = None
  927. def splitnport(host, defport=-1):
  928.     """Split host and port, returning numeric port.
  929.     Return given default port if no ':' found; defaults to -1.
  930.     Return numerical port if a valid number are found after ':'.
  931.     Return None if ':' but not a valid number."""
  932.     global _nportprog
  933.     if _nportprog is None:
  934.         import re
  935.         _nportprog = re.compile('^(.*):(.*)$')
  936.  
  937.     match = _nportprog.match(host)
  938.     if match:
  939.         host, port = match.group(1, 2)
  940.         try:
  941.             if not port: raise string.atoi_error, "no digits"
  942.             nport = string.atoi(port)
  943.         except string.atoi_error:
  944.             nport = None
  945.         return host, nport
  946.     return host, defport
  947.  
  948. _queryprog = None
  949. def splitquery(url):
  950.     """splitquery('/path?query') --> '/path', 'query'."""
  951.     global _queryprog
  952.     if _queryprog is None:
  953.         import re
  954.         _queryprog = re.compile('^(.*)\?([^?]*)$')
  955.  
  956.     match = _queryprog.match(url)
  957.     if match: return match.group(1, 2)
  958.     return url, None
  959.  
  960. _tagprog = None
  961. def splittag(url):
  962.     """splittag('/path#tag') --> '/path', 'tag'."""
  963.     global _tagprog
  964.     if _tagprog is None:
  965.         import re
  966.         _tagprog = re.compile('^(.*)#([^#]*)$')
  967.  
  968.     match = _tagprog.match(url)
  969.     if match: return match.group(1, 2)
  970.     return url, None
  971.  
  972. def splitattr(url):
  973.     """splitattr('/path;attr1=value1;attr2=value2;...') ->
  974.         '/path', ['attr1=value1', 'attr2=value2', ...]."""
  975.     words = string.splitfields(url, ';')
  976.     return words[0], words[1:]
  977.  
  978. _valueprog = None
  979. def splitvalue(attr):
  980.     """splitvalue('attr=value') --> 'attr', 'value'."""
  981.     global _valueprog
  982.     if _valueprog is None:
  983.         import re
  984.         _valueprog = re.compile('^([^=]*)=(.*)$')
  985.  
  986.     match = _valueprog.match(attr)
  987.     if match: return match.group(1, 2)
  988.     return attr, None
  989.  
  990. def splitgophertype(selector):
  991.     """splitgophertype('/Xselector') --> 'X', 'selector'."""
  992.     if selector[:1] == '/' and selector[1:2]:
  993.         return selector[1], selector[2:]
  994.     return None, selector
  995.  
  996. def unquote(s):
  997.     """unquote('abc%20def') -> 'abc def'."""
  998.     mychr = chr
  999.     myatoi = string.atoi
  1000.     list = string.split(s, '%')
  1001.     res = [list[0]]
  1002.     myappend = res.append
  1003.     del list[0]
  1004.     for item in list:
  1005.         if item[1:2]:
  1006.             try:
  1007.                 myappend(mychr(myatoi(item[:2], 16))
  1008.                      + item[2:])
  1009.             except:
  1010.                 myappend('%' + item)
  1011.         else:
  1012.             myappend('%' + item)
  1013.     return string.join(res, "")
  1014.  
  1015. def unquote_plus(s):
  1016.     """unquote('%7e/abc+def') -> '~/abc def'"""
  1017.     if '+' in s:
  1018.         # replace '+' with ' '
  1019.         s = string.join(string.split(s, '+'), ' ')
  1020.     return unquote(s)
  1021.  
  1022. always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  1023.                'abcdefghijklmnopqrstuvwxyz'
  1024.                '0123456789' '_.-')
  1025.  
  1026. _fast_safe_test = always_safe + '/'
  1027. _fast_safe = None
  1028.  
  1029. def _fast_quote(s):
  1030.     global _fast_safe
  1031.     if _fast_safe is None:
  1032.         _fast_safe = {}
  1033.         for c in _fast_safe_test:
  1034.             _fast_safe[c] = c
  1035.     res = list(s)
  1036.     for i in range(len(res)):
  1037.         c = res[i]
  1038.         if not _fast_safe.has_key(c):
  1039.             res[i] = '%%%02x' % ord(c)
  1040.     return string.join(res, '')
  1041.  
  1042. def quote(s, safe = '/'):
  1043.     """quote('abc def') -> 'abc%20def'
  1044.  
  1045.     Each part of a URL, e.g. the path info, the query, etc., has a
  1046.     different set of reserved characters that must be quoted.
  1047.  
  1048.     RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
  1049.     the following reserved characters.
  1050.  
  1051.     reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  1052.                   "$" | ","
  1053.  
  1054.     Each of these characters is reserved in some component of a URL,
  1055.     but not necessarily in all of them.
  1056.  
  1057.     By default, the quote function is intended for quoting the path
  1058.     section of a URL.  Thus, it will not encode '/'.  This character
  1059.     is reserved, but in typical usage the quote function is being
  1060.     called on a path where the existing slash characters are used as
  1061.     reserved characters.
  1062.     """
  1063.     safe = always_safe + safe
  1064.     if _fast_safe_test == safe:
  1065.         return _fast_quote(s)
  1066.     res = list(s)
  1067.     for i in range(len(res)):
  1068.         c = res[i]
  1069.         if c not in safe:
  1070.             res[i] = '%%%02x' % ord(c)
  1071.     return string.join(res, '')
  1072.  
  1073. def quote_plus(s, safe = ''):
  1074.     """Quote the query fragment of a URL; replacing ' ' with '+'"""
  1075.     if ' ' in s:
  1076.         l = string.split(s, ' ')
  1077.         for i in range(len(l)):
  1078.             l[i] = quote(l[i], safe)
  1079.         return string.join(l, '+')
  1080.     else:
  1081.         return quote(s, safe)
  1082.  
  1083. def urlencode(dict):
  1084.     """Encode a dictionary of form entries into a URL query string."""
  1085.     l = []
  1086.     for k, v in dict.items():
  1087.         k = quote_plus(str(k))
  1088.         v = quote_plus(str(v))
  1089.         l.append(k + '=' + v)
  1090.     return string.join(l, '&')
  1091.  
  1092. # Proxy handling
  1093. def getproxies_environment():
  1094.     """Return a dictionary of scheme -> proxy server URL mappings.
  1095.  
  1096.     Scan the environment for variables named <scheme>_proxy;
  1097.     this seems to be the standard convention.  If you need a
  1098.     different way, you can pass a proxies dictionary to the
  1099.     [Fancy]URLopener constructor.
  1100.  
  1101.     """
  1102.     proxies = {}
  1103.     for name, value in os.environ.items():
  1104.         name = string.lower(name)
  1105.         if value and name[-6:] == '_proxy':
  1106.             proxies[name[:-6]] = value
  1107.     return proxies
  1108.  
  1109. if os.name == 'mac':
  1110.     def getproxies():
  1111.         """Return a dictionary of scheme -> proxy server URL mappings.
  1112.  
  1113.         By convention the mac uses Internet Config to store
  1114.         proxies.  An HTTP proxy, for instance, is stored under
  1115.         the HttpProxy key.
  1116.  
  1117.         """
  1118.         try:
  1119.             import ic
  1120.         except ImportError:
  1121.             return {}
  1122.  
  1123.         try:
  1124.             config = ic.IC()
  1125.         except ic.error:
  1126.             return {}
  1127.         proxies = {}
  1128.         # HTTP:
  1129.         if config.has_key('UseHTTPProxy') and config['UseHTTPProxy']:
  1130.             try:
  1131.                 value = config['HTTPProxyHost']
  1132.             except ic.error:
  1133.                 pass
  1134.             else:
  1135.                 proxies['http'] = 'http://%s' % value
  1136.         # FTP: XXXX To be done.
  1137.         # Gopher: XXXX To be done.
  1138.         return proxies
  1139.  
  1140. elif os.name == 'nt':
  1141.     def getproxies_registry():
  1142.         """Return a dictionary of scheme -> proxy server URL mappings.
  1143.  
  1144.         Win32 uses the registry to store proxies.
  1145.  
  1146.         """
  1147.         proxies = {}
  1148.         try:
  1149.             import _winreg
  1150.         except ImportError:
  1151.             # Std module, so should be around - but you never know!
  1152.             return proxies
  1153.         try:
  1154.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
  1155.                 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
  1156.             proxyEnable = _winreg.QueryValueEx(internetSettings,
  1157.                                                'ProxyEnable')[0]
  1158.             if proxyEnable:
  1159.                 # Returned as Unicode but problems if not converted to ASCII
  1160.                 proxyServer = str(_winreg.QueryValueEx(internetSettings,
  1161.                                                        'ProxyServer')[0])
  1162.                 if '=' in proxyServer:
  1163.                     # Per-protocol settings
  1164.                     for p in proxyServer.split(';'):
  1165.                         protocol, address = p.split('=', 1)
  1166.                         proxies[protocol] = '%s://%s' % (protocol, address)
  1167.                 else:
  1168.                     # Use one setting for all protocols
  1169.                     if proxyServer[:5] == 'http:':
  1170.                         proxies['http'] = proxyServer
  1171.                     else:
  1172.                         proxies['http'] = 'http://%s' % proxyServer
  1173.                         proxies['ftp'] = 'ftp://%s' % proxyServer
  1174.             internetSettings.Close()
  1175.         except (WindowsError, ValueError, TypeError):
  1176.             # Either registry key not found etc, or the value in an
  1177.             # unexpected format.
  1178.             # proxies already set up to be empty so nothing to do
  1179.             pass
  1180.         return proxies
  1181.  
  1182.     def getproxies():
  1183.         """Return a dictionary of scheme -> proxy server URL mappings.
  1184.  
  1185.         Returns settings gathered from the environment, if specified,
  1186.         or the registry.
  1187.  
  1188.         """
  1189.         return getproxies_environment() or getproxies_registry()
  1190. else:
  1191.     # By default use environment variables
  1192.     getproxies = getproxies_environment
  1193.  
  1194.  
  1195. # Test and time quote() and unquote()
  1196. def test1():
  1197.     import time
  1198.     s = ''
  1199.     for i in range(256): s = s + chr(i)
  1200.     s = s*4
  1201.     t0 = time.time()
  1202.     qs = quote(s)
  1203.     uqs = unquote(qs)
  1204.     t1 = time.time()
  1205.     if uqs != s:
  1206.         print 'Wrong!'
  1207.     print `s`
  1208.     print `qs`
  1209.     print `uqs`
  1210.     print round(t1 - t0, 3), 'sec'
  1211.  
  1212.  
  1213. def reporthook(blocknum, blocksize, totalsize):
  1214.     # Report during remote transfers
  1215.     print "Block number: %d, Block size: %d, Total size: %d" % (blocknum, blocksize, totalsize)
  1216.  
  1217. # Test program
  1218. def test(args=[]):
  1219.     if not args:
  1220.         args = [
  1221.             '/etc/passwd',
  1222.             'file:/etc/passwd',
  1223.             'file://localhost/etc/passwd',
  1224.             'ftp://ftp.python.org/etc/passwd',
  1225. ##          'gopher://gopher.micro.umn.edu/1/',
  1226.             'http://www.python.org/index.html',
  1227.             ]
  1228.         if hasattr(URLopener, "open_https"):
  1229.             args.append('https://synergy.as.cmu.edu/~geek/')
  1230.     try:
  1231.         for url in args:
  1232.             print '-'*10, url, '-'*10
  1233.             fn, h = urlretrieve(url, None, reporthook)
  1234.             print fn, h
  1235.             if h:
  1236.                 print '======'
  1237.                 for k in h.keys(): print k + ':', h[k]
  1238.                 print '======'
  1239.             fp = open(fn, 'rb')
  1240.             data = fp.read()
  1241.             del fp
  1242.             if '\r' in data:
  1243.                 table = string.maketrans("", "")
  1244.                 data = string.translate(data, table, "\r")
  1245.             print data
  1246.             fn, h = None, None
  1247.         print '-'*40
  1248.     finally:
  1249.         urlcleanup()
  1250.  
  1251. def main():
  1252.     import getopt, sys
  1253.     try:
  1254.         opts, args = getopt.getopt(sys.argv[1:], "th")
  1255.     except getopt.error, msg:
  1256.         print msg
  1257.         print "Use -h for help"
  1258.         return
  1259.     t = 0
  1260.     for o, a in opts:
  1261.         if o == '-t':
  1262.             t = t + 1
  1263.         if o == '-h':
  1264.             print "Usage: python urllib.py [-t] [url ...]"
  1265.             print "-t runs self-test;",
  1266.             print "otherwise, contents of urls are printed"
  1267.             return
  1268.     if t:
  1269.         if t > 1:
  1270.             test1()
  1271.         test(args)
  1272.     else:
  1273.         if not args:
  1274.             print "Use -h for help"
  1275.         for url in args:
  1276.             print urlopen(url).read(),
  1277.  
  1278. # Run test program when run as a script
  1279. if __name__ == '__main__':
  1280.     main()
  1281.