1
1
mirror of https://github.com/Kozea/WeasyPrint.git synced 2024-10-04 07:57:52 +03:00
WeasyPrint/weasyprint/urls.py

277 lines
9.7 KiB
Python
Raw Normal View History

2022-02-14 09:11:30 +03:00
"""Various utility functions and classes for URL management."""
2018-01-14 03:48:17 +03:00
import codecs
2017-03-25 02:33:36 +03:00
import contextlib
import os.path
import re
import sys
import traceback
2017-03-25 02:33:36 +03:00
import zlib
2018-01-14 03:48:17 +03:00
from gzip import GzipFile
2022-02-14 07:59:23 +03:00
from pathlib import Path
2018-01-14 04:09:25 +03:00
from urllib.parse import quote, unquote, urljoin, urlsplit
from urllib.request import Request, pathname2url, urlopen
2020-05-30 02:27:13 +03:00
from . import __version__
2017-03-25 02:33:36 +03:00
from .logger import LOGGER
# See https://stackoverflow.com/a/11687993/1162888
# Both are needed in Python 3 as the re module does not like to mix
# https://datatracker.ietf.org/doc/html/rfc3986#section-3.1
UNICODE_SCHEME_RE = re.compile('^([a-zA-Z][a-zA-Z0-9.+-]+):')
BYTES_SCHEME_RE = re.compile(b'^([a-zA-Z][a-zA-Z0-9.+-]+):')
2020-01-02 15:25:19 +03:00
# getfilesystemencoding() on Linux is sometimes stupid…
2018-01-14 03:48:17 +03:00
FILESYSTEM_ENCODING = sys.getfilesystemencoding()
2020-01-13 23:26:49 +03:00
try: # pragma: no cover
2018-01-14 03:48:17 +03:00
if codecs.lookup(FILESYSTEM_ENCODING).name == 'ascii':
FILESYSTEM_ENCODING = 'utf-8'
2020-01-13 23:26:49 +03:00
except LookupError: # pragma: no cover
2018-01-14 03:48:17 +03:00
FILESYSTEM_ENCODING = 'utf-8'
2020-01-02 15:25:19 +03:00
HTTP_HEADERS = {
2020-05-30 02:27:13 +03:00
'User-Agent': f'WeasyPrint {__version__}',
2020-01-02 15:25:19 +03:00
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
}
2018-01-14 03:48:17 +03:00
class StreamingGzipFile(GzipFile):
def __init__(self, fileobj):
GzipFile.__init__(self, fileobj=fileobj)
self.fileobj_to_close = fileobj
def close(self):
GzipFile.close(self)
self.fileobj_to_close.close()
2024-07-28 19:13:23 +03:00
def seekable(self):
return False
2018-01-14 03:48:17 +03:00
def iri_to_uri(url):
2020-01-02 15:25:19 +03:00
"""Turn a Unicode IRI into an ASCII-only URI that conforms to RFC 3986."""
if url.startswith('data:'):
# Data URIs can be huge, but dont need this anyway.
return url
# Use UTF-8 as per RFC 3987 (IRI), except for file://
2020-01-02 15:25:19 +03:00
url = url.encode(
FILESYSTEM_ENCODING if url.startswith('file:') else 'utf-8')
# This is a full URI, not just a component. Only %-encode characters
# that are not allowed at all in URIs. Everthing else is "safe":
# * Reserved characters: /:?#[]@!$&'()*+,;=
# * Unreserved characters: ASCII letters, digits and -._~
# Of these, only '~' is not in urllibs "always safe" list.
# * '%' to avoid double-encoding
2012-05-18 19:54:10 +04:00
return quote(url, safe=b"/:?#[]@!$&'()*+,;=~%")
2011-12-16 15:19:10 +04:00
def path2url(path):
"""Return file URL of `path`.
2020-01-02 15:25:19 +03:00
2022-02-14 07:59:23 +03:00
Accepts 'str', 'bytes' or 'Path', returns 'str'.
2020-01-02 15:25:19 +03:00
"""
# Ensure 'str'
2022-02-14 07:59:23 +03:00
if isinstance(path, Path):
path = str(path)
elif isinstance(path, bytes):
2020-01-02 15:25:19 +03:00
path = path.decode(FILESYSTEM_ENCODING)
# If a trailing path.sep is given, keep it
wants_trailing_slash = path.endswith(os.path.sep) or path.endswith('/')
path = os.path.abspath(path)
if wants_trailing_slash or os.path.isdir(path):
# Make sure directory names have a trailing slash.
# Otherwise relative URIs are resolved from the parent directory.
path += os.path.sep
wants_trailing_slash = True
path = pathname2url(path)
2020-01-02 15:25:19 +03:00
# On Windows pathname2url cuts off trailing slash
if wants_trailing_slash and not path.endswith('/'):
path += '/' # pragma: no cover
if path.startswith('///'):
# On Windows pathname2url(r'C:\foo') is apparently '///C:/foo'
# That enough slashes already.
return f'file:{path}' # pragma: no cover
else:
2021-01-21 14:42:25 +03:00
return f'file://{path}'
def url_is_absolute(url):
2020-01-02 15:25:19 +03:00
"""Return whether an URL (bytes or string) is absolute."""
scheme = UNICODE_SCHEME_RE if isinstance(url, str) else BYTES_SCHEME_RE
return bool(scheme.match(url))
def get_url_attribute(element, attr_name, base_url, allow_relative=False):
"""Get the URI corresponding to the ``attr_name`` attribute.
Return ``None`` if:
* the attribute is empty or missing or,
* the value is a relative URI but the document has no base URI and
``allow_relative`` is ``False``.
2011-08-19 18:53:05 +04:00
Otherwise return an URI, absolute if possible.
2011-08-19 18:53:05 +04:00
2011-08-09 14:45:51 +04:00
"""
value = element.get(attr_name, '').strip()
if value:
return url_join(
base_url or '', value, allow_relative, '<%s %s="%s">',
2017-07-01 01:28:14 +03:00
(element.tag, attr_name, value))
def url_join(base_url, url, allow_relative, context, context_args):
"""Like urllib.urljoin, but warn if base_url is required but missing."""
if url_is_absolute(url):
return iri_to_uri(url)
elif base_url:
return iri_to_uri(urljoin(base_url, url))
elif allow_relative:
return iri_to_uri(url)
else:
2020-01-02 15:25:19 +03:00
LOGGER.error(
2021-01-21 14:42:25 +03:00
f'Relative URI reference without a base URI: {context}',
2020-01-02 15:25:19 +03:00
*context_args)
return None
2011-08-09 14:45:51 +04:00
2011-08-05 13:16:44 +04:00
def get_link_attribute(element, attr_name, base_url):
2020-01-02 15:25:19 +03:00
"""Get the URL value of an element attribute.
Return ``('external', absolute_uri)``, or ``('internal',
unquoted_fragment_id)``, or ``None``.
"""
attr_value = element.get(attr_name, '').strip()
if attr_value.startswith('#') and len(attr_value) > 1:
# Do not require a base_url when the value is just a fragment.
return ('url', ('internal', unquote(attr_value[1:])))
uri = get_url_attribute(element, attr_name, base_url, allow_relative=True)
if uri:
if base_url:
try:
parsed = urlsplit(uri)
except ValueError:
LOGGER.warning('Malformed URL: %s', uri)
else:
try:
parsed_base = urlsplit(base_url)
except ValueError:
LOGGER.warning('Malformed base URL: %s', base_url)
else:
# Compare with fragments removed
if parsed.fragment and parsed[:-1] == parsed_base[:-1]:
return ('url', ('internal', unquote(parsed.fragment)))
return ('url', ('external', uri))
2011-08-19 18:53:05 +04:00
def ensure_url(string):
"""Get a ``scheme://path`` URL from ``string``.
If ``string`` looks like an URL, return it unchanged. Otherwise assume a
filename and convert it to a ``file://`` URL.
2011-08-09 14:45:51 +04:00
"""
return string if url_is_absolute(string) else path2url(string)
def default_url_fetcher(url, timeout=10, ssl_context=None):
"""Fetch an external resource such as an image or stylesheet.
2012-10-08 21:51:18 +04:00
Another callable with the same signature can be given as the
``url_fetcher`` argument to :class:`HTML` or :class:`CSS`.
2021-02-18 23:03:40 +03:00
(See :ref:`URL Fetchers`.)
:param str url:
The URL of the resource to fetch.
:param int timeout:
The number of seconds before HTTP requests are dropped.
:param ssl.SSLContext ssl_context:
An SSL context used for HTTP requests.
:raises: An exception indicating failure, e.g. :obj:`ValueError` on
2017-04-29 11:41:53 +03:00
syntactically invalid URL.
:returns: A :obj:`dict` with the following keys:
* One of ``string`` (a :obj:`bytestring <bytes>`) or ``file_obj``
(a :term:`file object`).
* Optionally: ``mime_type``, a MIME type extracted e.g. from a
*Content-Type* header. If not provided, the type is guessed from the
file extension in the URL.
* Optionally: ``encoding``, a character encoding extracted e.g. from a
*charset* parameter in a *Content-Type* header
2015-07-01 02:01:43 +03:00
* Optionally: ``redirected_url``, the actual URL of the resource
if there were e.g. HTTP redirects.
* Optionally: ``filename``, the filename of the resource. Usually
derived from the *filename* parameter in a *Content-Disposition*
header
If a ``file_obj`` key is given, it is the callers responsibility
to call ``file_obj.close()``. The default function used internally to
fetch data in WeasyPrint tries to close the file object after
retreiving; but if this URL fetcher is used elsewhere, the file object
has to be closed manually.
2011-12-08 19:31:03 +04:00
"""
2018-01-14 03:48:17 +03:00
if UNICODE_SCHEME_RE.match(url):
# See https://bugs.python.org/issue34702
if url.startswith('file://'):
url = url.split('?')[0]
url = iri_to_uri(url)
2020-01-02 15:25:19 +03:00
response = urlopen(
Request(url, headers=HTTP_HEADERS), timeout=timeout,
context=ssl_context)
2018-01-14 03:48:17 +03:00
response_info = response.info()
2020-01-02 15:25:19 +03:00
result = {
'redirected_url': response.geturl(),
'mime_type': response_info.get_content_type(),
'encoding': response_info.get_param('charset'),
'filename': response_info.get_filename(),
}
2018-01-14 03:48:17 +03:00
content_encoding = response_info.get('Content-Encoding')
if content_encoding == 'gzip':
2020-01-13 23:26:49 +03:00
result['file_obj'] = StreamingGzipFile(fileobj=response)
elif content_encoding == 'deflate':
data = response.read()
try:
result['string'] = zlib.decompress(data)
except zlib.error:
# Try without zlib header or checksum
result['string'] = zlib.decompress(data, -15)
else:
result['file_obj'] = response
return result
2020-01-13 23:26:49 +03:00
else: # pragma: no cover
2012-07-13 14:24:55 +04:00
raise ValueError('Not an absolute URI: %r' % url)
class URLFetchingError(IOError):
"""Some error happened when fetching an URL."""
@contextlib.contextmanager
def fetch(url_fetcher, url):
"""Call an url_fetcher, fill in optional data, and clean up."""
try:
result = url_fetcher(url)
2020-05-30 16:48:24 +03:00
except Exception as exception:
raise URLFetchingError(f'{type(exception).__name__}: {exception}')
result.setdefault('redirected_url', url)
2013-06-20 15:26:12 +04:00
result.setdefault('mime_type', None)
if 'file_obj' in result:
try:
yield result
finally:
try:
result['file_obj'].close()
2020-01-13 23:26:49 +03:00
except Exception: # pragma: no cover
# May already be closed or something.
# This is just cleanup anyway: log but make it non-fatal.
2020-01-13 23:26:49 +03:00
LOGGER.warning(
'Error when closing stream for %s:\n%s',
url, traceback.format_exc())
else:
yield result