11"""Download bytes from a URL with a size cap, and resolve the content format."""
22
33import logging
4+ import re
45import time
56from pathlib import Path
67from typing import Optional
1920 "application/xml" : "xml" ,
2021 "text/xml" : "xml" ,
2122 "text/plain" : "text" ,
23+ "image/svg+xml" : "svg" ,
2224}
2325
2426_SUFFIX_FORMATS = {
2729 ".htm" : "html" ,
2830 ".xml" : "xml" ,
2931 ".txt" : "text" ,
32+ ".svg" : "svg" ,
3033}
3134
35+ #: How much of a payload :func:`sniff_format` reads to find an XML root element.
36+ SNIFF_WINDOW = 64 * 1024
37+
38+ #: The first element of an XML document, past its declaration, comments,
39+ #: processing instructions and doctype.
40+ _ROOT_ELEMENT = re .compile (rb"<([A-Za-z_][\w.:-]*)" )
41+
3242
3343def sniff_format (data : bytes ) -> Optional [str ]:
3444 """Identify a format from the leading bytes of a payload, or ``None`` if unknown.
@@ -46,6 +56,14 @@ def sniff_format(data: bytes) -> Optional[str]:
4656 'html'
4757 >>> sniff_format(b"<?xml version='1.0'?><article/>")
4858 'xml'
59+ >>> sniff_format(b'<svg xmlns="http://www.w3.org/2000/svg"/>')
60+ 'svg'
61+ >>> sniff_format(b"<?xml version='1.0'?><!-- by Inkscape --><svg/>")
62+ 'svg'
63+ >>> sniff_format(b"<!-- Created with Inkscape -->\\ n<svg/>")
64+ 'svg'
65+ >>> sniff_format(b'\\ xef\\ xbb\\ xbf<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "x"><svg/>')
66+ 'svg'
4967 >>> sniff_format(b"just some text") is None
5068 True
5169 >>> sniff_format(b"") is None
@@ -58,11 +76,64 @@ def sniff_format(data: bytes) -> Optional[str]:
5876 head = data [:512 ].lstrip ().lower ()
5977 if head .startswith (b"<!doctype html" ) or head .startswith (b"<html" ):
6078 return "html"
79+ # A byte order mark is not markup; Illustrator writes one, and a bare
80+ # <!DOCTYPE svg ...> with no XML declaration.
81+ prolog = head .removeprefix (b"\xef \xbb \xbf " )
82+ prolog_starts = (b"<svg" , b"<?xml" , b"<!--" , b"<!doctype svg" )
83+ if prolog .startswith (prolog_starts ) and _root_element (data ) in (b"svg" , b"svg:svg" ):
84+ return "svg"
6185 if head .startswith (b"<?xml" ):
6286 return "xml"
6387 return None
6488
6589
90+ def _root_element (data : bytes ) -> Optional [bytes ]:
91+ """Name the root element of an XML payload from its first 64 KB, lowercased.
92+
93+ The window is wide because exporters put licence comments and doctypes
94+ with internal subsets ahead of the root. A comment, declaration or
95+ doctype the window cuts off is still not markup, so nothing after its
96+ start is read as the root; the root is then unknown.
97+
98+ Examples:
99+ >>> _root_element(b'<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY a "b">]><svg/>')
100+ b'svg'
101+ >>> _root_element(b"<!-- <svg> in a comment --><article/>")
102+ b'article'
103+ >>> _root_element(b"<!-- cut off by the window <svg>") is None
104+ True
105+ """
106+ head = data [:SNIFF_WINDOW ]
107+ position = 0
108+ # One forward scan, so a window of unterminated "<!--" stays linear.
109+ while (start := head .find (b"<" , position )) != - 1 :
110+ if head .startswith (b"<!--" , start ):
111+ end , closing = head .find (b"-->" , start + 4 ), 3
112+ elif head .startswith (b"<?" , start ):
113+ end , closing = head .find (b"?>" , start + 2 ), 2
114+ elif head [start : start + 9 ].upper () == b"<!DOCTYPE" :
115+ end , closing = _doctype_end (head , start + 9 ), 1
116+ else :
117+ match = _ROOT_ELEMENT .match (head , start )
118+ return match .group (1 ).lower () if match else None
119+ if end == - 1 :
120+ return None
121+ position = end + closing
122+ return None
123+
124+
125+ def _doctype_end (head : bytes , position : int ) -> int :
126+ """Index of the ``>`` closing a doctype, past any internal subset; -1 if absent."""
127+ close = head .find (b">" , position )
128+ subset = head .find (b"[" , position )
129+ if subset != - 1 and (close == - 1 or subset < close ):
130+ subset_end = head .find (b"]" , subset )
131+ if subset_end == - 1 :
132+ return - 1
133+ close = head .find (b">" , subset_end )
134+ return close
135+
136+
66137def resolve_format (
67138 content_type : Optional [str ], url : Optional [str ], format_hint : Optional [str ]
68139) -> Optional [str ]:
0 commit comments